text:
Q: Differences in reading private key with libp11 and pkcs11-engine I'm trying to implement SSL client authentication in C++ using credentials stored on a smartcard.
In essence, this means using the openssl library to initialize an SSL context using a certificate and a private key, then using this context for all future https connections.
The libraries i've come across to help me with this are libp11 and its pkcs11-engine module, found here: https://github.com/OpenSC/libp11 .
A scenario in which my code actually works as intended with our webserver is where the certificate is listed and retrieved via libp11 and the private key is retrieved by id using the pkcs11 engine:
PKCS11_enumerate_certs(slot->token, &certs, &ncerts);

X509 *cert = certs[0].x509;

EVP_PKEY *pkey = ENGINE_load_private_key(pkcs11_eng, "pkey_id", NULL, NULL);

if (!SSL_CTX_use_certificate(context->ctx, cert )) {
    throw SSLError::getLastError();
}
if (!SSL_CTX_use_PrivateKey(context->ctx, pkey )) {
    throw SSLError::getLastError();
}
if (!SSL_CTX_check_private_key(context->ctx)) {
    throw SSLError::getLastError();
}

However, for consistency and to keep things simple, it is preferred to use libp11 for both of these retrievals as this would also eliminate the use of a whole other component (the pkcs11-engine).
The issue i'm having is that when retrieving pkey with:
PKCS11_KEY *key = PKCS11_find_key(&certs[0]);
EVP_PKEY pkey = PKCS11_get_private_key(key)

And initializing ssl, the checks pass, but the following error is  thrown by the SSL_connect() function:
error:80009005:Vendor defined:PKCS11_rsa_encrypt:General Error
Basically the private key works when it's retrieved via engine but an error is thrown when using libp11, which is strange because looking through the code on github for the engine, i noticed the same p11 calls being made that i was using.
If anyone has any experience with this topic and might know what's going on here, it would help me enormously.

A: This was my bad. I was initializing the pkcs11 engine with our own dll implementing pkcs11 but using the opensc dll when initializing p11. I guess the lesson learned here is always look carefully before copy/pasting code


text:
Q: How to install apps in Microsoft store using SYSTEM account? My requirement is to install apps in Microsoft store using SYSTEM account. But they are all getting installed only using admin user privileges. When I tried to install an app in Microsoft store using Add-AppxPackage utility with SYSTEM user, I'm getting the following error.

**PS C:\Windows\system32> Add-AppxPackage -Path C:\Path to file.appxbundle -Verbose VERBOSE: Performing the operation "Deploy
package" on target "C:\Path to file.appxbundle". Add-AppxPackage :
Deployment failed with HRESULT: 0x80073CF9, Install failed. Please
contact your software vendor. (Exception from HRESULT: 0x80073CF9)
Deployment Add operation rejected on package
Microsoft.RemoteDesktop_2020.1208.2040.0_neutral_~_8wekyb3d8bbwe from:
Microsoft.RemoteDesktop_2020.1208.2040.0_neutral___8wekyb3d8bbwe.appxbundle
install request because the Local System account is not allowed to
perform this operation. NOTE: For additional information, look for
[ActivityId] bc984532-ed5b-0000-41db-98bc5bedd601 in the Event Log or
use the command line Get-AppPackageLog -ActivityID
bc984532-ed5b-0000-41db-98bc5bedd601 At line:1 char:1

*

*Add-AppxPackage -Path C:\Path to file ...

*
  + CategoryInfo          : WriteError: (C:\Path to file...bbwe.appxbundle:String) [Add-AppxPackage], IOException
  + FullyQualifiedErrorId : DeploymentError,Microsoft.Windows.Appx.PackageManager.Commands.AddAppxPackageCommand

VERBOSE: Operation completed for:
C:\Path to file.appxbundle**
Is there any way, I can install these application using SYSTEM account?

redpajama_set_name: RedPajamaStackExchange


text:
Q: OffsetDateTime customer parser Hello I try parse String 20110330174824917 to OffsetDateTime using DateTimeFormatter so
 public static void main(String[] args)  {
       // System.out.println(OffsetDateTime.parse("20110330174824917", DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")));
        System.out.println(LocalDateTime.parse("20110330174824917", DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")));
    }

but I get
Exception in thread "main" java.time.format.DateTimeParseException: Text '20110330174824917' could not be parsed, unparsed text found at index 8
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1952)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)

Hey guys it looks like this problem is related with java 8
https://bugs.openjdk.java.net/browse/JDK-8031085
Thank you all for help

A: DateTimeFormatter#withZone
Your date-time string does not have timezone information and therefore, in order to parse it into OffsetDateTime, you need to pass the timezone information explicitly. You can use DateTimeFormatter#withZone to parse the date-time string into ZonedDateTime which you can convert to OffsetDateTime using ZonedDateTime#toOffsetDateTime.
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String strDateTime = "20110330174824917";

        // Change the ZoneId as per your requirement e.g. ZoneId.of("Europe/London")
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS", Locale.ENGLISH)
                                                .withZone(ZoneId.systemDefault());

        OffsetDateTime odt = ZonedDateTime.parse(strDateTime, dtf)
                                            .toOffsetDateTime();
        System.out.println(odt);
    }
}

Output:
2011-03-30T17:48:24.917+01:00

A: You can define the used Zone for the Formatter and concatenate the input string with the correct Zone Offset
// note the added Z at the end of the pattern for the offset
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSSZ").withZone(ZoneId.of("UTC"));

OffsetDateTime dateTime = OffsetDateTime.parse("20110330174824917" + "+0000", formatter);


text:
Q: Is there a way to set the indices of a multi index DataFrame? I am attempting to create a multi index dataframe which contains every possible index even ones where it does not currently contain values. I wish to set these non-existent values to 0. To achieve this, I used the following:
index_levels = ['Channel', 'Duration', 'Designation', 'Manufacturing Class']

grouped_df = df.groupby(by = index_levels)[['Total Purchases', 'Sales', 'Cost']].agg('sum')

grouped_df = grouped_df.reindex(pd.MultiIndex.from_product(grouped_df.index.levels), fill_value = 0)

The expected result:
 ___________________________________________________________________________________________
|Chan. | Duration   | Designation|    Manufact. |Total Purchases|  Sales      |   Cost      |
|______|____________|____________|______________|_______________|_____________|_____________|
|      | Month      | Special    |    Brand     |    0          |  0.00       |    0.00     |
|      |            |            |______________|_______________|_____________|_____________|
|      |            |            |    Generic   |    1567       | 16546.07    |   16000.00  |
|Retail|____________|____________|______________|_______________|_____________|_____________|
|      | Season     |Not Special |    Brand     |     351       | 13246.00    |   15086.26  |
|      |            |            |______________|_______________|_____________|_____________|
|      |            |            |    Generic   |     0         |  0.00       |    0.00     |
|______|____________|____________|______________|_______________|_____________|_____________|

This result is produced when at least one of the index levels contains a value. However, if the index level does not contain any value, then the following result is produced below.
___________________________________________________________________________________________
|Chan. | Duration   | Designation|    Manufact. |Total Purchases|  Sales      |   Cost      |
|______|____________|____________|______________|_______________|_____________|_____________|
|      | Monthly    |   Special  |    Generic   |    1567       | 16546.07    |   16000.00  |
|Retail|____________|____________|______________|_______________|_____________|_____________|
|      | Season     |Not Special |    Brand     |     351       | 13246.00    |   15086.26  |
|______|____________|____________|______________|_______________|_____________|_____________|

For some reason, the values continue to be autotruncated. How can I fix indices so that the desired result is always produced and I can always reliably use these indices for calculations, even when said indices have no values in them?

A: You should change the reindex part, as pd.MultiIndex.from_product() should take as input the original dataframe indexes (by giving grouped_df.index.levels as input you pass only the indexes resulting after the groupby).
This is a solution that wuold work:
full_idx = [df[col].dropna().unique() for col in index_levels]
grouped_df = grouped_df.reindex(pd.MultiIndex.from_product(full_idx), fill_value = 0)

If you are also interested in NaN categories, you should remove dropna() when defining the full indexes.


text:
Q: SQL Server 2008R2 trigger sometimes doesn't fire We use wireless barcode scanners to scan our goods as they wind their way around the factory, scanning each product at fifteen separate checkpoints.  After passing through a checkpoint, the product gets a STATUS ID which corresponds to the relevant checkpoint.
The scanners pass the status ID, Barcode of the product, Scanner name, and date/time to a table called HW_SCANNER_TRANSACTIONS and the trigger then updates other tables before updating the original table with a date and time that the trigger ran.
Recently, we have been seeing errors where the data is verified as in the scanner_transactions table but has not updated the other tables.  There appears to be no pattern to these.
USE [DBMAIN]
GO
/****** Object:  Trigger [dbo].[TRANSACTIONS_InsertTrigger]    Script Date: 09/02/2015 09:02:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[TRANSACTIONS_InsertTrigger]
ON [dbo].[HW_SCANNER_TRANSACTIONS]
AFTER INSERT
AS

BEGIN

SET NOCOUNT ON
UPDATE [GLA_FRAME_LABEL]
SET ITEM_STATUS_ID =  inserted.StatusID
FROM inserted
WHERE substring(inserted.[BarcodeID],2,15) = [GLA_FRAME_LABEL].[LABEL_ID]

UPDATE [QUOTE_ITEM]
SET ITEM_STATUS_ID  =  inserted.StatusID
FROM inserted
WHERE [QUOTE_ITEM_ID] =  (SELECT QUOTE_ITEM.QUOTE_ITEM_ID FROM QUOTE_ITEM INNER JOIN GLA_FRAME_LABEL ON
QUOTE_ITEM.QUOTE_ITEM_ID = GLA_FRAME_LABEL.QUOTE_ITEM_ID WHERE (GLA_FRAME_LABEL.LABEL_ID = SUBSTRING ( inserted .BarcodeID,2,15)))

UPDATE [GLA_FRAME_LABEL]
SET ITEM_STATUS_ID  =  inserted.StatusID
FROM inserted
WHERE [QUOTE_ITEM_ID]  =  (SELECT QUOTE_ITEM_ID FROM GLA_FRAME_LABEL WHERE LABEL_ID = SUBSTRING ( inserted .BarcodeID,2,15))
AND QTY_COUNT = (SELECT QTY_COUNT FROM GLA_FRAME_LABEL Where LABEL_ID = SUBSTRING ( inserted .BarcodeID,2,15))

UPDATE [HW_SCANNER_TRANSACTIONS]
SET [Synched] = GETUTCDATE()
FROM inserted
WHERE inserted.idx =[HW_SCANNER_TRANSACTIONS].[idx]

END;

When the errors occur, the only update that runs is the final one in the list which updates the transaction table synch date to say that it's been run.
I'm at a loss to explain why and wondering if there was anything wrong or needed adding to my trigger to make it work.


text:
Q: Entity Framework property required error for properties set in insert procedure I am using the Entity Framework (5.0.0) for a web site, and have an object that I am trying to insert via stored procedure. The object has some properties that do not need to be set upon insertion, as they are set by the stored procedure. The columns for these properties are set as NOT NULL in the database. Entity Framework is complaining that one of these properties is required, which I believe has to do with them not being set upon insertion.
Is there something I am missing, or not fully understanding? Or maybe my design is flawed? Thanks!

A: If you're using EF code first you probably have a [Required] attribute on that property. Just remove it and you should be fine.
If you're using EF model first then the property was inferred to be required because it is NOT NULL in the database. Change the Nullable setting for that column in the EDMX (essentially lying to EF) and EF should stop complaining.

A: I managed to find exactly what I was looking for. I scoured for what seemed like an eternity trying to find this, and I'm not sure how I missed it, but anyway, it goes as follows:
When viewing the Properties of a given column in the EDMX, there's a property called "StoreGeneratedPattern". Essentially, this is an enumeration declaring different behaviors of the specified column during insert and update procedures. The options are None, Computed, and Identity.
I initially didn't think this was what I wanted, since these columns are not identity columns, nor are they computed columns. However, that is not what the options are referring to, they just happen to share the same name. In my situation, Identity allows me to specify a value that is generated on insert and remains unchanged on update (per the documentation).
You can find out more about these options here.


text:
Q: JSON and serialization : lnvalid reference to this expression. fetch data form firebase as firestore database? import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:json_annotation/json_annotation.dart';

@JsonSerializable()
class MyCard {
  String name;
  String desc;
  String image;
  String flav;
  double price;

  MyCard(this.name, this.desc, this.image, this.flav, this.price);
  factory MyCard.Food(name, desc, image, flav, price) =>
      MyCard(name, desc, image, flav, price);
  MyCard.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        desc = json['desc'],
        image = json['image'],
        flav = json['flav'],
        price = json['price'];
}
@JsonSerializable()
class Food extends MyCard {
  @override
  String name;
  @override
  String desc;
  @override
  String image;
  @override
  String flav;
  @override
  double price;

  Food(
      {required this.name,
      required this.desc,
      required this.image,
      required this.flav,
      required this.price})
      : super(name, desc, image, flav, price);

  static Food _$FoodFromJson(Map<String, dynamic> json) => Food(
  name: json['name'] as String,
  desc: json['desc'] as String,
  image: json['image'] as String,
  flav: json['flav'] as String,
  price: json['price'] as double,
);

 static Map<String, dynamic> _$FoodToJson(Food instance) => <String, dynamic>{
      'name': instance.name,
      'desc': instance.desc,
      'image': instance.image,
      'flav': instance.flav,
      'price': instance.price,
    };

  factory Food.fromJson(Map<String, dynamic> json)=> _$FoodFromJson(json);
  static Map<String, dynamic> toJson() => _$FoodToJson(this);

  final FoodRef = FirebaseFirestore.instance.collection('listfood').withConverter<Food>(
      fromFirestore: (snapshot, _) => Food.fromJson(snapshot.data()!),
      toFirestore: (food, _) => Food.toJson(),
    );

  static var foodList = [
    Food(
      name: 'Fraise Cream',
      desc:
          'We have been loading up on the stone fruit and berries at the market. We have no self control to these summer gems. We have gross we can out of hand, our  Strawberry...',
      price: 2.50,
      image: 'assets/images/food1.png',
      flav: 'Strawberry Flovour Sweet Ice Cream',
    ),
    Food(
      name: 'Mandarine',
      desc:
          'We have been loading up on the stone fruit and berries at the market. We have no self control to these summer gems. We have gross we can out of hand, our  Strawberry...',
      price: 3.50,
      image: 'assets/images/food2.png',
      flav: 'Caramel Flovour Sweet Ice Cream',
    )
  ];
}

class Beverage extends MyCard {
  @override
  String name;
  @override
  String desc;
  @override
  String image;
  @override
  String flav;
  @override
  double price;

  Beverage(
      {required this.name,
      required this.desc,
      required this.image,
      required this.flav,
      required this.price})
      : super(name, desc, image, flav, price);

  static var beverageList = [
    Beverage(
      name: 'test',
      desc: 'We have test',
      image: 'assets/images/food1.png',
      price: 3.0,
      flav: 'Strawberry test',
    ),
  ];
}

Error straight error _$FoodToJson(this);
static Map<String, dynamic> toJson() => _$FoodToJson(this);
Which I myself do not know where I went wrong. And can the code fetch data from the database? I'm a newbie. Because someone said that it can fetch data from database like doc[index]["name"] to replace name in foodlist.
If solve the error of line static Map<String, dynamic> toJson() => _$FoodToJson(this); Is it possible to use Food.toJson().name like the code below?
static var foodList = [
    Food(
      name: Food.toJson().name,
      desc: Food.toJson().desc,
      price: Food.toJson().price
      image: Food.toJson().image,
      flav: Food.toJson().flav,
    ),
]

A: Firstly you have configured @JsonSerializable incorrectly I will recommend you to go through this video which explains how to configure @JsonSerializable with build_runner.  Run flutter pub run build_runner build every time when you make changes in the models file.
I have recreated the issue in my setup and found that to use @JsonSerializable() on inherited classes we have to use @JsonSerializable(explicitToJson: true) refer this answer from similar thread.
I have updated your code and posted in this gist: models.dart. Run flutter pub run build_runner build then import this file wherever you want and use firebase withConvertor as following:
import './models.dart';
void call() async {
    final foodRef =
        FirebaseFirestore.instance.collection('listfood').withConverter<Food>(
              fromFirestore: (snapshot, _) => Food.fromJson(snapshot.data()!),
              toFirestore: (food, _) => food.foodtoJson(),
            );
    await foodRef.add(Food(
      name: 'Mandarine',
      desc:
          'We have been loading up on the stone fruit and berries at the market. We have no self control over these summer gems. We have gross we can out of hand, our  Strawberry...',
      price: 3.50,
      image: 'assets/images/food2.png',
      flav: 'Caramel Flavour Sweet Ice Cream',
    )); //adding a sample document for testing

    await foodRef.get().then((QuerySnapshot snapshot) => {
          snapshot.docs.forEach((doc) {
            print(doc["name"]);
            print(doc["desc"]);
            print(doc["price"]);
            print(doc["image"]);
            print(doc["flav"]);
          })
        });
  }

You may need to make changes in the above according to your requirement.
For more information follow the official flutterfire documentation and for @JsonSerializable go through this thread


text:
Q: Make multiple means from one column with pandas With Python 3.10
Sample data:
import pandas as pd

data = [[1, 14890, 3], [4, 5, 6], [7, 8, 9], [11, 13, 14], [12, 0, 18], [87, None, 54], [1, 0, 3], [4, 5, 6], [7, 8, 9],
        [11, 13, 14], [12, 0, 18], [87, None, 54], [1, 0, 3], [4, 5, 6], [7, 8, 9], [11, 13, 14], [12, 0, 18],
        [87,10026, 54]]
df = pd.DataFrame(data, columns=['column', 'data', 'something'])
print(df)
df = df.mask(df == 0).fillna(df.mean())
print(df)    # <---this works but you will see what I mean about looking off..

Updated Solution:
df = pd.DataFrame(data, columns=['column', 'data', 'something'])
df['ma'] = round(df['data'].rolling(4, 1).apply(lambda x: np.nanmean(x)), 2)
df['final2'] = np.where(df['data'] > 0, df['data'], df['ma'])
print(df)
# it replaces the zeros and NULLS with a value, (sometimes it fits well, sometimes, not so much).

The idea is I have one or more column(s) with bad or missing data.

*

*If I use .fillna(df.mean()) for this it sticks out like a sore thumb.

*My Goal is to have a percentage of the total number of elements in the dataframe column to make the new mean from...

*I would like to take a len(df)*0.30 (30%) and use divide it in half.

*I would collect half the numbers above the index point where the (null/0/bad data) data exists.

*I would collect half the numbers below the index where the

*These collected elements would be the be used to calculate the missing or bad index point.
This would be more helpful if there were a data set that irregular or had missing bad data

A: You can take a rolling mean with min periods = 1 to smooth out the data.
or you can do a variant of this method to customise what you want.
Inside the lambda i used this np.nanmean(x).
import pandas as pd
import numpy as np

data = [[1, 14890, 3], [4, 5, 6], [7, 8, 9], [11, 13, 14], [12, 0, 18], [87, None, 54], [1, 0, 3], [4, 5, 6], [7, 8, 9],
        [11, 13, 14], [12, 0, 18], [87, None, 54], [1, 0, 3], [4, 5, 6], [7, 8, 9], [11, 13, 14], [12, 0, 18],
        [87,10026, 54]]
df = pd.DataFrame(data, columns=['column', 'data', 'something'])
df['ma'] = df['data'].rolling(3,1).apply(lambda x : np.nanmean(x))
df['final'] = np.where(df['data'] >= 0, df['data'], df['ma'])

print(df)

result:
    column     data  something            ma    final
0        1  14890.0          3  14890.000000  14890.0
1        4      5.0          6   7447.500000      5.0
2        7      8.0          9   4967.666667      8.0
3       11     13.0         14      8.666667     13.0
4       12      0.0         18      7.000000      0.0
5       87      NaN         54      6.500000      6.5
6        1      0.0          3      0.000000      0.0
7        4      5.0          6      2.500000      5.0
8        7      8.0          9      4.333333      8.0
9       11     13.0         14      8.666667     13.0
10      12      0.0         18      7.000000      0.0
11      87      NaN         54      6.500000      6.5
12       1      0.0          3      0.000000      0.0
13       4      5.0          6      2.500000      5.0
14       7      8.0          9      4.333333      8.0
15      11     13.0         14      8.666667     13.0
16      12      0.0         18      7.000000      0.0
17      87  10026.0         54   3346.333333  10026.0


text:
Q: componentWillUnmount & Warning: setState(...): error I'm having an issue when I use a navigate away from this component in react I get this error: warning.js:36 Warning: setState(...): "Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the ProjectsHeader component."
Now I've looked over the docs for componentWillUnmount which states "Invoked immediately before a component is unmounted from the DOM.
Perform any necessary cleanup in this method, such as invalidating timers or cleaning up any DOM elements that were created in componentDidMount."
The problem is that I don't know how to do that. I've looked at the other Stack overflow examples and I don't understand them and can't figure it out. There doesn't seem to be a good enough example for me to understand how to do it. I understand the lifecycle I just don't know how to execute it.
Here is my code:
import React from 'react';
import jQuery from 'jquery';
import $ from 'jquery';

import ProjectsHeaderLinks from "./ProjectsHeaderLinks.jsx";

export default class ProjectsHeader extends React.Component {

    constructor() {
        super()
        this.state = {
            class: "not-sticky-div",
            class2: "hidden-span",
            class3: "false"
        }
    }

    componentDidMount() {
        this.scrollTop();

    }

    componentWillUnmount(){
        this.scrollTop = null;
        console.log("unmounted");
    }

    scrollTop(){
        var that = this;
        let head = $(".header");
        let stick = "sticky";
        let projHead = document.getElementById("projHead");
    $(window).scroll(function() {
        $(window).scrollTop() > 400
            ? head.addClass(stick)
            : head.removeClass(stick);
        let newValue = projHead.classList.value.split(' ', 2);
        for (var i = 0; i < newValue.length; i++) {
            newValue[i] === "sticky"
                ? that.setState({class: "sticky-div", class2: "visible-span", class3: "true"})
                : that.setState({class: "not-sticky-div", class2: "hidden-span", class3: "true"});
            }
        })
    }

    render() {
        return (

                {this.state.class === "not-sticky-div"
                 ?
"This is My Projects Page" --Lonnie McGill

                 :
 <ProjectsHeaderLinks/>

            }

        )
    }
}

A: To solve the issue put:
componentWillUnmount(){
    $(window).unbind("scroll");
}


text:
Q: Has anyone successfully used Reverse with namespaces, rest_framework and host patterns? I have literally been trying to solve/ignore this issue for months now but I cannot test properly nor move on until I do. I've tried using namespaces and hard-coding but I still get the same error. 'django.urls.exceptions.NoReverseMatch: 'users' is not a registered namespace'
If you can see a solution that I cannot, please assist me. I have attached the url files and test that is giving me the error. I have tried changing the app_name, namespace, url name; adding and removing said variables...same issue no matter what. I'm stumped . Thank you in advance!
Test:
from rest_framework.test import APITestCase
from django.urls import reverse
from users.models import Feedback

class TestFeedbackAPI(APITestCase):
    def test_post_request_can_create_new_entity(self):
        data = {
            'subject': 'Test',
            'message': 'Testing on these hoes',
        }
        self.client.post(reverse('users:post_user_feedback'), data=data)
        self.assertEqual(Feedback.objects.count(), 1)

App named Users urls:
from django.urls import path
from .views import ProfileDetail, SettingsDetail, FeedbackDetail

app_name = 'users'

urlpatterns = [
    # path("create/", views.UserCreate.as_view()),  # Sign up view, POST
    path('profile/', ProfileDetail.as_view(),
         name='get_user_profile'),
    path('settings/', SettingsDetail.as_view(),
         name='get_user_settings'),
    path('support/', FeedbackDetail.as_view(),
         name='post_user_feedback'),
]

Api urls:
"""busTracker API URL Configuration"""

from django.urls import include, path

urlpatterns = [
    path("auth/", include("djoser.urls")),
    path("auth/", include("djoser.urls.authtoken")),
    path('', include('core.urls', namespace='core')),
    path('', include('users.urls', namespace='users')),
]

Host file:
from django.conf import settings
from django_hosts import patterns, host

host_patterns = patterns(
    "",
    host(r"www", "busTracker.template_urls", name="www"),
    host(r"console", settings.ROOT_URLCONF, name="console"),
    host(r"api", "busTracker.api_urls", name="api"),
)

Main url file (only used for admin):
"""busTracker URL Configuration"""

from django.contrib import admin
from django.urls import include, path

app_name = "console"

urlpatterns = [
    path("", admin.site.urls),
]

Full Error trace:
ERROR: test_post_request_can_create_new_entity (tests.test_request.TestFeedbackAPI)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/kappalucky/Documents/Projects/TransportLLC-backend/venv/lib/python3.8/site-packages/django/urls/base.py", line 72, in reverse
    extra, resolver = resolver.namespace_dict[ns]
KeyError: 'users'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/kappalucky/Documents/Projects/TransportLLC-backend/tests/test_request.py", line 12, in test_post_request_can_create_new_entity
    self.client.post(reverse('users:post_user_feedback'), data=data)
  File "/Users/kappalucky/Documents/Projects/TransportLLC-backend/venv/lib/python3.8/site-packages/django/urls/base.py", line 83, in reverse
    raise NoReverseMatch("%s is not a registered namespace" % key)
django.urls.exceptions.NoReverseMatch: 'users' is not a registered namespace

A: So i actually figured it out on my own after digging deep into all of the documentation. I was using from django.urls import reverse when I should have been using the django-host provided from django_hosts.resolvers import reverse. This allows me to include the host path so the reverse will look like this reverse('users:post_user_feedback', host="api"), data=data).


text:
Q: Can't change the Anchors in Faster RCNN I'm a newbie in pytorch and I was trying to put some custom anchors on my Faster RCNN network in pytorch. Basically, I'm using a resnet50 backbone and when I try to put the anchors, I got a mismatch error.
This is the code that I have:
backbone = torchvision.models.detection.backbone_utils.resnet_fpn_backbone('resnet50', True)
backbone.out_channels = 256

anchor_generator = AnchorGenerator(sizes=((4, 8, 16, 32, 64, 128),),
                                    aspect_ratios=((0.5, 1.0, 2.0),))

roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=[0],
                                                    output_size=7,
                                                    sampling_ratio=2)

model = FasterRCNN(backbone,
                   num_classes=10,
                   rpn_anchor_generator=anchor_generator,
                   box_roi_pool=roi_pooler)

The error that I got is the following: shape '[1440000, -1]' is invalid for input of size 7674336.

A: Alright, after some digging into the source code of PyTorch Faster RCNN, I found how they initialize the anchors:
anchor_sizes = ((32,), (64,), (128,), (256,), (512,))
            aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes)

rpn_anchor_generator = AnchorGenerator(
                anchor_sizes, aspect_ratios
            )

Following the same pattern for my custom anchors, the code will be:
anchor_sizes = ((4,), (8,), (16,), (32,), (64,), (128,))
            aspect_ratios = ((0.5, 1.0, 2.0),) * len(anchor_sizes)

rpn_anchor_generator = AnchorGenerator(
                anchor_sizes, aspect_ratios
            )

It will work!


text:
Q: OrCAD PCB Designer PSpice Automatic Route
The Automatic Route on the OrCAD PCB Designer, is always drawing a line width of 0.1270 (default), but i need a line width of 0.5000, like is shown on options menu and inside the red oval on this image, the NINV yellow line is 0.5000 because i did manually "Add Connect F3", but for some reason the Automatic Route always draw yellow lines width of 0.1270, the problem here is for example in this Capacitor C1, 3 lines are passing between Pin 1 and Pin 2, which is impossible for me to implement that in a real circuit board, only one line at max is allowed to pass between Pin 1 and Pin 2 on this Capacitor C1.
So my question is in what menus do i change the line width of Automatic Route ?

A: The stock auto router is not that great as people have mentioned.  I've seen it done well by guys who put a lot of time into it but it's often more work than is worth it for one off designs. Basically you have to constrain the heck out of it.  So have you tried going into constraint manager and setting either the default trace width or the trace width for that net and then running auto router?
It's under Setup->Constraints.  Then choose the physical section on the right hand side and you'll get a table for all routes or you can select Net and assign constraints to individual nets.  Orcad PCB/Allegro is all about setting constraints on your nets.  Things like width, number of vias, impedance, etc.  The fancier the package you own the more advanced the constraints you can set.  The better you constrain your design the better the autorouter will perform.


text:
Q: .libPaths not accurately directing install.packages I am confused!
I have just done a R and Rstudio reinstall on a work computer (where I am not administrator). I have added to the Environmental Variables R_LIBS_USER = "C:/Users/USER.NAME/Documents/R/win-library/3.2"as the location for my library.
at the console when I type:
.libPaths()

It returns:
[1] "C:/Users/USER.NAME/Documents/R/win-library/3.2" "C:/Program        Files/R/R-3.2.2/library"

As I read the the install.packages should default to install to the first path. However, when I run
install.packages("the package")

or
 install.packages("the package", lib = "C:/Users/USER.NAME/Documents/R/win-library/3.2")

it returns:
Error in install.packages : path[1]="C:\Users\USER.NAME\Documents\.Rhistory\win-library\3.2": The system cannot find the path specified

it seems that ".Rhistory" is replacing "R" in the path.  Why?
> sessionInfo()

R version 3.2.2 (2015-08-14)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1


text:
Q: How do I mark an issue as closed on Azure Boards? How do I mark an issue as closed after I complete it?
The status says 'Development hasn't started' because I don't see a way to change the status of that to 'In Progress'.
It tells me something called Create a Branch, which I don't use. I am a single person developer, and even though the project will be open source, I only have a master branch.
Is there a way to mark it as completed? I have the code checked in, all I want to do now is mark it as closed and move on to my next issue.
Why isn't the status just a Drop Down I can set?

A: That isn't the issue status.  The field you are describing is called "State".
The Development field will show you links to commits, branches, or pull requests.  You will have to associate the work item to them.
If you don't want to see this field to avoid confusion, you can customize the process to hide this area on the work item.


text:
Q: change font size of axisLabel How to increase the font size of only the axisLabels and not tick labels.

As you can see the axislabel font size is too small. if i give styling to text, all the text in chart is changed. I just want to change axislabel i.e Priority and Number of Alerts in this case to change. Is there a way to access only axisLabels?

A: This example : http://jsfiddle.net/thatOneGuy/juY5E/336/
I have appended a button that when clicked changes the font colour and the font size.
First off, when creating the text, I give it an ID (line 116) :
  svg.append("text")
    .attr('id','xAxisText')

Then I created a function that gets called when you click the button :
function changeFontColour(){
         d3.select('#xAxisText').style('fill','red').style('font-size', 30)
        }

This selects the text, then fills it red, then changes the font size to 30 :)


text:
Q: color packages change my spacing I have a problem with loading color packages. I have started my document some time a go and I have around 90 pages. Just now I wanted to add some code listings with colors so I loaded color package. My whole document then got messed around as the spaces between images got changed and the images started traveling to the next page... Is there a way to forbid those color packages like color or xcolor to change the spacing at all? Here is my template:
%% Clear sans, courier

% Klasa:
\documentclass[12pt]{mwart}

% Kodowanie:
\usepackage[utf8]{inputenc}

% odstep w listach
\usepackage[titles]{tocloft}
\addtolength{\cftfignumwidth}{10pt}

% Czcionki:
\usepackage[sfdefault]{ClearSans} %% option 'sfdefault' activates Clear Sans as the default text font
\usepackage[T1]{fontenc}
\usepackage{courier}
\usepackage[T1]{polski}

% Znak euro
\usepackage[official]{eurosym}

% Geometria i style
%\usepackage{showframe} % debug
\usepackage{geometry}
\geometry{a4paper,twoside=true,top=20mm,bottom=30mm,inner=35mm,outer=20mm}
\pagestyle{plain}
\usepackage{float}
\usepackage{afterpage}

% Grafika
\usepackage{graphicx}
\usepackage{epstopdf}

% matma
\usepackage{amssymb,amsmath}

% theoremy
\usepackage{amsthm}

% Stopnie
\usepackage{gensymb}

% Opisy
\usepackage{caption}
\captionsetup[table]{singlelinecheck=off}

% Tabele
\usepackage{float}
\floatstyle{plaintop}
\restylefloat{table}
\usepackage{array}
\usepackage{makecell}
%\usepackage{color}

% Footnoty
\usepackage{footnote}
\usepackage{perpage} %the perpage package
\MakePerPage{footnote} %the perpage package command

% kody
\usepackage{lipsum}
\usepackage{listings}

% Numerowanie obiektow wedlug rozdzialow
\usepackage{chngcntr}
\AtBeginDocument{\counterwithin{lstlisting}{section}}
\counterwithin{figure}{section}
\counterwithin{table}{section}
\numberwithin{equation}{section}

% Linki
\usepackage{url}
\usepackage{fancyref}

% Listy
\usepackage[ampersand]{easylist}
\ListProperties(Hide=100, Hang=true, Progressive=3ex, Style*=-- ,
Style2*=$\bullet$ ,Style3*=$\circ$ ,Style4*=\tiny$\blacksquare$ )

% Dane:
\title{Uniwersalny inteligentny sterownik silników do zastosowań przemysłowych}
\author{Łukasz Przeniosło}

% Zmienne srodowiskowe:
\newcommand{\paperTitlePl}{UNIWERSALNY INTELIGENTNY STEROWNIK SILNIKÓW DO ZASTOSOWAŃ PRZEMYSŁOWYCH}
\newcommand{\paperTitleEn}{UNIVERSAL INTELIGENT MOTOR DRIVER FOR INDUSTRIAL APPLICATIONS}
\newcommand{\topicChooseDate}{01.08.2015 r.}
\newcommand{\topicAcceptationDate}{01.06.2016 r.}
\newcommand{\tocLessLeft}[1]{\textsc{\textbf{\large \flushleft{#1}}} \vspace{3mm} \\ \indent }
\newcommand{\tocLessLeftNorm}[1]{\textsc{\textbf{\normalsize \flushleft{#1}}} \vspace{0mm} \\ \indent }
\newcommand{\tocLessCenter}[1]{\textsc{\textbf{\large \centerline{#1}}} \vspace{3mm} \\ \indent }
\newcommand{\insertImg}[3]{%
\begin{figure}[h]
    \centering
    \includegraphics[height=50mm]{#1}
    \caption{#2} \flushleft{Źródło: Na podstawie \cite{#3}}
    \label{#1}
\end{figure}
}
\newcommand{\insertImgSetSize}[4]{%
\begin{figure}[h]
    \centering
    \includegraphics[height=#2mm]{#1}
    \caption{#3} \flushleft{Źródło: Na podstawie \cite{#4}}
    \label{#1}
\end{figure}
}
\newcommand{\insertTab}[5]{%
\begin{savenotes}
    \begin{table}[h]
        \flushleft{Źródło: Na podstawie \cite{#4}} \\
        \vspace{2mm}
        \centering
        \begin{tabular}{#1}
        #2
        \end{tabular}
        \caption{#3}
        \label{#5}
        \floatstyle{plaintop}
    \end{table}
\end{savenotes}
}

% Zmienic jesli jednak Engineering -.- ...
\newcommand{\firma}{{Mechatronic Systems}}

% twierdzenia
\newtheorem{defn}{Definicja}[section]

% Indeksowanie w pdfie wyjsciowym
\usepackage{hyperref}

% Naprawienie referencji do figur i tabel
\renewcommand{\theHfigure}{figure.section.thesection.\thefigure}

% START:
\begin{document}

some text text text

\insertImgSetSize{example-image-a}
    {40}
    {1st image}
    {badcite}

some text text text

\insertImgSetSize{example-image-a}
    {50}
    {1st image}
    {badcite}

some text text text

\insertImgSetSize{example-image-a}
    {60}
    {1st image}
    {badcite}

some text text text

\insertImgSetSize{example-image-a}
    {50}
    {1st image}
    {badcite}

\end{document}

Edit: I have updated the example, it is ready to be pasted and run. Please notice how color package is commented out in line 53. Compile the code and see the document. Then uncomment the color package and compile, you will see the spacing increase. Is there a way to disable this spacing increase?

A: You're using wrongly \flushleft
\newcommand{\insertImg}[3]{%
\begin{figure}[h]
    \centering
    \includegraphics[height=50mm]{#1}
    \caption{#2}\label{#1}
    \raggedright Źródło: Na podstawie \cite{#3}
\end{figure}
}
\newcommand{\insertImgSetSize}[4]{%
\begin{figure}[h]
    \centering
    \includegraphics[height=#2mm]{#1}
    \caption{#3}\label{#1}
    \raggedright Źródło: Na podstawie \cite{#4}
\end{figure}
}
\newcommand{\insertTab}[5]{%
\begin{savenotes}
    \begin{table}[h]
        \raggedright Źródło: Na podstawie \cite{#4}\\
        \vspace{2mm}
        \centering
        \begin{tabular}{#1}
        #2
        \end{tabular}
        \caption{#3}
        \label{#5}
        \floatstyle{plaintop}
    \end{table}
\end{savenotes}
}


text:
Q: PyQt 3D for QtQuick (QML) support I'm developing a PyQt UI application with QML, and I need to use some 3D graphics,
I saw that Qt has extensive 3D support for QML (example: https://code.qt.io/cgit/qt/qt3d.git/tree/examples/qt3d/simple-qml?h=5.14)
But when I checked in PyQt docs I found 3D support only for widgets and not for QML (here: https://docs.huihoo.com/pyqt/PyQt5/Qt3DExtras.html#PyQt5-Qt3DExtras)
Am I missing something? Is 3D for QML not supported in PyQt?

A: I don't believe either PyQt or pyside are going to have classes that directly correspond to the same types in QML. Normally you would use the QML types directly in a QML engine (that might just happen to be hosted in a PyQt/pyside instantiated app).

A: Official answer from Riverbank:

It's currently a Qt Technology Preview. These are never supported by
  PyQt until they become "official".
Phil

I am resolved to using PyQt Widgets for the 3D graphics alongside the main QML application, this is not elegant but with some UI manipulations looks pretty transparent to user.


text:
Q: Backbone child view events not firing I'm a little confused as to why my event is not firing on a child view. I usually set a $el attribute but in this instance I am reusing the child view multiple times so I'm setting the className attribute but it's still not firing.
Here's my code:
Child view (simplified):
var LogbookEntryView = Backbone.View.extend({

    className: 'log-entry',
    collection: Logbook,
    template: _.template($('#logbook-entry-view').html()),

    events: {
        "click .edit-log": "editLog",
        "click .popup": "modalHandler"
    },

    render: function(model) {
        return this.template(model);
    },

    editLog: function(event) {
        var target = $(event.currentTarget);
        var id = $(target).data('id');
        var url = target.attr("href");
        var modal = $(target).data('modal');
        this.loadModal(modal, url);
        return false;
    }
})

Parent view method:
displaySkillsByCat: function() {
    var entryView = new LogbookEntryView();
    _.each(_.keys(app.data), function(cat) {
        $("#logbook-tabs ." + cat).removeClass('disabled');
        $("#" + cat).append(app.template);
        _.each(app.data[cat], function(item) {
            $("#" + cat + " .logbook-list").append(entryView.render(item.attributes));
        });
    })

    return this;
},
    groupSkillsByCategory: function(){
  var cats = _.uniq( this.collection.pluck('cat_group') );
  _.each(cats,  function(cat, index){
    app.data['cat' + cat] = Logbook.where({'cat_group': cat});
  });
},

A: The problem is that you say you're reusing a view, but in practice, you're not using it at all.
You're just passing data through the render function which returns a string, without any events or anything related to Backbone.
So the first step is to fix the child view class.

*

*collection property on a view isn't meant to be used that way, so remove that.

*A view should fill its el or $el (jQuery equivalent) with a template.

*render should return this as a standard.

var LogbookEntryView = Backbone.View.extend({
    className: 'log-entry',
    template: _.template($('#logbook-entry-view').html()),

    events: {
        "click .edit-log": "editLog",
        "click .popup": "modalHandler"
    },

    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    },

    editLog: function(event) {
        var $target = $(event.currentTarget);
        var id = event.currentTarget.id;
        var url = $target.attr("href");
        var modal = $target.data('modal');
        this.loadModal(modal, url);
        return false;
    },
    modalHandler: function() {},
    loadModal: function() {}
});

Then, in the parent view, you could simplify it a bit.

*

*Use _.each directly, you do not need _.keys. If it's a Backbone collection, you could use app.data.each(...).

*Avoid using the core jQuery function in a loop. Instead, cache the object in a variable, then use it in the loop.

*Instead of appending the string of the sub view, create a new view and append its el DOMElement.

displaySkillsByCat: function() {
    var entryView = new LogbookEntryView();
    _.each(app.data, function(entries, cat) {
        $("#logbook-tabs ." + cat).removeClass('disabled');
        $("#" + cat).append(app.template);

        // select this element once instead of each iteration
        var $list = $("#" + cat + " .logbook-list");
        _.each(entries, function(item) {

            // here, use `.el` to get the sub-view's element
            $list.append(new LogbookEntryView({ model: item }).render().el);
        });
    })

    return this;
},

The above is a simple fix for your situation, but if you don't keep track of the sub views and they are listening to a Backbone model, there could be memory leaks.
Here's a more efficient way to render a list with Backbone.


text:
Q: postgres aws connect error in pgadmin
As the picture shows, I got that error thousands times.
I'm new to postgresql and aws, but I did everything that AWS instructed.
I made Security Group correctly. (inbound rules : postgreSQL, TCP, 5432, (Source: I put anywhere and my IP and custom. I tried everything I could do))
I typed the endpoint of RDS correctly as well.


text:
Q: Select row from table from each schema I would like to select the row from DATABASECHANGELOGLOCK table from each schema with a given LIKE name. i.e. ...LIKE 'myschemaprefix%';
I would like something other than UNIONS as I have a large number of users.
SELECT 'MySchema1' as SCHEMA_NAME, LOCKED, LOCKGRANTED, LOCKEDBY FROM MySchema1.DATABASECHANGELOGLOCK
UNION
SELECT 'MySchema2' as SCHEMA_NAME, LOCKED, LOCKGRANTED, LOCKEDBY FROM MySchema1.DATABASECHANGELOGLOCK;

I attacked the problem using procedure to capture the names of all my schemas.
SET serveroutput ON
BEGIN
  FOR item IN (
    SELECT USERNAME FROM dba_users WHERE USERNAME LIKE 'MySchemaPrefix%'
  ) LOOP

    DBMS_OUTPUT.PUT_LINE
      (item.username||'.DATABASECHANGELOGLOCK');
  END LOOP;
END;
/

What I need is a SELECT within the loop that uses the output value to grab any rows where the LOCKED = 1;
Ideas?

A: This may fetch the required data
SET serveroutput ON
declare
  cur_locks sys_refcursor; -- cursor to fetch lock info

  -- variables to store data from a row of lock info
  v_locked number;
  v_lock_granted varchar2(30);
  v_locked_by varchar2(30);

BEGIN
  FOR item IN (
    SELECT USERNAME FROM dba_users WHERE USERNAME LIKE 'MySchemaPrefix%'
  ) LOOP

      OPEN cur_locks FOR
        'SELECT LOCKED, LOCKGRANTED, ' ||
        ' LOCKEDBY FROM '  || item.USERNAME  || '.DATABASECHANGELOGLOCK '
        || ' WHERE LOCKED = 1 ';

      -- loop to fetch and print
      LOOP
        fetch cur_locks into
         v_locked, v_lock_granted, v_locked_by;
        EXIT WHEN cur_locks%NOTFOUND;
        dbms_output.put_line(
          item.USERNAME ||','||
          v_locked ||','||
          v_lock_granted ||','||
          v_locked_by
        );
      end loop;

      close cur_locks;

    --DBMS_OUTPUT.PUT_LINE
      --(item.username||'.DATABASECHANGELOGLOCK');
  END LOOP;
END;
/


text:
Q: Something like Mojolicious for PHP? Mojolicious is a very good web framework for Perl. Does anyone perhaps know if there is something similar to it for PHP?

A: I would prefer Slim to write small web apps in PHP.
Snippet from docs:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require 'vendor/autoload.php';

$app = new \Slim\App;
$app->get('/hello/{name}', function (Request $request, Response $response) {
    $name = $request->getAttribute('name');
    $response->getBody()->write("Hello, $name");

    return $response;
});
$app->run();


text:
Q: Why this syntax for renaming columns in datasets? Form the documentation of Dataset:
    dataset = Dataset[{
   <|"a" -> 1, "b" -> "x", "c" -> {1}|>,
   <|"a" -> 2, "b" -> "y", "c" -> {2, 3}|>,
   <|"a" -> 3, "b" -> "z", "c" -> {3}|>,
   <|"a" -> 4, "b" -> "x", "c" -> {4, 5}|>,
   <|"a" -> 5, "b" -> "y", "c" -> {5, 6, 7}|>,
   <|"a" -> 6, "b" -> "z", "c" -> {}|>}]

gives a Dataset with columns "a", "b" and "c". To rename a column in a Dataset one uses the syntax
 dataset[All,<|"New"->"old"|>]

where "old" is the old column name and "New" is the new one. Here (also from the documentation):
dataset[All, <|"A" -> "a", "B" -> "b", "C" -> "c"|>]

and one gets the new Dataset with columns "A", "B" and "C". I wonder why this is in this way and not:
 dataset[All,<|"old"->"New"|>]

Can one give me a hint?

A: Just came across the same problem and find the following might be a sensible way:
dataset[All,KeyMap[Replace["old" -> "New"]]]

This approach essentially conducts the idea of OP and reserves the names of other columns.
BTW, I find the way suggested by the official documentation to rename columns (i.e., using Association as the operator) seems a bit tedious as unconnected columns are also involved to construct a new Association.

A: The easiest way to think about the short-hand query syntax is to turn to the documentation of Query, where we find that Query[All,f] will apply the function f to every row.  So Query[All, <|"aaa" -> #"a"|> &] would be the natural way to write a query.  The way you wrote it (i.e., Query[All, <|"aaa" -> "a"|> ]) is allowed as a more compact expression of the same query.
(Btw, this is not really "renaming", since it produces a new dataset.)


text:
Q: Drop down div not appearing on button hover, also z-index having no effect I am building something in React with Styled-Components.
I am trying to have a div explaining the rules drop down when a button is hovered.
Everything is in good position, but the display: none is not disappearing when hovered.
I have had this kind of trouble every time I try to do such things, I have even copied code from previous attempts. I haven't been able to find any good rules on the web. If someone could link to a blog post or site that explains why it is the way it is, or explain to to me, that would be much appreciated.
JSX

    <button id="rules-btn">

            ❓

        rules
    </button>

RULES:

Rule 1

Rule 2

Rule 1

Rule 1

Rule 1

STYLED-COMPONENTS
button {
    border: none;
    background: none;
    position: absolute;
    width: 200px;
    left: 50%;
    left: 50%;
    transform: translateX(-50%);
    color: #555;
    font-family: Lato;
    font-size: 20px;
    text-transform: uppercase;
    cursor: pointer;
    font-weight: 300;
    transition: background-color 0.3s, color 0.3s;
}

.rules-wrapper {
    left: 50%;
    transform: translateX(-50%);
    position: absolute;
    display: inline-block;
}

#rules-btn {
    top: 2rem;
}

#rules-btn:hover .rules-div {
    display: flex;
}

.rules-div {
    transform: translateX(-50%);
    display: none;
    position: absolute;
    left: 50%;
    top: 3.5rem;
    width: 20rem;
    transform: translateX(-50%);
    background: white;
    flex-direction: column;
    z-index: 5;
    border: 2px solid gray;
    padding: 2rem;
    align-items: center;
    box-shadow: 5px 5px 5px gray;
}

button:hover {
    font-weight: 600;
}

button:hover span {
    margin-right: 20px;
}

button:focus {
    outline: none;
}

span {
    display: inline-block;
    margin-right: 15px;
    line-height: 1;
    vertical-align: text-top;
    transition: margin 0.3s;
}

A: Looks like you already tried this:
#rules-btn:hover .rules-div {
    display: flex;
}

This will not work because .rules-div is not a child of #rules-btn. But it is right next to each other (siblings), therefore you can use Adjacent sibling combinator
#rules-btn:hover + .rules-div {
    display: flex;
}

A: thanks to @95faf8e76605e973 for this:
This will not work because .rules-div is not a child of #rules-btn. But it is right next to each other (siblings), therefore you can use Adjacent sibling combinator
#rules-btn:hover + .rules-div {
    display: flex;
}

for the z-index I had to add
.rules-wrapper {
     z-index: 5;
}


text:
Q: Javascript. If array has 3 odds in a row, print "odd". if array has 3 evens in a row - print "even" I'm new to javascript and I'm looking for some help with the following algorithm.
If array has 3 odd numbers in a row, print "odd". if array has 3 even number in a row - print "even".
function oddsAndEvens (arr) {

    for(i=0; i < arr.length; i++) {
        if(arr[i]%2==0 && arr[i+1]%2==0 &&  arr[i+2]%2==0) {
        console.log("even");
        }
       if(arr[i]%2!=0 && arr[i+1]%2!=0 &&  arr[i+2]%2!=0) {
       console.log("odd");
        }
    }
}

oddsAndEvens ([2,4,6]);

A: You can use Array.prototype.every(). You could also include check if element of array is, for example 7.5

var oddsAndEvens = (arr) => arr.every(n => n % 2 === 0) && "even"
    || arr.every(n => n % 2 != 0) && "odd";

console.log(oddsAndEvens([2, 4, 5])
           , oddsAndEvens([33, 99, 7])
           , oddsAndEvens([7.5, 4, 6]));

A: What You need is a counter for odd and event numbers. Below function will count them all and if there are 3 or more matches, then it prints in console log "odd" OR/AND "even". Works for array of any size.
function oddsAndEvens (arr) {
    var odd_count = 0,
        even_count = 0;

    for(i=0; i < arr.length; i++) {

        if(arr[i]%2==0) {
            event_count ++;

        }else if(arr[i]%2!=0){
            odd_count ++;
        }

    }

    if(even_count >= 3){
        console.log('even');
    }

    if(odd_count >= 3){
        console.log('odd');
    }

}

A: You need to be sure you have 3 defined values first. You need to add:
if(arr[i] && arr[i+1] && arr[i+2]) { }

full code:

function oddsAndEvens (arr) {
  for(i=0; i < arr.length; i++) {
    if(arr[i] && arr[i+1] && arr[i+2]) {
        if(arr[i]%2==0 && arr[i+1]%2==0 &&  arr[i+2]%2==0) {
        console.log("even");
        }
        if(arr[i]%2!=0 && arr[i+1]%2!=0 &&  arr[i+2]%2!=0) {
        console.log("odd");
        }
 }
  }
}
oddsAndEvens([1,3]); /* nothing. no 3 defined values in a row */
oddsAndEvens([1,3,7]); /* odd */
oddsAndEvens([2,2,8]); /* even */
oddsAndEvens([1,3,1, 9]); /* odd, odd */


text:
Q: Confusion with analog input range spec from a manual Looking at this manual of a galvo-mirror device, I'm confused with relating the analog inputs to angle range. It is written in the manual:
The scanner accepts a differential analog command input. If the scaling is 0.5 Volt per
degree mechanical movement (see Section 3.2.5.), -10 V to +10 V gives -20 to +20
degrees mechanical movement. The driver will attempt to set the mirror position to the
command input value.

Here is what I am confused about: Lets focus on one of the galvo-mirror which requires diff bipolar inputs to rotate the mirror. And lets call the bipolar diff inputs as Vp and Vn where Vdiff = Vp-Vn.
When they say "-10 V to +10 V gives -20 to +20 degrees", is -10 and +10 meant for (Vp-Vn) or simply Vp? This confuses me, because if the -10 V to +10 V range is meant for Vidff=(Vp-Vn) then the range for Vp will be -5 to +5 and the range for Vn will be +5 to -5. But if the -10 V to +10 V range is meant for Vp, then the range for Vp will be -10 to +10 and the range for Vn will be +10 to -10 which means Vdiff will swing from -20V to +20V.
Can someone help me what is meant by inputs here?

A: With differential inputs, this means (Vp - Vn).
The input is differential, so this could mean that the range of Vp and Vn are -5 to +5...It could also mean that Vn is always zero and Vp can be -10 V to +10 V.  It depends on the other aspects of that input what is allowed.


text:
Q: Integrate Amazon S3 into OSGi (Apache Felix) I try to add "Upload to amazon S3" functionality to my bundle. I added dependency on aws-java-sdk to bundle's pom:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.93</version>
</dependency>

After that, I edited configuration of maven-bundle-plugin:
<Embed-Dependency>
 im4java;scope=compile,aws-java-sdk;scope=compile|runtime;optional=false;inline=true
</Embed-Dependency>
<Embed-Transitive>true</Embed-Transitive>

But when I try to install bundle I get error message

missing requirement [447.74] osgi.wiring.package;
  (osgi.wiring.package=com.amazonaws.auth

Could anyone help me?

A: You have to add this package to
<Export-Package>

or to
<Private-Package>

In later case be sure to add all other packages, cause adding of
<Private-Package>

will override default behavior. In simplest case it should looks like
<Private-Package>com.amazonaws.*, *</Private-Package>


text:
Q: Is possible to edit "ionic-img-viewer" npm or copy the image style in Ionic 2? I want to ask if I can to edit or add any additions when my image viewed by "ionic-img-viewer" npm. Or at least how can used the same style of my image tag.
for example: this is my img tag and you can see some codes of filters
<img src="{{url}}" style="filter: brightness(130%) contrast(130%) grayscale(100%) ;" #imageToView>

These codes of using ionic-img-viewer npm
<button ion-button full clear icon-only color="" (click)="viewImg(imageToView)">
   <ion-icon name="expand"></ion-icon>
</button>

TS codes
import { ImageViewerController } from "ionic-img-viewer";
...
constructor( public navCtrl: NavController, ..., public imageViewerCtrl: ImageViewerController)
...
viewImg(imageToView) {
  const viewer = this.imageViewerCtrl.create(imageToView)
  viewer.present();
}

When I viewed this image with ionic-img-viewer it's show me the original image (without any filter). So is there any way to applied my style in the viewed image.

Note: ionic-img-viewer npm is this [ https://www.npmjs.com/package/ionic-img-viewer ]

A: I found the solution. I just searched to javascript files of npm in

..\node_modules\ionic-img-viewer\dist\umd\src\image-viewer.component.js
  ..\node_modules\ionic-img-viewer\dist\es2015\src\image-viewer.component.js

Then playing with template code as shown in below image


text:
Q: What does it take to persuade people in Promises to Keep? Promises to Keep: Help Louis Letrush get Frost from Sibbi Black-Briar.
In this quest, there are multiple chances to persuade people (the guard and Sibbi, twice). How much Speech is required to successfully persuade them?
The reason that I phrased the title so, instead of as "how much Speech do I need to persuade...", is because I know that the Amulet of Articulation is an alternative to Speech, thus there are alternatives.

A: Both persuading the guard to let you in and persuading Sibbi to give you the key are Easy speech checks. They require 25 speech, or 18 speech and the Persuasion perk.


text:
Q: Cannot get kubectl environment variables on deploy I have a docker container with a few environment variables setup. I know that in a typical use case, React is unable to read these variables as the process.env variables are replaced during transpiling.
I am trying to work around this without having to spin up a back-end server by using a plugin called react-env.
The core idea is to create a .env file which can be written to using a bash script. The bash script will copy any environmental variables to the .env file. The plugin will generate a env.js file which then will be consumed by the React application at runtime.
Dockerfile
FROM node:9

# Install yarn
RUN npm install yarn

# Install serve.js
RUN yarn global add serve

# Create app directory
WORKDIR /usr/app

# Copy all necessary files and grant permissions.
# - yarn.lock
# - package.json
# - .env
# - docker-entrypoint.sh
COPY . /usr/app/
COPY yarn.lock /usr/app
COPY package.json /usr/app
COPY .env /usr/app
COPY docker-entrypoint.sh /usr/app/docker-entrypoint.sh
RUN chmod 777 /usr/app/docker-entrypoint.sh

# Install dependencies.
RUN printf "\n" >> /usr/app/.env
RUN echo 'REACT_APP_GCP_PROJECT_ID='$GCP_PROJECT_ID >> /usr/app/.env //READ ENVIRONMENTAL VARIABLE HERE
RUN yarn

# Build application.
RUN yarn build

# Set entrypoint of application.
ENTRYPOINT [ "/usr/app/docker-entrypoint.sh" ]

docker-entrypoint.sh
serve build

App.jsx
...

console.log(env("GCP_PROJECT_ID"));

...

Inspect Console
'' //Empty string.

However, after making the image and deploying the application, the console outputs an empty string of the environmental variable.
Manually exec into the and running the echo command correctly does work:
Querying manually:
# echo 'REACT_APP_GCP_PROJECT_ID='$GCP_PROJECT_ID
REACT_APP_GCP_PROJECT_ID=SOME_VALUE

but
# cat .env
REACT_APP_SETUP="OK"
REACT_APP_GCP_PROJECT_ID=

How can I get my pod environmental variables into my .env file before React runs?

A: It looks like $GCP_PROJECT_ID is not defined in the build environment, and thus it isn't included in the echo command when it runs at build time.  (I presume this is because you are having kubectl define it).
Assuming that you expect that $GCP_PROJECT_ID does not exist in the build environment and is instead something you are trying to copy from at the time your container executes (as indicated by your exec example), your problem is that the quoting of the RUN line
RUN echo 'REACT_APP_GCP_PROJECT_ID='$GCP_PROJECT_ID >> /usr/app/.env

Is interpreting $GCP_PROJECT_ID during the build, which of course is the empty string.  In your test in the shell inside the container, it appears that $GCP_PROJECT_ID actually exists in the environment and all is well.
You need to actually quote the $GCP_PROJECT_ID variable to get it included into /usr/app/.env, like so (instead of being interpreted as an empty string!):
RUN echo 'REACT_APP_GCP_PROJECT_ID=$GCP_PROJECT_ID' >> /usr/app/.env

Of course, if you need the literal string which is the value of $GCP_PROJECT_ID to be included in the .env file, your only alternative may be to actually do the echo into .env at the beginning of the container execution (e.g. at the top of docker-entrypoint.sh, and remove all the related code from your Dockerfile).

If I am wrong about you having kubectl define it when the process starts, an alternative solution would require you to ensure that the docker build itself has access to that environment variable.  You can do this with the --build-arg argument, such as:
docker build --build-arg GCP_PROJECT_ID=[correct value] .

In this case, you need to add an argument command to the Dockerfile, like so:
ARG GCP_PROJECT_ID

at some point before the RUN command.


text:
Q: Take text from Text area I have this html code -
<form method="post" style="width:100%; margin-bottom:40px;" >
                <textarea id="wall_post" style="width:100%;; margin-left:-4px; margin-right:auto; resize:none;" rows="4"></textarea>
                <input id="wallPost" type="submit" value="Post" method="post" style="float:right; font-size:65%;" />

                    <input type="checkbox" id="sms" value = "SMS" method = "post"/>SMS
                    <input type="checkbox" id="email" value = "Email" method = "post"/>Email

            </form>

As you can see there are a few buttons. I'd like to have it so that when say the checkbox with value SMS is clicked, the stuff in the textarea is passed to a django view. I know I can pass stuff into django using a jquery ajax post with the relevant url conf, but how do I do so on the request of the user? (in pseudocode - if user clicks post, give django function text area text)
thanks!

A: Why do you have to change whether or not your textarea is being submitted to django?
It's not much data. Why not always submit it and check in your view if the SMS checkbox is checked?
If checked: do something with textarea data. If not: don't.
Note: you're missing the name attribute on each of your inputs.
def my_view(request):
    if request.method == 'POST':
        if request.POST.get('sms'):
            # do something with text area data since SMS was checked
            print request.POST.get('my_textarea')

        # process form as usual.

If you want to change whether or not django reads your data, you could potentially dynamically add or remove the textarea's name attribute with javascript, but this is riskier and more work than the above solution.
update - the html to work with above code.
<form method="post">
    {% csrf_token %}
    <textarea name="my_textarea"></textarea>
    <input type="checkbox" name="sms" />
</form>


text:
Q: Boundary conditions for the $bc$ system In this question, I will be referring to chapter 2 of Polchinski String Theory vol. 1.
In equation (2.7.29), he states that the boundary conditions for the $bc$ system of the open string are
\begin{equation} c(z)= \tilde{c}(\bar{z}), \quad b(z)= \tilde{b}(\bar{z}), \quad \text{Im}\; z =0. \quad (1)
\end{equation}
$\text{Im} \; z = 0$ is the boundary of the open string, so that, in the cylinder, this should be translated to the the ends of the string: $\sigma_1 = 0$ and $\sigma_1 = \pi$.
Now, the $bc$ system action with the left and right-moving variables reads
$$\int d^2 z \; \big( b \bar{\partial} c + \tilde{b} \partial \tilde{c}\big), $$
with $d^2z = 2 d \sigma_1 d \sigma_2$, $\partial = \frac{1}{2}(\partial_1 - i \partial_2) $, $\bar{\partial} = \frac{1}{2} ( \partial_1 + i \partial_2)$, $0 \leq \sigma_1 \leq \pi$ and $\sigma_2$ being the Euclidean time going from $ - \infty$ to $\infty$.
If I substitute these definitions in the action I get
$$ \int_{- \infty}^{\infty} d \sigma_2 \int_0^\pi d\sigma_1 \big(b \partial_1c + i b \partial_2 c + \tilde{b} \partial_1 \tilde{c} - i \tilde{b} \partial_2 \tilde{c} \big).$$
Doing a partial integration in the derivatives with respect to $\sigma_1$, we get the following boundary terms that should be equal to zero
$$\int_{- \infty}^{\infty} d \sigma_2 \big(bc + \tilde{b} \tilde{c} \big)\bigg\rvert_{\sigma_1=0}^{\sigma_1 = \pi}.$$
As is done in the bosonic string, the boundary conditions at $\sigma_1=0$ and at $\sigma_1 = \pi$ should be zero independently. So that we should have
$$b(z)c(z) + \tilde{b}(\bar{z}) \tilde{c}(\bar{z})=0, \quad \sigma=0 \\
b(z)c(z) + \tilde{b}(\bar{z}) \tilde{c}(\bar{z})=0, \quad \sigma= \pi$$
But these are not the same conditions as in equation (1). Because for the last equations to be satisfied we should have $c(z) = \pm\tilde{c}(\bar{z}) $ and $b(z) = \mp \tilde{b} (\bar{z})$ at $\sigma_1 = 0 , \pi$.
My question is: Does the boundary conditions change in the cylinder or am I doing something wrong?


text:
Q: I can't get the Java .Replace object to change my string depending on Scanner input I am using a scanner to put a String value into currentGuess, then i have a method called 'alphabet' which contains a simple string of letters, i wanted to have a letter whether a,b,c that a user puts into a scanner, replacing the letter in the Alphabtet String with _ or taken.This doesn't happen anymore like it used to. I don't know what i did wrong. Underneath the 'scanner' is an object called "alphabet();" which checks your letters and updates the list with a return. The program is a resemblance of scrabble where a user enters a letter and that letter is removed from the alphabet. Only letters that get replaced are 'abcdefg'so 7, which is what the while loop is set to, but nothing else does, for some weird reason. If i set the first letter in the string to 'h', then type h, it will change that letter. I will include a small bit of the problem code and my entire code for those interested. I will be very happy if someone helps me out.
private static String alphabet()
{
    System.out.println("debugging:underneath alphabet string. >"+currentGuess+"<");
    for(int i=0;i<alphabet.toCharArray().length;i++){
            if(currentGuess.contains(alphabet.toCharArray()[i]+""))
            {
                System.out.println("debugging: >"+currentGuess+"<");
                alphabet=alphabet.replace((alphabet.toCharArray()[i]+""), "test");

            }else if(currentGuess.contains(Vowels.toCharArray()[i]+""))
            {
            System.out.println("You have just entered a Vowel, board not affected.");
            }

import java.util.Scanner;

import java.util.Arrays;
public class scrabble{

    private static String alphabet = "[b][c][d][f][g][h][j][k][l][m]\n[n][p][q][r][s][t][v][w][x][y][z]";
    private static String currentGuess = "";
    private static String guessedLetters = "";
    private static String currentPlayer;
    private static int letterValue = 0;
    private static int playerNumber = 1;
    private static String playerTwo;
    private static String playerOne;
    private static String Response = "";
    private static int playerTwoScore = 0;
    private static int playerOneScore = 0;
    private static int playerTurnScore = 0;
    private static String playerLetter = "";
    private static int finalScores = 0;
    private static int duplicateLetterValue = 0;
    private static String Vowels = "[a][e][i][o][u]";

    public static void main(String args[]){
    Scanner scan = new Scanner(System.in);
    System.out.println("\nThis is the main console.");
    System.out.println("Type Y to begin or N to exit.");

    if(new Scanner(System.in).next().equalsIgnoreCase("y")){
        System.out.println("Player one, enter your name: ");
        playerOne = scan.next();
        System.out.println("Player two, enter your name: ");
        playerTwo = scan.next();

        currentPlayer();
        startGame();
    }
    else
    {
        System.out.println("Goodbye.");
        System.exit(0);
    }
}

private static void startGame()
{
    int i=0;
    System.out.println("     <--Scrabble Board-->");
    System.out.print(alphabet()+"\n");
    System.out.println("\nNext Turn is: "+currentPlayer);
//if(currentGuess.equals("quit")){
    //if(currentGuess.equals("pass")){

for(i=0;i<7;i++){
    duplicateLetterValue=letterValue;
    guessedLetters+=currentGuess;
    playerLetter+=currentGuess;
    playerTurnScore+=letterValue;

    System.out.println("\n"+currentPlayer+": Enter a letter: ");

    currentGuess=new Scanner(System.in).next();

    //usedLetters();
    alphabet();
    System.out.println("debugging(below used letters and alphabet): >"+currentGuess+"<");
    System.out.println("current player:" +currentPlayer+"\n");
        switch(currentGuess.toUpperCase())
        {
        case "A":
        int a=9;
        letterValue =9;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;
        case "B":
        int b=2;
        letterValue =2;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;
        case "C":
        int c=9;
        letterValue =9;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;
        case "D":
        int d=4;
        letterValue =d;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "E":
        int e=12;
        letterValue =e;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "F":
        int f=2;
        letterValue = f;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "G":
        int g=3;
        letterValue =g;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "H":
        int h=2;
        letterValue =h;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "I":
        letterValue =9;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "J":
        int j=1;
        letterValue =j;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "K":
        int k=1;
        letterValue =k;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "L":
        int l=4;
        letterValue =l;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "M":
        int m=2;
        letterValue =m;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "N":
        int n=6;
        letterValue =n;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "O":
        int o=8;
        letterValue =o;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "P":
        int p=2;
        letterValue =p;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "Q":
        int q=1;
        letterValue =q;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "R":
        int r=6;
        letterValue =r;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "S":
        int s=4;
        letterValue =s;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "T":
        int t=6;
        letterValue =t;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "U":
        int u=4;
        letterValue =u;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "V":
        int v=2;
        letterValue =v;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "W":
        int w=2;
        letterValue =w;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "X":
        int x=1;
        letterValue =x;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "Y":
        int y=2;
        letterValue =y;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;

        case "Z":
        int z=1;
        letterValue =z;
        System.out.println(">Value of "+currentGuess.toUpperCase()+" is "+letterValue);

        break;
        default:
        System.out.println("Only permitted to use a single character.");
        startGame();
        break;
        }
    }
        System.out.println("\nRemaining letters are: \n"+alphabet());
        playerOneTurn();
        System.out.println("debugging: below Switch statement>"+currentGuess+"<");
    //}
        //currentGuess.equals(" ");
        //currentPlayer();
        //startGame();
//}
        //System.out.println("You have chosen to exit the game.");
        //finalScores();

}
            private static void playerOneTurn()
        {
            System.out.println("debugging:inside player one Turn >"+currentGuess+"<");
            //if(currentPlayer==playerTwo){
            //playerTwoTurn();
        //}

            playerTurnScore=playerTurnScore -duplicateLetterValue;
            playerLetter+=currentGuess;
            System.out.print(currentPlayer +"'s word is: "+playerLetter);
            System.out.println("\nEnter (Y) if both players agree on the word or anything else if you disagree: ");
            Response=new Scanner(System.in).next();

            if(Response.equalsIgnoreCase("y")&&currentPlayer == playerOne)
        {

            System.out.print("\nPlayer one score has changed.");

            playerOneScore+=playerTurnScore;

            System.out.println("\nPlayer one Score: "+playerOneScore+"\n");
            playerLetter="";

            currentPlayer();
            startGame();

            }else if(Response.equalsIgnoreCase("y")&&currentPlayer == playerTwo)
            {

            playerTwoTurn();

            }else{
            System.out.println("Word denied.");
            System.exit(0);
            }
        }

        private static void playerTwoTurn()
        {
            System.out.println("inside player two turn >"+currentGuess+"<");
            currentPlayer();
            System.out.println("\nNext Turn is: "+currentPlayer);

            guessedLetters += currentGuess;
            System.out.print("Overall used letters: "+guessedLetters);
            System.out.print("\nPlayer two score has changed.");
            playerTwoScore+=playerTurnScore;
            System.out.print("\nPlayer two Score: "+playerTwoScore);
            startGame();
        }

private static String alphabet()
{
    System.out.println("debugging:underneath alphabet string. >"+currentGuess+"<");
    for(int i=0;i<alphabet.toCharArray().length;i++){
            if(currentGuess.contains(alphabet.toCharArray()[i]+""))
            {
                System.out.println("debugging: >"+currentGuess+"<");
                alphabet=alphabet.replace((alphabet.toCharArray()[i]+""), "test");

            }else if(currentGuess.contains(Vowels.toCharArray()[i]+""))
            {
            System.out.println("You have just entered a Vowel, board not affected.");
            }
}
return alphabet;
}
private static void currentPlayer()
    {
    if(playerNumber==1)
        {
            currentPlayer=playerOne;
            playerNumber+=1;
        }
        else{
            currentPlayer=playerTwo;
            playerNumber-=1;
        }
    }

    private static void finalScores(){

        if(playerOneScore>playerTwoScore){
        System.out.println("Player one wins.");
        System.exit(0);
        }else{
        System.out.println("Player two wins.");
        System.out.print(playerTwoScore);
        System.exit(0);
    }
}

private static void usedLetters()
{
    for(int i=0;i<currentGuess.toCharArray().length;i++)
    {
        if(guessedLetters.contains((currentGuess.toCharArray()[i]+"")))
        {
            //currentGuess=currentGuess.replace((currentGuess.toCharArray()[i]+""), "");
            System.out.println(">Those letters were previously used.");
            playerTurnScore=playerTurnScore-duplicateLetterValue;

        }
    }
}

}


text:
Q: How to Optimize Nginx & PHP FPM based on server specification my server always hit 502 bad gateway where the load average is low. I have no idea what the causes of it. Been trying to figure out setting Nginx and PHP FPM but getting the same result.
Server Specification
2x E5-2670 0 @ 2.60GHz [16 cores]
32 GB RAM
Here is my nginx settings
user  nobody;
worker_processes 1;
worker_rlimit_nofile 2500;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

pid     /var/run/nginx.pid;
include /usr/local/apps/nginx/etc/modsecurity*.conf;

events {
    worker_connections  1024;
}

error_log /usr/local/apps/nginx/var/log/error_log debug;

http {
    include    mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /usr/local/apps/nginx/var/log/web.access.log  main;

    sendfile        on;
    #tcp_nopush  on;

    #keepalive_timeout  0;
    keepalive_requests 200;
    keepalive_timeout  130;

    #gzip  on;

    client_max_body_size 200M;

    # If your domain names are long, increase this parameter.
    server_names_hash_bucket_size 64;

    # To hide the version number in headers
    server_tokens off;

    include /usr/local/apps/nginx/etc/conf.d/*.conf;
}

Here is the php fpm conf
pm.max_children = 5
pm.start_servers = 0
pm.min_spare_servers = 1
pm.max_spare_servers = 5
pm.max_requests = 20
pm.process_idle_timeout = 10
request_terminate_timeout = 120s

Can you provide regarding the calculation? and explain it so we can learn it how to set it properly


text:
Q: SQL INNER JOIN Multiple Tables and columns The Problem:
Construct the SQL statement to find all of the people that have meetings only before Dec. 25, 2016 at noon using INNER JOINs. Display the following columns:
 Person's first name
 Person's last name
 Meeting ID
 Meeting start date and time
 Meeting end date and time

The Tables:
There are 5 tables in this database(person, building, room, meeting, person_meeting
+-----------+------------+------------+
| person_id | first_name | last_name  |
+-----------+------------+------------+
|         1 | Tom        | Hanks      |
|         2 | Anne       | Hathaway   |
|         3 | Tom        | Cruise     |
|         4 | Meryl      | Streep     |
|         5 | Chris      | Pratt      |
|         6 | Halle      | Berry      |
|         7 | Robert     | De Niro    |
|         8 | Julia      | Roberts    |
|         9 | Denzel     | Washington |
|        10 | Melissa    | McCarthy   |
+-----------+------------+------------+

+-------------+----------------------+
| building_id | building_name        |
+-------------+----------------------+
|           1 | Headquarters         |
|           2 | Main Street Buidling |
+-------------+----------------------+

+---------+-------------+-------------+----------+
| room_id | room_number | building_id | capacity |
+---------+-------------+-------------+----------+
|       1 | 100         |           1 |        5 |
|       2 | 200         |           1 |        4 |
|       3 | 300         |           1 |       10 |
|       4 | 10          |           2 |        4 |
|       5 | 20          |           2 |        4 |
+---------+-------------+-------------+----------+

+------------+---------+---------------------+---------------------+
| meeting_id | room_id | meeting_start       | meeting_end         |
+------------+---------+---------------------+---------------------+
|          1 |       1 | 2016-12-25 09:00:00 | 2016-12-25 10:00:00 |
|          2 |       1 | 2016-12-25 10:00:00 | 2016-12-25 12:00:00 |
|          3 |       1 | 2016-12-25 11:00:00 | 2016-12-25 12:00:00 |
|          4 |       2 | 2016-12-25 09:00:00 | 2016-12-25 10:00:00 |
|          5 |       4 | 2016-12-25 09:00:00 | 2016-12-25 10:00:00 |
|          6 |       5 | 2016-12-25 14:00:00 | 2016-12-25 16:00:00 |
+------------+---------+---------------------+---------------------+

+-----------+------------+
| person_id | meeting_id |
+-----------+------------+
|         1 |          1 |
|        10 |          1 |
|         1 |          2 |
|         2 |          2 |
|         3 |          2 |
|         4 |          2 |
|         5 |          2 |
|         6 |          2 |
|         7 |          2 |
|         8 |          2 |
|         9 |          3 |
|        10 |          3 |
|         1 |          4 |
|         2 |          4 |
|         8 |          5 |
|         9 |          5 |
|         1 |          6 |
|         2 |          6 |
|         3 |          6 |
+-----------+------------+

My Solution so Far:
SELECT first_name,last_name ,building_name,meeting_start,meeting_end
FROM person P
INNER JOIN building B
ON P.person_id=PM.person_id
INNER JOIN person_meeting PM
    ON M.room_id
I'm having trouble completing the SQL statement, please help if possible.

A: this might do the trick for you. I used aliases for each of the tables in the join and used them in the select statements for the columns you needed. Then I joined the needed tables and in the where it determines the ones with a meeting_end before dec 12 at noon. (i assume, if you wanted it start just switch it to meeting_start)
select p.first_name,p.last_name,pm.meeting_id,m.meeting_start,m.meeting_end from person p
inner join person_meeting pm on pm.person_id = p.person_id
inner join meeting m on m.meeting_id = pm.meeting_id
where m.meeting_end > '2016-12-25 12:00:00'


text:
Q: Remove Button to configure in Table (editable) cloned rows I have an editable table with rows cloned, the rows cloned are editable in both column with a text area and input number. If you click to edit the input number, there is a function which makes the sum and gives the Total Amount automatically.
My issue now is that i can not configure properly the remove button for the rows cloned. If you give a try you notice that instead of removing a row, it adds one more. Please i need help on how to figure it out this issue.
This is the script for rows cloned, i think it needs to get reduced and improved
$('input:button').live('click',function(){
    var temprow = $('#temprow tbody').html();
    var tr = $(this).closest('tr');
    tr.after(temprow);
});

$("input.tr_clone_add").live('click', function() {
    var lastid = $('[id^="sum"]').length + 1;
    var $tr = $(this).closest('.tr_clone');
    var $clone = $tr.clone();
    $clone.find(':text').val('');
    $clone.attr('id', 'sum' + lastid)
    $tr.after($clone);
    initEditables();
    tally('p#subtotal');
    tally('p#total');
});

$(".tr_clone_remove").live("click", function() {
$(".tr_clone").last().remove();
    initEditables();
    tally('p#subtotal');
    tally('p#total');
});

initEditables();
tally('p#subtotal');
tally('p#total');

My Table

A: *

*Change the tr.after function to:
if ($(this).val() == '+') {
    tr.after(temprow);
}

*Make the remove() call as:
$(this).parent().parent().remove();

Here is the fiddle.

A: Edited your Fiddle with the correct solution: http://jsfiddle.net/Manna/S3kZw/5/

*

*Since the tr_clone_remove class is also a button type input, the first handler is called every time you click on the remove button.
$('input:button').live('click',function(){
    var temprow = $('#temprow tbody').html();
    var tr = $(this).closest('tr');
    tr.after(temprow);
});

This is the reason why rows are being inserted, instead of being deleted.

*Also, updated your remove row block with the correct code.


text:
Q: Proof that all Cauchy sequences converge I am supposed to prove that all Cauchy sequences converge, using the fact that a sequence converges iff its lim sup equals its lim inf. I think the proof I have works, but the one given in the solutions is different, so I'd like to make sure. Also, this is for a calculus class, not real analysis, so I don't know about metric spaces or any of that. I believe the problem pertains solely to sequences in $\mathbb{R}$.
We have the Cauchy sequence $\{a_n\}$. By the definition of the Cauchy sequence, we have
$$\left|a_m-a_n\right|<\frac{\epsilon}{3}$$
for a given $\epsilon>0$ and $m,n>N$. There exist the numbers $\inf_{n>N}\{a_n\}$ and $\sup_{n>N}\{a_n\}$, that is to say, the infimum and supremum of the sequence with the first $N$ terms truncated. By the definition of the infimum, we must have
$$\left| a_{low}-\inf_{n>N}\{a_n\}\right|<\frac{\epsilon}{3}$$
for some $a_{low} \in \{a_n|n>N\}$, because otherwise $\inf_{n>N}\{a_n\}+\frac{\epsilon}{3}$ would be a greater lower bound for $\{a_n|n>N\}$ than the infimum, a contradiction. By the same reasoning, we also have
$$\left|\sup_{n>N}\{a_n\}-a_{high}\right|<\frac{\epsilon}{3}$$
for some $a_{high} \in \{a_n|n>N\}$. Now, by the definition of the Cauchy sequence, we must have
$$\left|a_{high}-a_{low}\right|<\frac{\epsilon}{3}$$
Expanding the absolute value terms gives
$$-\frac{\epsilon}{3}<a_{low}-\inf_{n>N}\{a_n\}<\frac{\epsilon}{3}$$
$$-\frac{\epsilon}{3}<\sup_{n>N}\{a_n\}-a_{high}<\frac{\epsilon}{3}$$
$$-\frac{\epsilon}{3}<a_{high}-a_{low}<\frac{\epsilon}{3}$$
Adding these together gives
$$-\epsilon<\sup_{n>N}\{a_n\}-\inf_{n>N}\{a_n\}<\epsilon$$
So
$$\left|\sup_{n>N}\{a_n\}-\inf_{n>N}\{a_n\}\right|<\epsilon$$
which, we remember, holds for $n>N$. By the definition of the infinite limit, then, because we can make the difference of the infimum and the supremum arbitrarily close to zero by increasing $N$, we have
$$\lim_{N \rightarrow \infty}\left( \sup_{n>N}\{a_n\}-\inf_{n>N}\{a_n\} \right)=\lim_{N \rightarrow \infty}\sup_{n>N}\{a_n\}-\lim_{N \rightarrow \infty}\inf_{n>N}\{a_n\}=0$$
So the lim inf of any Cauchy sequence equals its lim sup, and therefore it converges.

A: Basically, a Cauchy sequence can not have different values for lim-inf and lim-sup, assuming both exists. I.e. if $lim_{inf}=a$ and $lim_{sup}=b$, where $b-a > 0$, then there will exists $n,m > N$ and an $\varepsilon < \frac{b-a}{3}$ such that $\left |a_{n} - a_{m}  \right |> \varepsilon $, just take $a_{n}$ from the subsequence 'going' to $lim_{inf}=a$ and take $a_{m}$ from the subsequence 'going' to $lim_{sup}=b$.


text:
Q: ProGuard and dynamic proxies with spring 3 i am trying to obfuscate a java app with ProGuard, but i have a problem with one particular topic, here it is.
My app uses Java 1.7, Valkyrie RCP for GUI, spring 3.1.3 for bean container and spring JDBC for database communication, so spring contains all objects, from gui views to jdbc's daos.
When i obfuscate the code with ProGuard 5.1, spring is having problems to instantiate beans. I am usging ant target, here is the code:
<proguard
          optimize="false"
          shrink="false"
          obfuscate="true"
          allowaccessmodification="false"
          usemixedcaseclassnames="false"
          skipnonpubliclibraryclasses="false"
          printseeds="obfuscateseeds.txt"
          printusage="obfuscateusage.txt"
          printmapping="obfuscatemapping.txt">

  <keepattribute name="*Annotation*"/>

  <injar name="${proj.output}/app/lib/myjar.jar"/>
  <outjar name="${proj.output}/app/lib/myjar-ofuscated.jar"/>

  <keep name="com.myjar.Main">
    <method name="main"/>
  </keep>

  <libraryjar name="${env.JAVA_HOME}/jre/lib/rt.jar"/>
  ...

</proguard>

I have many configuration classes, and proguard ofuscate them very well, but at the moment some of them gets instantiated, a wrong method is called. For exame my main Configuration object is like next:

@Configuration
@EnableTransactionManagement
@Import({ RulesContext.class })
public class MainContext implements ApplicationConfig{

    @Autowired private RulesContext rulesContext;

    @Bean public AnnotationBeanConfigurerAspect annotationBeanConfigurerAspect(){
        logger.debug("annotationBeanConfigurerAspect");

        return AnnotationBeanConfigurerAspect.aspectOf();
    }

    /* lot of methods between */

    @Bean @Override public RulesSource rulesSource() {
        logger.debug("rulesSource");
        DefaultRulesSource rules = new DefaultRulesSource();
        rules.addRules(rulesContext.enterpriseRules());
        rules.addRules(rulesContext.coinRules());
        rules.addRules(rulesContext.bankRules());
    }

    /* lot of methods after */
}

when it gets obfuscated, the result is:

@Configuration
@EnableTransactionManagement
@Import({o.class})
public class b
  implements ApplicationConfig
{
  @Autowired
  private o f;

  @Bean
  public AnnotationBeanConfigurerAspect a()
  {
    this.a.debug("annotationBeanConfigurerAspect");
    return AnnotationBeanConfigurerAspect.aspectOf();
  }

  @Bean
  public RulesSource rulesSource()
  {
    this.a.debug("rulesSource");
    DefaultRulesSource localDefaultRulesSource = new DefaultRulesSource();
    localDefaultRulesSource.addRules(this.f.a());
    localDefaultRulesSource.addRules(this.f.b());
    localDefaultRulesSource.addRules(this.f.c());
  }
}

And when i exec the app, it throws an exception:

org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'rulesSource' defined in class
  com.myjar.j.b: Instantiation of bean failed; nested exception
  is org.springframework.beans.factory.BeanDefinitionStoreException:
  Factory method [public org.valkyriercp.rules.RulesSource
  com.myjar.j.b.rulesSource()] threw exception; nested
  exception is java.lang.ClassCastException:
  org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect
  cannot be cast to com.myjar.n.g.b.b

The object com.myjar.n.g.b.b (RulesContext before obfuscation) has a method a() which returns an appropiate RulesObject, but for some reason, method a() in the obfuscated RulesContext object does not gets invoked, but method a() in the b object (MainContext) instead. So method a() in b (MainContext) object returns an AnnotationBeanConfigurerAspect object, which is not a Rules object and so the exception.
If i avoid obfuscation over the package which contains all spring config objects, the program runs very well, it is just obfuscation when the problem is present.
Any of you has encountered some similar problem? how do you solve it? or, any clue on what's happening?
Thank you for your time


text:
Q: How to prevent a path from being filled (again)? I am drawing some shapes on a canvas element. The first element is a path, which should not get filled at all. I know I can set fillStyle to none, but it gets filled twice.
Here is some example code (also on jsfiddle):
can = document.getElementById('can');
ctx = can.getContext('2d');

function drawPoint(x,y){
    ctx.arc(x,y,12,0,Math.PI*2,false);
    ctx.fillStyle ='rgba(255, 0, 0, 0.2)';
    ctx.fill();
}

function shape(){
    ctx.fillStyle = 'rgba(0,255,0,0.2)';
    ctx.beginPath();
    ctx.moveTo(10,10);
    ctx.lineTo(100,30);
    ctx.lineTo(30,200)
    ctx.closePath();
    ctx.stroke();
    ctx.fill();
}

shape();

drawPoint(30,12);

This is just an example code, to illustrate the problem I am facing.
When I draw the shape afterwards, the point is in the background. So this won't work. I also searched for resources on how the fill method works but couldn't find anything useful.
So how can I draw the shape without filling it?

A: Just don't call fill()...
For example, if you want your method reusable you can use a flag:
function shape(fill){
    fill = fill || false;
    ctx.fillStyle = 'rgba(0,255,0,0.2)';
    ctx.beginPath();
    ctx.moveTo(10,10);
    ctx.lineTo(100,30);
    ctx.lineTo(30,200)
    ctx.closePath();
    ctx.stroke();
    if (fill) ctx.fill();
}

Now you can call:
draw();     /// won't fill
draw(true); /// fills

Also add a beginPath() to this method or else it will just add to the path of the first shape (which perhaps is what you mean?):
function drawPoint(x,y){
    ctx.beginPath();
    ctx.arc(x,y,12,0,Math.PI*2,false);
    ctx.fillStyle ='rgba(255, 0, 0, 0.2)';
    ctx.fill();
}

Hope this helps (and that I didn't misunderstand your question)!
Modified fiddle here


text:
Q: create dictonary with array as value in key value pair : java Script Am trying to achieve something like the following :
  Key                      value

fruit               apple,orange,banana,grapes
cooldrinks          pepsi,cococola,miranda
snaks               lays,kurkure

for that i use the code as:
<script>
var vars = [{key:"key", value:"val1",value:"val2",value:"val3",value:"val4"}];
vars[0].key = "fruit";
vars[0].val1 = "apple";
vars[0].val2 = "orange";
vars[0].val3 = "banana";
vars[0].val4 = "grapes";
</script>

But it is not possible for large dictionaries how can i implement such dictionaries with huge content? can anyone suggest me a simplest method?
In the case of dynamic array what should i need to change in my code?

A: How about:
var data = [
  {fruit: ['apple','orange','banana','grapes']},
  {cooldrinks: ['pepsi','cocacola','miranda']},
  {snacks: ['lays','kurkure']}
]

A: Why you use an array for this? Use an object instead:
var dictionary = {
   key1: ["value1", "value2"],
   key2: ["value3", "value4"]
};

If you want to obtain all keys, you may use Object.keys:
var allKeys = Object.keys(dictionary);

Also, you can access a key using dot syntax or indexed syntax:
var key1value = dictionary.key1;
key1value = dictionary["key1"];

A: You can use js objects to do this
var dictionary = [
  { fruit: ['apple', 'orange', 'banana', 'grapes'] },
  { cooldrinks: ['pepsi', 'cocacola', 'miranda'] },
  { snacks: ['lays', 'kurkure'] }
];

You can then access them like this
dictionary.fruit;     // returns apple, orange, banana, grapes
dictionary.snacks[0]; // returns lays

You can even use [] notation
dictionary["fruit"][0];// returns apple

A: You should first of all create this key/values object:
function Pairs() {
    this.key= "",
    this.values= new Array()
}

this object will hold your key and values for all the things.
Next up you need to create a dictionary array to hold all the Pairs:
var dictionary = new Array();

then, create your objects, fill them up with data and add them to dictionary:
var fruit = new Pairs();
fruit.key = "fruit";
fruit.values[0] = "banana";
fruit.values[1] = "Orange";
fruit.values[2] = "Apple";
dictionary.push(fruit);  //adding fruit to dictionary

var car = new Pairs();
car.key = "car";
car.values[0] = "Honda";
car.values[1] = "Toyota";
car.values[2] = "Ferrari";
dictionary.push(car);   //adding car to dicitonary

once dictionary is populated, you can access the objects like:
dictionary.length; //get the length of all the objects present in dictionary
dictionary[0].key; //get the key of a particular object

See the DEMO here


text:
Q: Связь расширения для браузера и активной страницы Пробую сделать расширение для браузера и столкнулся с одним непонятным моментом. Как сделать, чтобы скрипт мог видеть сразу и popup расширения, и активную страницу в браузере? Для примера: в расширении поле для ввода и кнопка. Вводим текст в поле, нажимаем кнопку и в какой-то элемент на странице в браузере вставляем то, что ввели. Прошу дать хотя бы наводку.
P.s.: расширение делаю для оперы, если это важно

A: Можно воспользоваться несколькими вариантами:

*

*самый простой, но не всегда удобный, комбинировать отправку/прием сообщений

*

*runtime.sendMessage - отправить сообщение, но только не скрипту контента, например из popup в background

*tabs.sendMessage - отправить сообщение табу

*runtime.onMessage - устанавливает слушателя сообщений

*немножко сложнее, но максимально гибкий

*

*runtime.connect - из всех зависимых скриптов(контент,popup, и т.п.) запрашиваем соединение с background

*runtime.onConnect - в background принимаем соединиения

*... далее, в этом варианте, используем для связи долгоживущий порт, по которому очень легко передавать/получать сообщения в обе стороны.

PS: Расширение лучше делать и тестировать в Chrome, а после установить его в Оперу.


text:
Q: Why can't I buffer polygons in ArcGIS Pro? I've created a polygon by merging several polygons from the same layer using the merge option under Edit menu. Now I cannot buffer the resulting polygon. I tried repair geometry it didn't help. I'm getting an error message saying WARNING 000117: Warning empty output generated. How can I solve this? The distance unit I used is meters. I'm using buffer tool. I set side type to "exclude polygon itself", method: planar and no dissolve.
EDIT: I can't buffer unmerged normal polygons either.
CRS EDIT: CRS of the current map: WGS 1984 Aux...
          CRS of the layer to be buffered: WGS 1984 Aux... (set when creating
                                                            the feature class)
          CRS for the output set in the environments tab: WGS 1984 Aux...
NOTE: I'm using ArcGIS Pro 2.2.3.

A: It turns out that it was the environment that I should have set. I set the environment to a layer that contains the layer to be buffered and it worked. So make sure that the environment is set big enough to comprise the layer itself and the buffer.