text:
Q: How to automatically sum in excel for filtered data? I am going to build a TIME SHEET. I want to sum the total amount of hours worked for a project chosen from drop-down menu.

Total Worked Hours for Project No 4 will be the total hours worked for project no 4 e.g. 50 Hours

A: You can just reference the value of the cell directly!
So, if the drop down list is in cell A1, then this is your value (the value of A1)! In your case, just reference $B$8
This means you don't need to stick it else where, but instead just use a VLookUp() function.

Original Answer (partly incorrect as I hadn't realised how the OP had implemented the drop down list)
I offer this as an option where you don't need to use Macros. I'm sure there will be a more elegant way, but this will suffice.
Create a new worksheet in your Excel file, call it Result. Right click on the drop down list, format control and select the cell link - choose A1 in your new worksheet.
Now, you can reference this cell so you can perform a look up and concatenate this new value.
In my example below, I have 1 combo box, and the selected value is G4

As you can, see, it displays the value 15 as it should be
The code in cell F11 is
=VLOOKUP(G4,I2:J8,2)

When I select change the value in the drop down list, to a 9, for example, it displays 50 in my value cell.
At this stage, you should be able to update your code so it can perform the maths for you as well.

A: I think you are looking for a combination of VLOOKUP() and SUMIF().
SUMIF() allows you to check the value of the cell before summing, or check the value of a cell in one range before summing a cell in another range.
For example,


text:
Q: Changing the background of a column cell value of an based on the Value (HTML Reported created by awk) I have created an HTML Table (Data from the DB) using awk. I am stuck at creating the Background of a column, depending on the cell value. Not much idea about css. I am abble to change the ont bbased on the condition but not the background color. here is my code. If the status is less than 100 background should be red..else same bg as rest of the table..
BEGIN {
  print "

The report provides overall Percentage Secured in the given subjects.

"
  print "
"
}

NR==1 {
  # Header row
  print "
"

  for ( i = 1; i <= NF; i++ ) {
    print ""$i"	"
  }
  print "
"
}

NR>1 {
  # Data rows
  print "
"
  if( $i < 100 ) {
    color="RED"  \\ Background should be Red if the status is less tha 100\\
}
  if( $i == 100 ) {
    color="BLACK" \\Same background as rest o the table\\
  }
  print ""$1"	"$2"	"$3"	"$4"	"$5"	"
  print "
"
}
END {
  print "
"
}

A: This is an old but good reference for basic css properties: http://www.htmlhelp.com/reference/css/properties.html
I would do
BEGIN {
  print ""
  print "<title> Set the page title here </title>"
  print ""
  print ""
  # use P tags, not BR line breaks -- easier to apply styling.
  print "
The report provides overall Percentage Secured in the given subjects.
"
  print "
"
}

NR == 1 {...} # I would use TH tags for the headers

NR > 1 {
  # Data rows
  print "
"
  for ( i = 1; i <= NF; i++ ) {
    class = $i < 100 ? "class=\"error\"" : ""
    printf "%s	\n", class, $i
  }
  print "
"
}

Putting styles in one place will help if

redpajama_set_name: RedPajamaStackExchange


text:
Q: Special terminal blocks for PT100? I'm about to lay out a board that will connect to a 4 wire PT100 sensor. Are regular screw terminal block connectors OK or do I need something more specialist? I am mainly thinking about possible thermocouple effects and noise/shielding

A: It totally depends on your accuracy requirements and your error budget. For normal applications, nothing special is required other than normal care for a low-level precision DC amplfier.
If you have a pathological situation in the environment (lots of temperature gradient), extreme accuracy requirements and/or are operating at a very low excitation then you might want to start thinking about low-thermal-EMF solders and terminal blocks with low Seebeck coefficients relative to copper or whatever material is being used for the interconnections. First calculate how many uV error you can tolerate (input-referred, of course) then you can make quantitative judgements.
Reasonable thermal EMFs will cancel if they are equal, so symmetry is a goal. For example, it should be obvious that you want to put the terminals with the force on the outside and sense terminals next to each other on the inside (Force/Sense/Sense/Force) and keep the layout around the center two terminals of the block as symmetrical as possible (including heat flow paths).
Electrical shielding is normally not provided by the terminal block, but by the instrument housing features. In particular, PCB-mount terminal blocks usually have no shielding at all.


text:
Q: CRM 2011 connect to organization.svc using C# The CRM 2011 is setup with ADFS and HTTPS. I'm trying to connect to organization.svc from custom web page which sits on the same IIS with CRM 2011 but as a different web site using this code:
OrganizationServiceProxy serviceProxy;
ClientCredentials clientCredentials = new ClientCredentials();
clientCredentials.UserName.UserName = "admin";
clientCredentials.UserName.Password = "pass";

Guid contactId = Guid.Empty;

Uri OrganizationUri = new Uri(String.Format("https://organization.crmdev.com:port/XRMServices/2011/Organization.svc"));

Uri HomeRealmUri = new Uri(String.Format("https://organization.crmdev.com:port/XRMServices/2011/Discovery.svc"));

using (serviceProxy = new OrganizationServiceProxy(OrganizationUri, null, clientCredentials, null))
{
    serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
    IOrganizationService service = (IOrganizationService)serviceProxy;
    Entity contact = new Entity("contact");
    contact.Attributes["lastname"] = "oi oi";
    contactId = service.Create(contact);
}

It returns error message:
An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.ID3242: The security token could not be authenticated or authorized.
and in the event viewer I see error:
Account For Which Logon Failed:
    Security ID:        NULL SID
    Account Name:       admin
    Account Domain:
Failure Reason:     Unknown user name or bad password.

although I give the correct user name and password..
and if I try to replace:
using (serviceProxy = new OrganizationServiceProxy(OrganizationUri, null, clientCredentials, null))

with:
using (serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealUri, clientCredentials, null))

it returns:
Object reference not set to an instance of an object.
because serviceProxy is null.

A: So, I'm just starting to use ADFS myself, I would suggest having a read of Active Directory and Claims-Based Authentication if you havnt already.
Also from looking at your code I don't think your HomeRealmUri is correct. You appear to have given it the address of the CRM Discovery Service. I think you are okay to leave it as null if you only have the single ADFS in play. As described in the MSDN here.
I would have expected it to look more like this: urn:federation:contoso
For the user name I believe you need to specify the domain, which you usually have to do in this format: username@domain
You might also want to look at this example its a single sign on web page that talks to Crm, which sounds a lot like what your trying to achieve.
Good luck.

A: I've finally figured it out :)
I was missing the "/organization", meaning the organizationUri should be:
 Uri OrganizationUri = new Uri(String.Format("https://organization.crmdev.com:port/organization/XRMServices/2011/Organization.svc"));

I've figured it out when I used this code:
IDiscoveryService discoveryService = new DiscoveryServiceProxy(discoveryUri, null, userCredentials, null);

            RetrieveOrganizationRequest orgRequest =
                                        new RetrieveOrganizationRequest()
                                        {
                                            UniqueName = "organization name",
                                            AccessType = EndpointAccessType.Default,
                                            Release = OrganizationRelease.Current
                                        };
            RetrieveOrganizationResponse org =
                    (RetrieveOrganizationResponse)discoveryService.Execute(orgRequest);

And saw the endpoins that the organization have include the "/organization" in the Uri..


text:
Q: How to use REGEX in StepArgumentTransformation to find prefixed string I want to use StepArgumentTransformation of SpecFlow to transform all strings prefixed with "key:" to something else. I don't get around on how to use the right regular expression.
Lets say I have the following step in my feature file:
Given a user is logged in with key:testkey and has password key:testpassword and username John

Which leads to this step definition:
[Given(@"a user is logged in with (.*) and has password (.*) and username (.*)")]
public void GivenUserIsLoggedIn(string key, string password, string username)
{
    // To stuff
}

Now I want to change the key values by using step argument transformation:
[StepArgumentTransformation(@"add correct regular expression here")]
public string TransformKeys(string value)
{
    // Do transformation
    return result;
}

I only want values prefixed with "key:" to enter the transformation method. How can I achieve this? I tried several stuff like
[StepArgumentTransformation(@"key:.*")
[StepArgumentTransformation(@"(key:.*)")
[StepArgumentTransformation(@"key:\w+")

But i either get error "parameter count mismatch" or the transformation method isn't entered at all.

A: Note: I am using specflow3 as version
Scenario: stackoverflow usecase
    Given a user is logged in with key:testkey and has password key:testpassword and username John

In step definition:
[Given(@"a user is logged in with (key:.*) and has password (key:.*) and username John")]
        public void GivenAUserIsLoggedInWithKeyTestkeyAndHasPasswordKeyTestpasswordAndUsernameJohn(string username, string password)
        {
            var user = username;
            var pass = password;

            Console.Write("username: {0} and password: {1} ", user, pass );
        }

[StepArgumentTransformation(@"key:(.*)")]
        public string ValueForKey(string value)
        {
            return value;
        }


text:
Q: Clean url in php with two get parameters I am working on a PHP script that uses clean URIs.
My problem is, that I have one page that first uses no get parameter, then one and at the end two.
The line in the .htaccess file currently looks like this:
 RewriteRule ^birthing-records/([^/]+)/?$ birthing-records.php?url=$1 [L,QSA,NC]

But if I add the second parameter like this:
RewriteRule ^birthing-records/([^/]+)/([^/]+)/?$ birthing-records.php?url=$1&second=$2 [L,QSA,NC]

The script redirects me to the error page.
How do I have to set this up?
Do I need two lines in the .htaccess for that case?
I would normally solve this by simply calling another page but I would like to keep the exact URIs I am using right now because all of those pages are indexed at Google. I would really appreciate any help.

A: You need one rule for each, otherwise whenever you put one param it'll break.
RewriteRule ^birthing-records/([^/]+)/?$ birthing-records.php?url=$1 [QSA,NC]
RewriteRule ^birthing-records/([^/]+)/([^/]+)/?$ birthing-records.php?url=$1&second=$2 [L,QSA,NC]

Thanks to @Martin for this note: that the L option of the first one has been removed since the L option indicates the last rule to be run (only one rule can exist with the L option)
Otherwise, as far as I can tell, they each work fine individually, but if you want to accept 1 OR 2 parameters, then two rules is what you need.
You can test htaccess stuff here: http://htaccess.mwl.be/


text:
Q: How to encyrpt a message using someone's pkcs7 signed-data? i need to send a XML data to applications that check data integrity.
demodata.pem (http://privatepaste.com/376402542e)
ca.pem (http://privatepaste.com/85fff7bfe3)
D:\stest\wz\apptest\dist\q\realq>openssl smime -verify -inform pem -in demodata.pem -CAfile ca.pem -out out.xml
Verification successful

D:\stest\wz\apptest\dist\q\realq>

so i refer below link to make a new messages.
https://unix.stackexchange.com/questions/118265/how-to-encyrpt-a-message-using-someones-ssl-smime-p7s-file
D:\stest\wz\apptest\dist\q\realq>openssl pkcs7 -in demodata.pem -inform pem -print_certs -out smime.pem

[smime.pem]
-----BEGIN CERTIFICATE-----
MIIDeDCCAuGgAwIBAgIBBDANBgkqhkiG9w0BAQQFADCBiDELMAkGA1UEBhMCS1Ix
EDAOBgNVBAgTB3dpenZlcmExDjAMBgNVBAcTBXNlb3VsMRAwDgYDVQQKEwd3aXp2
ZXJhMRAwDgYDVQQLEwd3aXp2ZXJhMRIwEAYDVQQDEwlheG1zZXJ2ZXIxHzAdBgkq
hkiG9w0BCQEWEHJvb3RAd2l6dmVyYS5jb20wHhcNMDgxMTE2MDYzMjA1WhcNMjkw
OTA3MDYzMjA1WjB7MQswCQYDVQQGEwJLUjEOMAwGA1UECBMFc2VvdWwxDjAMBgNV
BAcTBXNlb3VsMQwwCgYDVQQKEwNrZWIxDDAKBgNVBAsTA2tlYjESMBAGA1UEAxMJ
a2ViLmNvLmtyMRwwGgYJKoZIhvcNAQkBFg1heG1Aa2ViLmNvLmtyMIGfMA0GCSqG
SIb3DQEBAQUAA4GNADCBiQKBgQDqiAmyc1N+9/+dsOvA8ZvjpAHkF4ZmhSdjf2ZN
9xoh/M6z3YqkTHdchaAdTuiCSvAHiITYgCPEQ4h95ur2/0SdBFk7sbbmNmrhJWTv
KypizOKnJ27pVrNs/HhmMDWw3g0TQmwgDG8pUwR0M2tfP/Z5gNeFK49BnGZMCYJi
4zyQGwIDAQABo4H9MIH6MAkGA1UdEwQCMAAwLAYJYIZIAYb4QgENBB8WHU9wZW5T
U0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1UdDgQWBBRzwPiRKm5PWVsjsSat
FxRTyi3zWjCBnwYDVR0jBIGXMIGUoYGOpIGLMIGIMQswCQYDVQQGEwJLUjEQMA4G
A1UECBMHd2l6dmVyYTEOMAwGA1UEBxMFc2VvdWwxEDAOBgNVBAoTB3dpenZlcmEx
EDAOBgNVBAsTB3dpenZlcmExEjAQBgNVBAMTCWF4bXNlcnZlcjEfMB0GCSqGSIb3
DQEJARYQcm9vdEB3aXp2ZXJhLmNvbYIBADANBgkqhkiG9w0BAQQFAAOBgQCd3RYF
Nn22ca9x1lD/vvKuDk+DM5/448kKowu0zVheWvaU/GrKTCvtyJNMnr87dEn219BE
iAczBxzYaXnQAK09vptCKbc+tc/QG0NRalSxidIiuPvbIjzko/j4IuX6IWOR+5Ka
/EhbG4N5WrmKZkuSpuFxrwdbh5i/AtEpkqBv9w==
-----END CERTIFICATE-----

D:\stest\wz\apptest\dist\q\realq>openssl smime -encrypt -text -in newxml.txt -out newdata.der -outform der smime.pem
Loading 'screen' into random state - done

D:\stest\wz\apptest\dist\q\realq>openssl smime -verify -inform der-in newdata.der -CAfile ca.pem
Verification failure
8476:error:21075071:PKCS7 routines:PKCS7_verify:wrong content type:.\crypto\pkcs
7\pk7_smime.c:285:

D:\stest\wz\apptest\dist\q\realq>

but as you can see, Verification is failed.
so how can i make signed-data from someone's data. does it possible ?


text:
Q: Setting up a CSS Grid systems to allow for different number of items I am trying to setup a grid systems using CSS and SASS that allows for a different number of items to be proportionally spaced within its container, see image below:

The grid is 4 x 2 as you can appreciate so I need to find a way to span, fill or fit the column and rows to fill the space but since I'm learning its proven to be a challenge for me, I have a codepen with poor results, any advise will be much appreciated.
Here is my codepen "code":
* {
    font-family: sans-serif;
    font-size: 14px;
    color: white;
}
.container {
    width: 800px;
    margin: 0 auto;
}

.wrapper {
    width: 100%;
    margin: 20px 0;

    display: grid;
    grid-gap: 10px;

    grid-template-rows: fit-content(180px);
    grid-template-columns: repeat(auto-fit, minmax(180px, 2fr));
}

.item {
    background-color: orangered;
    height: 100px;
    width: 100%;
}

A: Something like this ?

.container {
    width: 300px;
    margin: 0 auto;
}

.wrapper {
    border: 1px solid;
    margin: 10px 0;
    padding: 10px;
    display: grid;
    grid-gap: 10px;

    /* Start with 4 columns to make it easier */
    grid-template-columns: repeat(4, 1fr);
}

.item {
    padding:10px;
    font-size:30px;
    background-color: orangered;
    grid-column: span 2;
}

/* spans the first element when there's only 3 */
.item:nth-last-child(3) {
    grid-row: span 2;
}

/* Selects the second element when there's 4 (the element we selected above) and rest it's grid span */
.item:nth-last-child(4) + .item {
    grid-row: span 1;
}

/* Spans the first element when there's 5 elements */
.item:nth-last-child(5) {
    grid-row: span 2;
}

/* Resets the column span of the rest of the elements when there's 5 elements */
.item:nth-last-child(5)~div {
    grid-column: span 1;
}

1

2

3

1

2

3

4

1

2

3

4

5


text:
Q: Layout, which will wrap it's content automatically? I have a composite A, which should contains another composite B.
Composite B will change it's size.
What layout should I apply to composite A, so that it will wrap composite B automatically?

A: I think that a GridLayout will work for you but keep in mind that you have to tell compositeB to SWT.FILL not the other way around:
Composite compositeA = new Composite(parent, SWT.NONE);
compositeA.setLayout(new GridLayout(1, false));

Composite compositeB = new Group(compositeA, SWT.NONE);
compositeB.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));


text:
Q: Is this a metric on the shift space? Consider
$$
\Omega_N:=\left\{\omega=(\ldots,\omega_{-1},\omega_0,\omega_1,\ldots): \omega_i\in\left\{0,1,\ldots,N-1\right\}\text{ for }i\in\mathbb{Z}\right\}
$$
and
$$
\Omega_N^R:=\left\{\omega=(\omega_0,\omega_1,\omega_2,\ldots): \omega_i\in\left\{0,1,\ldots,N-1\right\}\text{ for }i\in\mathbb{N}_0\right\}.
$$

I wonder, if then
  $$
d(x,y)=\begin{cases}2^{-(\ell-k)}\text{ if }k,\ell\text{ are maximal such that }x_{[k,\ell]}=y_{[k,\ell]}\\0, x=y\end{cases}
$$
  is a metric on both $\Omega_N$ and $\Omega_N^R$.

I think yes! However, I would like to hear your YES or NO, because I am not totally sure.

A: Let $\zeta\in\Omega_N^R$ be the constant $0$ sequence, and define $\omega=\langle\omega_k:k\in\Bbb N\rangle\in\Omega_N^R$ as follows:
$$\omega_k=\begin{cases}
1,&\text{if }k=2^n\text{ for some }n\in\Bbb N\\
0,&\text{otherwise}\;.
\end{cases}$$
Then $\omega$ agrees with $\zeta$ on arbitrarily long segments, but $\omega\ne\zeta$, so $d(\omega,\zeta)$ is undefined. For that matter, if we set $\omega_0=1$ and $\omega_k=0$ for $k>0$, then $\omega$ agrees with $\zeta$ on an infinite segment. The situation with $\Omega_N$ is just as bad.
For $\Omega_N^R$ you can fix matters by defining
$$\delta(x,y)=\min\{k\in\Bbb N:x_k\ne y_k\}$$
for $x\ne y$ and then setting $d(x,y)=2^{-\delta(x,y)}$.
For $\Omega_N$ you can do something similar: if $x\ne y$ let
$$\delta(x,y)=\min\{k\in\Bbb N:x_k\ne y_k\text{ or }x_{-k}\ne y_{-k}\}\;,$$
and then set $d(x,y)=2^{-\delta(x,y)}$.
In both cases you get a metric, and the space itself is of course a Cantor set.


text:
Q: Can´t populate spinner from string array in android I have problem with populating a spinner with items from a string array. When I start the emulator nothing is shown in the spinner. The spinner is shown and it´s empty,but when I click on It nothing happens.
Here is my activity:
package org.example.anders.eazy;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class StartActivity extends Activity {
    Spinner workoutSpinner;
    ArrayAdapter<CharSequence> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        workoutSpinner = (Spinner)findViewById(R.id.spinnerWorkout);
        adapter =ArrayAdapter.createFromResource(this,R.array.workout_name,android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        workoutSpinner.setAdapter(adapter);
        workoutSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(getBaseContext(),parent.getItemAtPosition(position)+" selected", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

}

My layout file for activity:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="org.example.anders.eazy.StartActivity">

    <Button
        android:id ="@+id/push_button"
        android:layout_width="180dp"
        android:layout_height="180dp"
        android:text="@string/startWorkout"
        android:background="@drawable/button_bg_round"
        android:padding="15dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        />

    <TextView android:text="@string/workout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/push_button"
        android:id="@+id/WorkoutText"/>

    <Spinner
        android:id="@+id/spinnerWorkout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/WorkoutText"/>

</RelativeLayout>

And my string array in string file looks like this:
<!-- Spinner options-->
<string-array name="workout_name">
    <item>Chest Workout</item>
    <item>Leg Workout</item>
    <item>Arms Workout</item>
</string-array>

A: Can you try this?
class YourActivity extends AppCompat {
    Spinner spinner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);

        spinner = (Spinner) findViewById(R.id.spinner_id);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,     getResources().getStringArray(R.array.your_array));

        spinner.setAdapter(adapter);
    }
}


text:
Q: iPhone 5s Touch ID sensor API After a lot of rumors, Apple has announced the new iPhone 5s will have a biometric fingerprint sensor (Touch ID).
Has apple already released the API/SDK for this sensor? If so, can an example be provided?

A: Update iOS >= 8
As of iOS 8, the old part of this answer is no longer true. Apple has introduced the Local Authentication Framework, which allows you to utilize Touch ID in your applications
Quote + Sample code (Local Authentication Framework Reference)

The Local Authentication framework provides facilities for requesting authentication from users with specified security policies. For example, to request that the user authenticate using Touch ID you would use code such as this:

LAContext *myContext = [[LAContext alloc] init];
NSError *authError = nil;
NSString *myLocalizedReasonString = <#String explaining why app needs authentication#>;

if ([myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError]) {
    [myContext evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
                  localizedReason:myLocalizedReasonString
                            reply:^(BOOL succes, NSError *error) {
            if (success) {
                // User authenticated successfully, take appropriate action
            } else {
                // User did not authenticate successfully, look at error and take appropriate action
            }
        }];
} else {
    // Could not evaluate policy; look at authError and present an appropriate message to user
}

Old answer iOS < 7
From the September 10, 2013 keynote approximately 61 minutes into the presentation:

All fingerprint info is encrypted and stored inside the secure enclave
  in our new A7 chip. Here, it is locked away from everything else,
  accessible only by the Touch ID sensor. It's never available to other
  software, it's never stored on Apple's servers or backed up to iCloud.

As of yet, this is all the information that is available. That being said, this is speculation, but I think it's likely that there won't be an API for this. If anything, usage of the sensor, will only be done through interaction with the keychain allowing the OS to interact with the sensor, while keeping your app separate in its cozy little sandbox.
EDIT: It looks like it's true that we can't access the sensor. Here's a quote from an ALLThingsD article (linked below).

Apple Senior Vice President Phil Schiller confirmed to AllThingsD that
  developers won't get access to use a fingerprint as a means of
  authentication. He declined to comment on whether that might come in
  the future.

http://allthingsd.com/20130910/iphone-developers-wont-get-fingerprint-reader-authentication-option-for-now-anyway/


text:
Q: Listen to changes made by another application I've got two applications which are using the same mongo database and the same model/tabel. For example, both uses mongoose.model('foo', schema).

*

*The first application manages the data: Adds, changes and removes entries at the model foo

*The second application just listens on the data: It uses the data of foo.

The second application needs to know if the data of foo has changed. When I look at the documentation of mongoose, I just found the middlewares for save and remove. But when I'm add post hooks to the schema, they aren't triggered at the second application.
When I search generally for change hooks at mongo database, I mainly find information that is a few years old and says that MongoDB doesn't support triggers. An alternative is to listen to the oplog. But about oplog I found nothing on the mongoose page.
What is the best practice to achieve the goal to listen with mongoose to changes made by another application?

A: If your Mongo version is 3.6 or later, there is a possibility to listen the collection using Change Streams


text:
Q: Is there a way to cherry-pick lag variables in a VAR model? I modelling two time series of daily data. One is sign-ups and the other terminations of subscriptions. I'd like to predict the latter using the information contained in both variables with a VAR model using the vars package in R.
Since I'm modelling subscriptions I know that terminations are correlated with multiples of the sign-ups the months before. That is, a spike in sign-ups on May 10th, will lead to an increase in terminations in June 10th, July 10th and August 10th and so on, although the effect wears off.
My question is, can I cherry-pick which lags to use in the model somehow? Specifying
library(vars)

fit <- VAR(data, p=30)

gives you all the lags.


text:
Q: 'Customize' button in admin bar for CSS On the WordPress.org site I'm an admin for, we have a Customize button in the Admin bar (see very left):

This allows us to easily edit CSS on the front end without editing any of our files. I specifically remember reading that this feature allows us to write CSS that won't be overwritten by a theme update.
Now the time to update has come, and I'd like to absolutely confirm this. But I can't find any references to this button online.
What's this feature called? Is it on everyone's WordPress.org site, or is this some special feature of our theme or perhaps a plugin?

A: The WP Toolbar's Customize button will launch the Theme Customizer. This is standard on all WordPress sites, but it could be disabled via themes or plugins.
WordPress version 4.7 added the Custom CSS feature which will allow you to add your own styles to the activated theme. These styles will not be overridden when updating the theme.

...custom CSS safely stays available through updating and switching
  themes, starting fresh for each new theme.

Technically, it would be possible for a theme to stomp on any options or theme mods with an update, so you should always make a backup of your database and files before updating.


text:
Q: Listeners wouldn't work when a serialized panel is deserialized and retrieved (Java) I'm designing a JPanel in which there are some buttons which have their own action listeners and would do certain things when clicked (for example, one of them would remove the panel). In case the user closes the program, panels shouldn't be deleted and should be retrieved. for this purpose I serialize panels and deserialize them when needed. but the problem is listeners such as action listeners and mouse listeners wouldn't work when the panel is retrieved. is there any way to solve this problem? or is there any alternative to do the same thing without problem?
My panel code in case it's needed:
import jdk.internal.org.objectweb.asm.commons.SerialVersionUIDAdder;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.URL;
import java.text.Format;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Random;

public class Download extends JPanel implements Serializable {
    private String fileName;
    private boolean removed = false;
    private double downloadSpeed;
    private double downloadedSize;
    private double sizeOfFile;
    LocalTime downloadTime;
    LocalDate downloadDate;
    private boolean checked = false;
    private static final long serialVersionUID = 1113799434508676095L;
    JLabel test = new JLabel("test");

    public Download (MainPage c,URL url,LocalTime time,LocalDate date) {

        setLayout(null);
        downloadDate = date;
        downloadTime = time;
        fileName = url.getFile();
        JCheckBox checkbox = new JCheckBox();
        checkbox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED)
                    setChecked(true);
                else
                    setChecked(false);
            }
        });
        checkbox.setBackground(new Color(186,212,215));
        checkbox.setBounds(95,42,17,15);
        add(checkbox);
        MouseAdapter a = new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                super.mouseEntered(e);
                setBackground(new Color(224,235,252));
                checkbox.setBackground(new Color(224,235,252));
            }

            @Override
            public void mouseExited(MouseEvent e) {
                super.mouseExited(e);
                setBackground(new Color(186,212,255));
                checkbox.setBackground(new Color(186,212,255));
            }
        };
        UIManager.put("ProgressBar.background", new Color (235,255,255));
        UIManager.put("ProgressBar.foreground", new Color (10,109,63));
        UIManager.put("ProgressBar.selectionBackground", Color.RED);
        UIManager.put("ProgressBar.selectionForeground", Color.GREEN);
        setBackground(new Color(186,212,255));
        setPreferredSize(new Dimension(600,100));
        JPanel file = new JPanel();
      /*  test fileImg = new test("file.png");
        fileImg.setBounds(10,10,40,50);
        add(fileImg); */
        JLabel fileNameLabel = new JLabel(fileName);
        fileNameLabel.setBounds(100,5,400,15);
        fileNameLabel.setForeground(new Color(109,111,114));
        add(fileNameLabel);
        JProgressBar jpb = new JProgressBar(0,100);
        Random r = new Random();
        jpb.setValue(r.nextInt(100));
        jpb.setBounds(100,25,400,10);
        JLabel progressBarValue = new JLabel("%" + jpb.getValue() + "");
        progressBarValue.setBounds(510,18,25,20);
        add(progressBarValue);
        this.setBorder(BorderFactory.createMatteBorder(0,0,2,0,new Color(18,42,79)));
        addMouseListener(a);
        add(jpb);
        JButton trash = new JButton(new ImageIcon("trash.png"));
        trash.setBounds(130,40,25,25);
    /*    trash.setContentAreaFilled(false);
        trash.setFocusPainted (false);
        trash.setBorderPainted(false); */
        trash.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("text");
            }
        });
        add(trash);

        test.setBounds(180,40,25,25);
        test.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                super.mousePressed(e);
                System.out.println("text");
            }
        });
        add(test);
        double lower = 0;
        double upper = 999.99;
        sizeOfFile = Math.random() * (upper - lower) + lower;
        downloadSpeed = Math.random() * (upper - lower) + lower;
        downloadedSize = jpb.getValue() * sizeOfFile / 100;
        JLabel downloadSpeedLabel = new JLabel (String.format ("%.1fKbs",downloadSpeed));
        JLabel downloadedSizeLabel = new JLabel (String.format ("%.1fMG / %.2fMG",downloadedSize,sizeOfFile));
        downloadedSizeLabel.setForeground(new Color(109,111,114));
        downloadSpeedLabel.setForeground(new Color(109,111,114));
        downloadSpeedLabel.setBounds(250,35,100,30);
        downloadedSizeLabel.setBounds(420,35,150,30);
        add(downloadSpeedLabel); add(downloadedSizeLabel);

    }

    public boolean isRemoved() {
        return removed;
    }

    public void setRemoved(boolean removed) {
        this.removed = removed;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public double getDownloadSpeed() {
        return downloadSpeed;
    }

    public void setDownloadSpeed(double downloadSpeed) {
        this.downloadSpeed = downloadSpeed;
    }

    public double getDownloadedSize() {
        return downloadedSize;
    }

    public void setDownloadedSize(double downloadedSize) {
        this.downloadedSize = downloadedSize;
    }

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }

    public double getSizeOfFile() {
        return sizeOfFile;
    }

    public void setSizeOfFile(double size) {
        this.sizeOfFile = size;
    }
}


text:
Q: Wrappers/law of demeter seems to be an anti-pattern I've been reading up on this "Law of Demeter" thing, and it (and pure "wrapper" classes in general) seem to generally be anti patterns. Consider an implementation class:
class FluidSimulator {
    void reset() { /* ... */ }
}

Now consider two different implementations of another class:
class ScreenSpaceEffects1 {
    private FluidSimulator _fluidDynamics;
    public FluidSimulator getFluidSimulator() { return _fluidDynamics; }
}

class ScreenSpaceEffects2 {
    private FluidSimulator _fluidDynamics;
    public void resetFluidSimulation() { _fluidDynamics.reset(); }
}

And the ways to call said methods:
callingMethod() {
   effects1.getFluidSimulator().reset(); // Version 1
   effects2.resetFluidSimulation();      // Version 2
}

At first blush, version 2 seems a bit simpler, and follows the "rule of Demeter", hide Foo's implementation, etc, etc. But this ties any changes in FluidSimulator to ScreenSpaceEffects. For example, if a parameter is added to reset, then we have:
class FluidSimulator {
    void reset(bool recreateRenderTargets) { /* ... */ }
}

class ScreenSpaceEffects1 {
    private FluidSimulator _fluidDynamics;
    public FluidSimulator getFluidSimulator() { return _fluidDynamics; }
}

class ScreenSpaceEffects2 {
    private FluidSimulator _fluidDynamics;
    public void resetFluidSimulation(bool recreateRenderTargets) { _fluidDynamics.reset(recreateRenderTargets); }
}

callingMethod() {
   effects1.getFluidSimulator().reset(false); // Version 1
   effects2.resetFluidSimulation(false);      // Version 2
}

In both versions, callingMethod needs to be changed, but in Version 2, ScreenSpaceEffects also needs to be changed. Can someone explain the advantage of having a wrapper/facade (with the exception of adapters or wrapping an external API or exposing an internal one).
EDIT: One of many real examples for which I ran into this rather than a trivial example.

A: This is obviously an artificial example.  In many real cases, callingMethod (in real life, there can multiple callingMethods) can remain blissfully unaware that Foo.doSomething has changed, because Bar insulates it.  For example, if I use a stable printing API, I don't have to be concerned about my printer's firmware adding support for glossy printing.  My existing black-and-white printing code keeps on working.  I suppose you would group this under "adapter", which I think it much more common than you imply.
You are right that sometimes callingMethod must be changed too.  But when the Law of Demeter is used properly, this will only occur rarely, usually to take advantage of new functionality (as distinct from a new interface).
EDIT: It seems quite possible that callingMethod does not care whether render targets are recreated (I'm assuming this is a question of performance v. accuracy).  After all, "We should forget about small efficiencies, say about 97% of the time" (Knuth).  So ScreenSpaceEffects2 could add a resetFluidSimulation(bool) method, but have resetFluidSimulation() keep working (without change to callingMethod) by calling _fluidDynamics.reset(true) behind the scenes.

A: The question is, does callingMethod() need to know whether to recreate the rendering tables?
Suppose some given execution of callingMethod() does or does not need to recreate the rendering tables.  In that case you extend the wrapper with a new method.  Then you just need to call the new method from just the appropriate instances of callingMethod().
class ScreenSpaceEffects2 {
    private FluidSimulator _fluidDynamics;
    public void resetFluidSimulation() { _fluidDynamics.reset(false); }
    public void resetFluidSimulationWithRecreate() { _fluidDynamics.reset(true); }
}

Alternatively the decision to recreate may belong somewhere else entirely ...
class ScreenSpaceEffects2 {
    private FluidSimulator _fluidDynamics;
    public void resetFluidSimulation() {
             _fluidDynamics.reset( someRuleEngine.getRecreateRenderTables() ); }
}

... in whch case nothing in callingMethod() need change at all.

A: The main difference is that in version 1, as provider of the Bar abstraction, you have no control on how Foo is exposed. Any change in Foo will be exposed to your clients, and they will have to bear with it.
With version 2, as provider of abstraction Bar, you can decide if and how you want to expose the evolutions. It will depend only on the Bar abstraction, and not Foo's. In your example, your Bar abstraction may already know which integer to pass as argument, and thus you will be able to let your users transparently use the new version of Foo, with no change at all.
Suppose now Foo evolves, and require the user to call foo.init() before any call to doSomething. With version 1, all users of Bar will need to see that Foo changed, and adapt their code. With version 2, only Bar has to be changed, its doSomething calling init if needed. This leads to less bugs (only the author of abstraction Bar has to know and understand abstraction Foo and less coupling between classes.


text:
Q: Looking for basic explanation on unity matchmaker (5.4) and how to use in scripts Having decided to do Networking through Unity over Photon due to price (if there is a better way of networking let me know) I have been trying to create a simple unity matchmaker where when a user enters the game they first look for any other match (AKA rooms / games), if there is one they join it, if there isn't one they create one. However I am struggling to find a clear explanation of how to use the unity matchmaker, so I can develop code to get my desired behavior which seems even trickier as it seems unity is changing it's networking system a lot in recent updates so I believe anything before 5.4 is currently out-of-date. The only useful thing I have found is this example code but I want to understand the system more so I don't miss any key concepts, which is likely as I am fairly beginner-ish.
So what I am asking you today is can you direct me to a clear explanation of the matchmaking system (including scripting) which is relevant to the current unity or, admittedly much harder and more time consuming, could you try to do it yourself and it will serve as future reference for others like me.
Thanks for reading, of course any answers will be greatly appreciated.
[i work in c#]
EDIT:
I understand my question is very difficult to answer so I am going to test out the example code until i get the desired behavior and post any errors which i cannot solve.
Problem 1

*

*I have copied the exact code (Included below for easier reference) into a script which i have attached to my network manager. But I am getting errors due to protection levels -

I have two theories on how to solve this -

*

*Changing the method accessors

*Not deriving the script from monobehaviour

I am currently testing them out, any advice on how to solve this would be very useful. I wonder if I should report this to unity as to me it seems to be a wrong example in unity docs which say it is updated for 5.4. Thanks.
Problem 2
I have created this script and have run it in the editor attached to an empty GameObject with single network manager, I get no compiler errors but when I run it debugs "ERROR: Match Search Failure" which means the listmatches funtion was unsuccessful, my script is below -
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Networking.Match;
using UnityEngine.Networking.Types;
using System.Collections;
using System.Collections.Generic;

public class MyMatchMaker : MonoBehaviour {
    bool done;
    // Use this for initialization
    void Start () {
        NetworkManager.singleton.StartMatchMaker();
        NetworkManager.singleton.matchMaker.ListMatches(0, 20, "Match", false, 0, 1, OnMatchList);
        Debug.Log("Searching");
    }

    public virtual void OnMatchList(bool success, string extendedInfo, List<MatchInfoSnapshot> matchList)
    {
        if (success)
        {
            if (matchList.Count != 0)
            {
                Debug.Log("Matches Found");
                NetworkManager.singleton.matchMaker.JoinMatch(matchList[0].networkId, "", "", "", 0, 1, OnMatchJoined);
            }
            else
            {
                Debug.Log("No Matches Found");
                Debug.Log("Creating Match");
                NetworkManager.singleton.matchMaker.CreateMatch("Match", 2, true, "", "", "", 0, 1, OnMatchCreate);
            }
        }
        else
        {
            Debug.Log("ERROR : Match Search Failure");
        }
    }

    public virtual void OnMatchJoined(bool success, string extendedInfo, MatchInfo matchInfo)
    {
        if (success)
        {
            Debug.Log("Match Joined");
            MatchInfo hostInfo = matchInfo;
            NetworkManager.singleton.StartClient(hostInfo);

            OnConnect();
        }
        else
        {
            Debug.Log("ERROR : Match Join Failure");
        }

    }

    public virtual void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo)
    {
        if (success)
        {
            Debug.Log("Match Created");

            MatchInfo hostInfo = matchInfo;
            NetworkServer.Listen(hostInfo, 9000);
            NetworkManager.singleton.StartHost(hostInfo);

            OnConnect();
        }
        else
        {
            Debug.Log("ERROR : Match Create Failure");
        }
    }

    void OnConnect ()
    {
        if (Network.isServer)
        {
            Debug.Log("You are Server");
        }
        else if (Network.isClient)
        {
            Debug.Log("You are Client");
        }
        else
        {
            Debug.Log("ERROR : MatchMaking Failed, Peer type is neither Client nor Server");
        }
    }
}

Thanks, hopefully you may be able to see where i have gone wrong.
@Programmer

A: Ah... Got this code working I debuged the information string in the call back and had to change a few project settings.
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Networking.Match;
using UnityEngine.Networking.Types;
using System.Collections;
using System.Collections.Generic;

public class MyMatchMaker : MonoBehaviour {
    bool done;
    // Use this for initialization
    void Start () {
        NetworkManager.singleton.StartMatchMaker();
        NetworkManager.singleton.matchMaker.ListMatches(0, 20, "Match", false, 0, 1, OnMatchList);
        Debug.Log("Searching");
    }

    public virtual void OnMatchList(bool success, string extendedInfo, List<MatchInfoSnapshot> matchList)
    {
        if (success)
        {
            if (matchList.Count != 0)
            {
                Debug.Log("Matches Found");
                NetworkManager.singleton.matchMaker.JoinMatch(matchList[0].networkId, "", "", "", 0, 1, OnMatchJoined);
            }
            else
            {
                Debug.Log("No Matches Found");
                Debug.Log("Creating Match");
                NetworkManager.singleton.matchMaker.CreateMatch("Match", 2, true, "", "", "", 0, 1, OnMatchCreate);
            }
        }
        else
        {
            Debug.Log("ERROR : Match Search Failure");
        }
    }

    public virtual void OnMatchJoined(bool success, string extendedInfo, MatchInfo matchInfo)
    {
        if (success)
        {
            Debug.Log("Match Joined");
            MatchInfo hostInfo = matchInfo;
            NetworkManager.singleton.StartClient(hostInfo);

            OnConnect();
        }
        else
        {
            Debug.Log("ERROR : Match Join Failure");
        }

    }

    public virtual void OnMatchCreate(bool success, string extendedInfo, MatchInfo matchInfo)
    {
        if (success)
        {
            Debug.Log("Match Created");

            MatchInfo hostInfo = matchInfo;
            NetworkServer.Listen(hostInfo, 9000);
            NetworkManager.singleton.StartHost(hostInfo);

            OnConnect();
        }
        else
        {
            Debug.Log("ERROR : Match Create Failure");
        }
    }
}


text:
Q: Why npm give me this output? I have a problem with ionic, npm ecc.
I want to write an app with Ionic framework using Angular.
I installed Node.js, ionic, angular, @ionic/angular, native-run, cordova-res, @capacitor/camera, @capacitor/storage, @capacitor/filesystem.
But when I put the command ionic start this is the output:
? Starter template: sidemenu
√ Preparing directory .\ludolambru in 1.97ms
√ Downloading and extracting sidemenu starter in 367.60ms
> ionic integrations enable capacitor --quiet -- ludolambru io.ionic.starter
> npm.cmd i --save -E @capacitor/core@latest
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: ionic-app-base@0.0.0
npm ERR! Found: @angular/compiler@12.1.5
npm ERR! node_modules/@angular/compiler
npm ERR!   dev @angular/compiler@"~12.1.1" from the root project
npm ERR!   peer @angular/compiler@"12.1.5" from @angular/compiler-cli@12.1.5
npm ERR!   node_modules/@angular/compiler-cli
npm ERR!     dev @angular/compiler-cli@"~12.1.1" from the root project
npm ERR!     peer @angular/compiler-cli@"^12.0.0 || ^12.1.0-next" from @angular-devkit/build-angular@12.1.4
npm ERR!     node_modules/@angular-devkit/build-angular
npm ERR!       dev @angular-devkit/build-angular@"~12.1.1" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/compiler@"12.2.6" from @angular/localize@12.2.6
npm ERR! node_modules/@angular/localize
npm ERR!   peerOptional @angular/localize@"^12.0.0 || ^12.1.0-next" from @angular-devkit/build-angular@12.1.4
npm ERR!   node_modules/@angular-devkit/build-angular
npm ERR!     dev @angular-devkit/build-angular@"~12.1.1" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\latin\AppData\Local\npm-cache\eresolve-report.txt for a full     report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\latin\AppData\Local\npm-cache\_logs\2021-09-17T09_15_32_264Z-    debug.log
[ERROR] An error occurred while running subprocess npm.

        npm.cmd i --save -E @capacitor/core@latest exited with exit code 1.

    Re-running this command with the --verbose flag may provide more information.

Installing dependencies may take several minutes.

  ──────────────────────────────────────────────────────────────

        Ionic Appflow, the mobile DevOps solution by Ionic

           Continuously build, deploy, and ship apps
        Focus on building apps while we automate the rest

        Learn more: https://ion.link/appflow

  ──────────────────────────────────────────────────────────────

> npm.cmd i
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: ludolambru@0.0.1
npm ERR! Found: @angular/compiler@12.1.5
npm ERR! node_modules/@angular/compiler
npm ERR!   dev @angular/compiler@"~12.1.1" from the root project
npm ERR!   peer @angular/compiler@"12.1.5" from @angular/compiler-cli@12.1.5
npm ERR!   node_modules/@angular/compiler-cli
npm ERR!     dev @angular/compiler-cli@"~12.1.1" from the root project
npm ERR!     peer @angular/compiler-cli@"^12.0.0 || ^12.1.0-next" from @angular-devkit/build-angular@12.1.4
npm ERR!     node_modules/@angular-devkit/build-angular
npm ERR!       dev @angular-devkit/build-angular@"~12.1.1" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/compiler@"12.2.6" from @angular/localize@12.2.6
npm ERR! node_modules/@angular/localize
npm ERR!   peerOptional @angular/localize@"^12.0.0 || ^12.1.0-next" from @angular-    devkit/build-angular@12.1.4
npm ERR!   node_modules/@angular-devkit/build-angular
npm ERR!     dev @angular-devkit/build-angular@"~12.1.1" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

I tried to serch it on google but i didn't find anything. I don't know if I forgot some packages or I was wrong something else.

A: You have incompatible dependencies,
You have @angular/compiler@12.1.5 installed but @angular/localize@12.2.6 requires @angular/compiler@"12.2.6". I'm guessing you have package.json that looks like:
"@angular/compiler":"12.1.5",
"@angular/localize":"12.2.6"

You'll need to change that so that they can be resolved. It is hard to give explicit advice without seeing your package.json.


text:
Q: Get the most significant bit from an 8-bit value I know there are similar questions on this site, however, I couldn't seem to find something that really helped me out with the issue i'm having.
So far:
I have 1-byte (8-bits) that could be any combination of 1's and 0's.
Ex: 11000010 is my byte of data. (Little-Endian)
What i need to do is determine if the Most Significant Bit (MSB), in this case the 11, is either a 00, 01, 10, 11 and from there do some other things.
I have so far gotten the program to output the Byte as 11000010 (stored in a string) and am trying to extract the 11 from it.  (If i can figure that out then creating a switch case or if statement to check what the contents is simple enough on my own).
**I haven't been so good with C++ which is why i'm asking for assistance.
Any help is greatly appreciated.

A: You don't need to store it as a string, just use bitwise operators:
unsigned char myByte = 0xc2; // 11000010
char twoMost = (myByte & 0xff) >> 6; // 00000011

The 0xff "selects" (masks) only the first 8 bits, so that if the char type is actually bigger than 8 bits, then everything else is discarded.
By shifting 6 bits to the right, you get to keep only the two most significant. Then, you can apply a switch like:
switch(twoMost) {
    case 0: // 00
        doSomething();
        break;
    case 1: // 01
        doSomething();
        break;
    case 2: // 10
        doSomething();
        break;
    case 3: // 11
        doSomething();
        break;
    default:
        // This is not possible, but better output an error message
}

A: It seemes that you want to get the value of first two most significant bits.
This can be done by filtering them out and moving the value 6 bits to the left:
unsigned char input;
unsigned char output;

input = whatever_you_want;

output = input & 0xc0; //0xc00 = 0b11000000
output = output >> 6;

A: First, endianness has to do with the order of bytes in a word, not with the order of bits in a byte.
Second, you want two most significant bits, not the MSB.
That said, here's the code:
unsigned char c = Something(); //That's your byte; comes from somewhere
unsigned char x = c >> 6;

So if the MSBs are 11, the value of x will be 3. If it's 10, then 2. If 01, then 1. If 00, then 0.
Unsigned-ness of the variable is important; it makes the >> operator behave like a bitwise shift, not like arithmetic shift. With a signed char variable, you'd want the following expression instead:
char x = (c >> 6) & 3;

Signed-ness of the vanilla char datatype is compiler and platform specific, and can be affected by compiler options.


text:
Q: Phone Number Formatting Python Whenever i run my program is print the number 10 randomly and i don't know where its coming from. Anyone help me out?

def main():
    phoneNumber=int(input("Enter a 10 digit unformatted telephone number in the format ##########: "))
    tempNumber = []
    phoneNumber = str(phoneNumber)
    length = len(phoneNumber)
    index=0
    print(length)

    if (length ==10):
        print("The unformatted number is: ",phoneNumber)
    else:
        print("The telephone number was NOT entered in unformatted format ##########.")

    for num in phoneNumber:
        tempNumber.append(num)

    tempNumber.insert(0,"(")
    tempNumber.insert(4,")")
    tempNumber.insert(8,"-")
    phoneNumber = ''.join(tempNumber)
    print("The formatted number is: ",phoneNumber)

main()

A: You are printing the length of the input given by user, so that's why 10 is printed out (see statement no. 6 inside main() function).
phoneNumber = str(phoneNumber)
length = len(phoneNumber)
index = 0
print(length)  # <--- this statement is printing the length of the input


text:
Q: Size of canvas in kivy In my app I need to know how big the canvas is in pixels.
Instead calling canvas.size returns [100,100] no matter how many pixels the canvas is wide.
Can you please tell me a way to get how many pixels the canvas is wide and high?

A: There is no position nor size in a Canvas. Canvas act just as a container for graphics instructions, like Fbo that draw within a Texture, so it have a size.
In Kivy, Canvas.size doesn't exists, but i guess you called your widget a canvas. By default, a Widget size is 100, 100. If you put it into a layout, the size will be changed, when the layout will known its own size. Mean, you need to listen to the changes of the Widget.size, or use a size you known, like Window.size.

A: I'm gonna guess that you actually need the window size in order to know what your image boundaries are. In this case, you can use:
from kivy.core.window import Window
size = Window.size

And you can of course use the source image of your canvas with PIL or scipy etc. to get its resolution (which the canvas will match).

A: It seems that the canvas has a "size" of (100,100) whatever you do. The size you are looking for must be the widget size e.g.
If you have a FloatLayout and want to draw on it a rect that fills it
try:
f = FloatLayout
Rectangle(pos_hint={'x': 0, 'y': 0}, size=f.size)

and not
Rectangle(pos_hint={'x': 0, 'y': 0}, size=f.canvas.size)


text:
Q: Error Handling with Ajax in Rails 3 I'm creating a simple demo app that allows a user to enter their email address to register their interest in receiving beta access. The app then sends them a confirmation email that lets them know we've received their request. If you've ever signed up to be notified of a beta launch then you get the idea.
I'm curious about how to handle errors in Rails 3 while using AJAX. Before implementing my respond_to block I had a form that rendered a shared errors partial.
Here's the form.
<% if flash[:notice] %>

<%= flash[:notice] %>

<% end %>

Sign up to be notified when the beta launches.

<%= form_for @user, :remote => true do |form| %>

    <%= render '/shared/errors', :target => @user %>

    <%= form.label :email, "Your Email Address" %>
    <%= form.text_field :email %>

    <%= form.submit "Notify Me" %>
<% end %>

And here's the aforementioned errors partial.
<% if target.errors.any? %>

    <% target.errors.full_messages.each do |message| %>

<%= message %>

    <% end %>

<% end %>

Very standard stuff. The controller action looks like this.
def create
@user = User.new(params[:user])

respond_to do |format|
  if @user.save
    format.html { redirect_to :back, flash[:notice] = "Thanks for your interest! We'll let you know when the app is in beta." }
    format.js
  else
    format.html { render :action => :new }
    format.js
  end
end
end

Everything works perfectly before implementing ajax. If the form passes validation then they see the success flash message and if not then they see a list of errors. So now that i have a create.js.erb file how should I handle the errors without repeating myself or is that impossible. I obviously want to keep this as DRY as possible.

A: I'm not sure the rails remote form way to do it, but my standard mode of operation is to return objects on ajax request in this format:
{ success: true|false,
  data: "html or some other data",
  errors: {} } // jsonified ActiveModel::Errors object

It works very well and lets you render partials into the data field for use on the page, or you can loop through errors in the error object to insert error messages or highlight fields.

A: I have been facing the same problem a few days ago. I used remote => true option in my form to use Ajax in my Rails 3 application. After that, I have been looking for solution for validating my form fields. After trying a good number of jQuery / Javascript approaches (none of them worked for me though) I came to know about a superb gem called client_side_validations. It is very easy to install by following the instructions on github link (https://github.com/bcardarella/client_side_validations). It works like charm for client side validation of form fields, an awesome gem indeed. Hope this helps with people who are tired of looking for a simple solution for client side validation of model fields after using Ajax in Rails 3 application.

A: You can still render a shared partial for all .js errors in your js.erb file.
<% if @user.errors.any? %>
   var el = $('#create_user_form');
   // Create a list of errors
   <%= render :partial=>'js_errors', :locals=>{:target=> @user} %>
 <% else %>
     $('#users_list').append("<%= escape_javascript(render :partial=>"users/show", :locals=>{:user => @user }) %>");
    // Clear form
    el.find('input:text,textarea').val('');
    el.find('.validation-errors').empty();
<% end %>

And your partial could look like (Assuming jquery):
  <% target.errors.full_messages.each do |error| %>
    var errors = $('
');
    errors.append('
<%= escape_javascript( error ) %>
');
  <% end %>

But there's also ANOTHER option...It's even DRYer.
http://www.alfajango.com/blog/rails-3-remote-links-and-forms/
If you are working your way through ajax in rails 3, this guide is really the best for understanding responses and ajax rendering as it currently stands.
I worked through this guide and posted in the comments how you can actually use your HTML partials for both HTML and AJAX request responses.  I did it by accident and then followed up on how to do it.
Enjoy!
You can actually return straight-up html with your response just like before.
Here's the short version:
def create
     @something = Somethng.new(params[:something])
     if @something.save
       respond_with( @something, :status => :created, :location => @something ) do |format|
         format.html do
           if request.xhr?
             render :partial => "something/show", :locals => { :billable => @billable }, :layout => false
           end
         end
       end
       else
        respond_with( @something.errors, :status => :unprocessable_entity ) do |format|
          format.html do
            if request.xhr?
              render :partial => "something/new", :locals => { :something => @something }, :layout => false
            else
              render :action => :new
            end
          end
        end
      end
    end


text:
Q: File based routing in NodeJS/ExpressJS Is there a way to do the following in NodeJS (or ExpressJS)?
While I understand the flexibility routing offers, I pretty much dislike the way it has to be configured. (I am no expert in Express)
For example, the application structure is as shown below:
app
-- public // has all the static files.
-- dynamic // Root level file for something that contains all the dynamic pages
   -- index.nsf // NSF == node server file (Just making up a sample extension here).
                // NSF files have front matter and code like shown in section below
   -- posts // A directory
      -- view.nsf
      -- edit.nsf
   -- pages
      -- thankyou.nsf
      -- contactus.nsf

i.e when the user goes to the url "http://mydomain.com/pages/contactus", the content from that nsf file is rendered.
The NSF that I have in mind, will probably look like below - with just some YAML front matter
---
controller: contactUsController // A javascript file
layout: contact // Jade layout or HTML layouts
---

OR with some YAML front matter and layout as the content of the file.
---
controller: contactUsController
---
extends base
h1 This is the contact us page. Fill in the details below.

Even a one time configuration to setup a middleware like below would work:
app.use(app.**some_automatic_router**);
app.use(express.static(path.join(__dirname, 'public')));

Thank you.

A: Maybe you are looking for something like this :
https://npmjs.org/package/dynamic-routes


text:
Q: How to use Cookies in ANDROID? Its a login app that will ask user for its username and password and then send this data to some php script on server.This part is working properly. Now what I need is to maintain this session via cookies even if user closes this application so as to keep user logged in until and unless he logs out manually.
Following is my core code for this process
public class SignIn extends AppCompatActivity implements View.OnClickListener {

public Button blogin;
public TextView content, error, link_signup;

public EditText uname, pass;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_in);

    uname = (EditText) findViewById(R.id.uname);
    pass = (EditText) findViewById(R.id.pass);
    content = (TextView) findViewById(R.id.content);
    error = (TextView) findViewById(R.id.error);
    link_signup = (TextView) findViewById(R.id.link_signup);

    blogin = (Button) findViewById(R.id.blogin);

    blogin.setOnClickListener(this);
    link_signup.setOnClickListener(this);

}

public boolean validate() {
    boolean valid = true;

    String email = uname.getText().toString();
    String password = pass.getText().toString();

    if (email.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
        uname.setError("Enter a valid email address");
        error.setTextSize(20);
        error.setTextColor(Color.parseColor("#FFFFFF"));
        error.setBackgroundColor(Color.parseColor("#646464"));
        error.setText("Invalid Username or Password");

        valid = false;
    } else {
        uname.setError(null);
    }

    if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
        pass.setError("Enter a password between 4 and 10 alphanumeric characters");
        error.setTextSize(20);
        error.setTextColor(Color.parseColor("#FFFFFF"));
        error.setBackgroundColor(Color.parseColor("#646464"));
        error.setText("Invalid Username or Password");
        valid = false;
    } else {
        pass.setError(null);
    }

    return valid;
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.blogin:
            validate();
            new JsonTask().execute("https://www.aboutmyclinic.com/test.php", uname.getText().toString(), pass.getText().toString());
            break;
        case R.id.link_signup:
            startActivity(new Intent(this, Register.class));
            break;

    }

}

@Override
protected void onPause() {
    super.onPause();

    uname.setText("");
    pass.setText("");
    error.setText("");
    error.setBackgroundColor(Color.parseColor("#FFFFFF"));
}

public class JsonTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {

            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();

            connection.setReadTimeout(10000);
            connection.setConnectTimeout(15000);
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("firstParam", params[1])
                    .appendQueryParameter("secondParam", params[2]);

            String query = builder.build().getEncodedQuery();
            OutputStream os = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();

            connection.connect();

            InputStream inputStream = connection.getInputStream();
            StringBuffer buffer = new StringBuffer();

            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {

                buffer.append(line + "\n");
            }
            return buffer.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {

                }
            }

        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        JSONObject json = null;
        String sucessvalue = null;
        String errorvalue=null;
        try {
            json = new JSONObject(result);
            sucessvalue = json.getString("Success");
            errorvalue=json.getString("Error");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        if(sucessvalue!=null) {

            Intent i = new Intent(SignIn.this, login.class);
            i.putExtra("sucessval", sucessvalue);
            startActivity(i);
        }
        else
            content.setText(result);
    }
}
}

My php page looks like this:
<?php
$fp=$_POST['firstParam'];
$sp=$_POST['secondParam'];
if($fp=='badhe.percept@gmail.com' && $sp=='badhe')
echo "{Success:'Hellooo...'}";
else
echo "{Error:'something happened'}";
?>

A: I'm  using this solution. It will store your cookies in your Shared preferences. This will prevent you from losing the data if the app is closed.
Initialize it at the beginning of your app.
CookieManager cookieManager = new CookieManager(new PersistentCookieStore(getApplicationContext()),CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);


text:
Q: Version mismatch. H2O is version 3.22.0.1, but the h2o-python package is version 0.0.local I am following the H2O install manual. I can run the jar and get web access, but every time I install python packages via the instruction on the website I am getting the issue:
Version mismatch. H2O is version 3.22.0.1, but the h2o-python package is version 0.0.local
When running the h2o.init()
I am installing the h2o python on macOS using python 3.6 inside a fresh virtual environment I created.
Any Ideas

A: I had the same problem while trying to initiate h2o inside a virtual environment using jupyter notebook.
As it has been said on the previous thread OSError: Version mismatch while installing h2o? you probably have to kill the h2o cluster. In my case it worked with:
h2o.cluster().shutdown()

A: this question is a duplicate of this questions: OSError: Version mismatch while installing h2o?
basically you need to make sure your h2o.jar version matches the version you ahve for you python package. You can also find more of a walk through.
for the python package you might just need to uninstall the version you currently have with a pip uninstall and then reinstall the latest wheel file found on the H2O-3 downloads page: http://h2o-release.s3.amazonaws.com/h2o/rel-xia/1/index.html and click on the python tab.


text:
Q: await vs yield from for python https://stackoverflow.com/a/44273861/433570
says 'yield from' is old and we should learn 'await'.
But It doesn't say they are the same thing or they are different.
But I have some good book and videos which talks about yield from
Can I think yield from was replaced by await? and they are essentially the same thing?
https://www.youtube.com/watch?v=MCs5OvhV9S4
I have a book fluent python which also talks about yield from

*

*Edit

When I see some good books/videos like the above talking about yield from, could I substitute yield from with await in my mind?

A: Yes they are the same thing. Yield is the manual way of doing async await. See https://www.python.org/dev/peps/pep-0492/#new-coroutine-declaration-syntax where they detail that async await is just a coroutine (yield) underneath


text:
Q: It is impossible Debugging over Bluetooth Trying to debug an application on wear. Prior to this, using the emulator, we now have the device. Following the instructions, stopped on the line
In the Android Wear companion app, you should see the status change to:
Host: connected Target: connected
The phone status host: not connected target device is connected.
what could be the problem? I have a feeling that it is impossible to connect device.
P.s. USB debugging on my phone, and debugging via bluetooth on the clock included. App for my  phone (for my model LG G Watch), also downloaded and installed.

A: 1)Setup Devices for Debugging
Enable USB debugging on the handheld:
Open the Settings app and scroll to the bottom.
If it doesn't have a Developer Options setting, tap About Phone (or About Tablet), scroll to the bottom, and tap the build number 7 times.
Go back and tap Developer Options.
Enable USB debugging.
Enable Bluetooth debugging on the wearable:
Tap the home screen twice to bring up the Wear menu.
Scroll to the bottom and tap Settings.
Scroll to the bottom. If there's no Developer Options item, tap About, and then tap the
build number 7 times.
Tap the Developer Options item.
Enable Debug over Bluetooth.
2)Set Up a Debugging Session
On the handheld, open the Android Wear companion app.
Tap the menu on the top right and select Settings.
Enable Debugging over Bluetooth. You should see a tiny status summary appear under the option:
    Host: disconnected

    Target: connected

Connect the handheld to your machine over USB and run:
adb forward tcp:4444 localabstract:/adb-hub; adb connect localhost:4444
Note: You can use any available port that you have access to.
In the Android Wear companion app, you should see the status change to:
Host: connected
Target: connected
3)Debug Your App
Your wearable should show up as localhost:4444 when running adb devices. To run any adb command, use this format:
      adb -s localhost:4444 <command>

If there are no other devices connected over TCP/IP (namely emulators), you can shorten the command to:
      adb -e <command>

For example:
      adb -e logcat

      adb -e shell

      adb -e bugreport


text:
Q: Transparention of UIController in Swift - what segue chose? I am trying to chose right segue to have good "DropDown" in swift UIKit.
Only progress I have made is this:

or this:

My point is that i want the combination of these two. I don't want popover but also i wanna see the top part of the last controller. Is that even possible?

A: Unfortunately, Apple doesn't hand you one of these "half covering" presentations on a silver platter; you have to build it yourself. Use a presented view controller whose modal presentation style is custom and provide a transitioning delegate. Now you can make a custom transition animation with a custom UIPresentationController that puts you in charge of where the presented view controller's view will go. Adding the "shadow view" behind the presented view is up to you as well, so if you don't want it, don't add it.


text:
Q: Import components from .war file in Angular 2 I'm new to Angular 2. I want to reuse Angular component from war file in my Angular project. How can I import that component from war file to my Angular project? Or Is there a way to do this?
Thanks in advance!

A: .war files are just zip files.

*

*Unzip the war file

*Find the component file

*import it into the project / place it into the project folder


text:
Q: Add a class to a specific checkbox when is checked I have an foreach echo, which displays a list of items on my website and I want to make a system to add a green background (when a checkbox is checked) and remove that checkbox when its no more checked.
echo '<form action="selector.php" id="form1" method="post" target="_self">';

foreach ($Query as $row) {
  echo '

        Accept
        <input type="checkbox"  name="accepted[]" value="'.$row['topic_identification'].'" id="accepted"></input>

        Decline
        <input type="checkbox" name="declined[]" value="'.$row['topic_identification'].'" id="declined"></input>

  ';
}

echo '
  <input type="submit" name="submit" value="submit">

  </form>
';

For each checkbox, I want to add the class
.greenbox {
  background-color: green;
}

when it's checked, and when I uncheck it, I want it to remove the class.
Thank you!
Here is the CSS For the class ContainerPen and CheckmarkPen
    .containerPen {
  display: block;
  position: relative;
  padding-left: 35px;
  margin-bottom: 12px;
  cursor: pointer;
  font-size: 22px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.containerPen input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

.checkmarkPen {
  position: absolute;
  top: 0;
  left: 0;
  height: 25px;
  width: 25px;
  background-color: #eee;
}

.containerPen:hover input ~ .checkmarkPen {
  background-color: #00ff00;
}

.containerPen input:checked ~ .checkmarkPen {
  background-color: #00ff00;

}

.checkmarkPen:after {
  content: "";
  position: absolute;
  display: none;
}

.containerPen input:checked ~ .checkmarkPen:after {
  display: block;
}

.containerPen .checkmarkPen:after {
  left: 9px;
  top: 5px;
  width: 7px;
  height: 12px;
  border: solid white;
  border-width: 0 3px 3px 0;
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
}

A: As an alternative method;
Depending on which browsers you are supporting, you can simply do what you're trying to do through the CSS :checked pseudo-class selector.
You can read up on it here and see compatibility here.
Usage example would be;
input:checked
{
    background-color: green;
}

Or something like;
label input:checked
{
    background-color: green;
}

If you only want to have it affect inputs inside labels. Note that this selector will also apply to radio buttons or options inside selects.

A: $onload = <<<EOT

EOT;

// then add it where you want.

echo $onload;

Important
This kind of echo is called Heredoc and has 2 requirements (or it will error out). There can be NO spaces after the initial <<<EOT (just a line break), and there can be no spaces before the closing EOT;. In fact, the last line can only be EOT; Just make sure about the spaces. Otherwise, it's a great way to form a readable php output for things like html and javascript blocks.

A: you can either add an eventListener or an onclick event on both checkboxes that pass the id to the function.
Then you can use JavaScript's built-in classlist properties to add and remove class.

const addClass = (id) => {
    let checkbox = document.querySelector(`#${id}`);
    checkbox.classList.toggle('greenbox');
}
.greenbox{
  background-color: green;
}
<input type="checkbox" onclick="addClass(this.id)" id="accepted">
<input type="checkbox" onclick="addClass(this.id)" id="declined">


text:
Q: install Windows Phone 8 API documentation locally does anybody know if the Windows phone 8 MSDN Documentation can be installed locally?
I want this content:
http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff402535%28v=vs.105%29.aspx
visible in Help Viewer 2.0 since I often have to work in offline scenarios.
I have installed VS 2012 and the WP8 SDK.
When I choose "Windows Phone Development" in the Help Viewer 2.0 installed with VS2012 I get the 7.1 documentation.
Manfred

A: Just go inside Visual Studio.
Click "Help - Add and Remove Help Content"
Under "Recommended Documentation"
you will see "Windows Phone Development",
probably as the last item.
Click "Add" next to the item,
then click "Update" in the lower right.
The docs (approximately 209 megabytes worth) will pull down to your local machine.


text:
Q: How to view HTML file from application explicitly on default browser with version 2.3 in android I'm doing an android application which I want to view an HTML file from my application data(asset) on default browser.I used below code.Its working fine on some device browsers & not on some devices like Samsung S(with Gingerbread 2.3 version).It shows "Web Page not available... The requested file was not found". I want to view this file only on default browser not webview. How could I do that?
My Code:
    Uri myPageUri = Uri.fromFile(new  File(getFilesDirectory(this),"myPage.html"));
    Intent browserIntent = new Intent(Intent.ACTION_VIEW);
    browserIntent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
    browserIntent.addFlags(Intent.FLAG_FROM_BACKGROUND);
    browserIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    browserIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    if (Build.VERSION.SDK_INT >= 11) {
        browserIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    }
    browserIntent.putExtra(Browser.EXTRA_APPLICATION_ID, "com.android.browser");
    browserIntent.setData(myPageUri);

    startActivity(browserIntent);

....
  public static File getFilesDirectory(Context context) {
    File dir = context.getExternalFilesDir(null);
    if (dir == null) {
        dir = context.getFilesDir();
    }
    return dir;
}


text:
Q: scikit-image feature detector, descriptor and description matching I have a goal of comparing two images using scikit image. My plan is as follows.  Detect features on an image, get descriptors of detected features and then match descriptors between two images (compute a distance).
So far I found that scikit-learn has CENSURE feature detector and Daisy features descriptor. But it looks like Daisy creates description of whole image.
I wonder if there is method, which would take feature detected by CENSURE and create descriptors, which I can later use in match_descriptors method.


text:
Q: Webpack unable to resolve a third-party module I'm using compact/angular-bootstrap-lightbox in a project migrating from RequireJS to webpack, and am wondering if the error I'm getting is in my setup or the module itself.
In my webpack entry point, I have:
require("angular");
require("angular-bootstrap-lightbox");
...

So, to attempt to satisfy those dependencies:

*

*npm install angular

*npm install angular-bootstrap-lightbox

*webpack
Results in:
Module not found: Error: Cannot resolve module 'angular-bootstrap-lightbox' in ...

If I comment out the angular-bootstrap-lightbox require() call, Google's AngularJS imports just fine, which makes me think the issue is with the third party module. If that is the case, what are they missing that they should add, and is there a temporary workaround?

A: angular-bootstrap-lightbox doesn't have a main file specified in package.json. But there is index.js which requires the script. So you just need to specify it manually:
require("angular-bootstrap-lightbox/index.js");

You probably want to load css as well. So specify it similar way:
require("angular-bootstrap-lightbox/dist/angular-bootstrap-lightbox.css");


text:
Q: Supported TLS Cipher suites on Google Cloud Platform I'm checking which TLS cipher suites are supported on Google Cloud Platform. In case of AWS, there are some supported TLS cipher suites to use their service. But, Google Cloud Platform just describes which TLS version is supported. Can I get which cipher suite is mandatory to access Google Cloud Platform by non-Google end users?
For example, web server (or file server) is working on Google Cloud Platform, end user will send and receive encrypted data over TLS. During TLS, which cipher suite should be added?

A: This has recently become configurable using SSL Policies.


text:
Q: Android Fragment and reload application I have my FragmentActivity :
public class FragmentActivity extends FragmentActivity
{
    // ...
    protected void onCreate(Bundle savedInstanceState) {
         if (savedInstanceState != null) {
             myFragment = (MyFragment) getSupportFragmentManager().getFragment(
            savedInstanceState, MyFragment.class.getName());
         }
         else {
             myFragment = new Fragment(myObject);
         }
    }
}

And in my Fragment :
public class MyFragment extends Fragment
{
    public MyFragment(myObject) {
        super();
        this.myObject = myObject;
        setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        MyDAO myDAO = new MyDAO (myObject);
    }
}

Everything is working except when i close my application, do some stuff (my application enters in background) and then relaunch my application.
I get a NullPointerException on
MyDAO myDAO = new MyDAO (myObject);

where myObject is null.
The savedInstanceState is called ... i don't understand how this is working.
TY

A: The system is killing your process and the instance of myObject is being garbage collected.
Setting the instance to be retained is only helpful between orientation changes, but keep in mind that your app running in background may be killed when the system runs out of memory. Pass this variable as an argument instead. It's important to implement Parcelable or Serializable on MyDAO class.
PS.: You need to have an empty constructor for your fragment because the system recreates its instance when your activity is recreated:
public MyFragment() {

}

public MyFragment(myObject) {
    super();
    setRetainInstance(true);
    Bundle args = new Bundle();
    args.putParcelable("myObject", myObject);
    setArguments(args);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    myObject = getArguments().getParcelable("myObject");
    MyDAO myDAO = new MyDAO (myObject);
}


text:
Q: Including boost/asio.hpp throwing error When I use #include  in a header file, my program will no longer compile, giving the following error: 'boost::asio::basic_socket<Protocol,StreamSocketService>::cancel': By default, this function always fails with operation_not_supported when used on Windows XP, Windows Server 2003, or earlier. Consult documentation for details.
I am also using websocketpp in this project, if that is relevant - however the error only occurs if I include  specifically in my header.
I am using Windows 10, Visual Studio 14.
I'm at a loss as to why this error is occuring. I do not have to use the library at all, simply include it.

A: If you look at the header file, it's checking that _WIN32_WINNT is at least 0x0600. Refering to this msdn page, you can decide which version to specify, e.g. 0x0600 for Windows Vista and above. Specify this line before the include statement:
#define _WIN32_WINNT 0x0600


text:
Q: How to modify child item of a branch once I added an item into the bucket? I have defined number of branches using same hierarchy but different layout.
I'm importing the data from the external source and creating items in a bucket programmatically. I obtain the reference to proper branch based on some logic and I use following code to create and add a branch item into my bucket:
BranchItem branch = News.GetNewsBranchItem(item.Genre);
if (branch == null)
{
   Sitecore.Diagnostics.Log.Error(string.Format("Missing branch for {} genre!", item.Genre), this);
   Sitecore.Diagnostics.Log.Error(string.Format("Failed to import import item id: {0}", item.Id.ToString()), this);
   return;
}
Item newlyCreatedBranch = parent.Add(ItemUtil.ProposeValidItemName(item.Title), branch);

Then I want to access branch first child which is actually news item I want to fill with the data and complete the action:
Item newsItem = newlyCreatedBranch.Children[0];
newsItem.Editing.BeginEdit();
newsItem[SCG.BasePage2.FieldIds.MetaKeywords] = item.Keywords;
.
.
.
newsItem.Editing.EndEdit();

After process successfully finishes I do inspect the newly created items and found to my surprise that I'm missing content?!
I'm surprised because earlier I was accessing and filling my branch child node before
parent.Add(ItemUtil.ProposeValidItemName(item.Title), branch);

and noticed that the news item was properly filled ...
Any help appreciated

A: It was late after long day hence silly question I posted above.
Well, following code return news item instead of branch item:
Item newlyCreatedBranch = parent.Add(ItemUtil.ProposeValidItemName(item.Title), branch);

Once I considered returned item, the item I want to fill problem was solved.
Commented code was not necessary:
Item newsItem = parent.Add(ItemUtil.ProposeValidItemName(item.Title), branch);
//Item newsItem = newlyCreatedBranch.Children[0];


text:
Q: How to make an angular custom validator work only on submission? I developed a login component using the Angular-8 reactive form concept. I have asynchronous validations like empty fields, invalid emails. these validations should be asynchronous. But I have two custom validators like is-user-exist, is-password-match-user. These two validators should be only validated if user clicks submit. How to have a reactive form validator to check these two validators alone on submitting and other validations asynchronously.

A: You can control for a form (or single form elements) when the value or the validity is updated. This feature has been available in AngularJS 1.x but missed in Angular 2+ from some time. Starting from some version (Angular 5 I think) can be one of:

*

*change: change is the default mode. By using this update option the form / form control is updated after every single change.

*blur: the blur change mode is only updated the from values / validity status after a form control lost the focus.

*submit: updates are only done after form submit.

In reactive forms this can be done with the setting updateOn of either form or form control. Sample code:
this.nameForm = new FormGroup ({
  firstname: new FormControl('', {
    validators: Validators.required,
    updateOn: 'change'
  }),
  lastname: new FormControl('', {
    validators: Validators.required,
    updateOn: 'submit' // <--
  })
});


text:
Q: Populate specific array indices from other array in JavaScript I have 2 arrays, arr1 and arr2. They're both 2-dimensional. I want to copy certain array values from arr1 to arr2.
For instance, I want to copy the value from arr1[9][9] into arr2[0][0]. My guess was to write arr2[0][0] = arr1[9][9]; but that failed.
I looked at some similar questions on this site but they did not answer my question.

Here is the code for the particular situation. The code is written is Google Apps script.
  // eplList and attList are both arrays. They are filled below (I checked, the values exist)
  var eplList = epl.getRange(2, 2, eplLastRow, 2).getValues();
  var attList = attsheet.getRange(3, 1, attLastRow, 20).getValues();

  var eplListLength = eplList.filter(String).length;
  var attListLength = attList.filter(String).length;

  // Declaring the empty array I want to fill
  var masterArray = [];

  var ix, jx, day;

  // Here I begin to fill the array
  for (ix = 0; ix < eplListLength; ix++)
  {
    masterArray[ix][0] = eplList[ix][0]; // This is where I am getting the error message
    masterArray[ix][1] = eplList[ix][1];

      for (jx = 0; jx < attListLength; jx++)
      {
        if (eplList[ix][0] == attList[jx][day*4-4])
          masterArray[ix][6+day] = masterArray[ix][6+day].concat(" ", attList[jx][day*4-2], ": ",attList[jx][day*4-3]);
      };
 // and some morecode
  };

The error I'm getting is "TypeError: Cannot set property '0' of undefined"

A: To fix particular issue you've got try this code, but i not sure about code below):
masterArray[ix] = [eplList[ix][0], eplList[ix][1]]; // This is where I am getting the error message


text:
Q: Cannot read property 'next' of undefined I'm subscribing to an observable so that anytime my subscribeToTasks() call in my service fails, it will ultimately invoke the code in my subscriptionError() method from my component,  which in this example is just a simple alert. The problem is, anytime an error on this call occurs and this.newSubscriptionFailure.next() gets invoked, I get the following error in my browser console:

Cannot read property 'next' of undefined

How is newSubscriptionFailure undefined when you can clearly see it being defined above the method? That code should get hit long before the error in the api call happens. I've used this approach in the past and it has always worked, the only difference I can think of is that I'm calling .next() in the service (same file that newSubscriptionFailure is defined) whereas I normally call .next() in a separate component file. What am I doing wrong? Is there a way I can get this to work, or a better approach to take?
Code from my service:
import { Observable } from 'rxjs/Observable';
import { Subject }    from 'rxjs/Subject';

public subscribeToTasks(period: string, stripeToken: string): Observable<any> {
    let body = JSON.stringify({ period, stripeToken });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.authHttp.post(this.apiTasks, body, options).map(response => {
        return response.json();
    }).catch(this.newSubscriptionError);
}

newSubscriptionFailure = new Subject();
newSubscriptionFailure$ = this.newSubscriptionFailure.asObservable();

public newSubscriptionError() {
    this.newSubscriptionFailure.next();
}

code from my component:
ngOnInit(): void {
    this.subscriptionError();
}

subscriptionError(){
    this.subscriptionsService.newSubscriptionFailure$.subscribe(() => {
        alert('call failed');
    });
}

A: Change
}).catch(this.newSubscriptionError);

to
}).catch((e)=>this.newSubscriptionError());

or
}).catch(this.newSubscriptionError.bind(this));

your this is not refering to the Injectable otherwise

A: In case anyone else has the same issue I had.  I was using a subject called this.destroy$ that I call next on in the OnDestroy method.  Using it in the subscribed observable like: .takeUntil(this.destroyed$).  I had forgotten to initialise this destroy$ object.  After using destroy$: Subject<any> = new Subject<any>(); the error went away.


text:
Q: Calculate the sum of the infinite series $\sum_{n=0}^{\infty} \frac{n}{4^n}$ A previous problem had us solving $\sum_{n=0}^{\infty} \frac{1}{4^n}$ which I calculated to be $\frac{4}{3}$ using a bit of mathematical manipulation.
Wonderful. Thank you for all the prompt responses.  Could anyone suggest an alternate technique that does not involve differentiation?

A: Let $f(x)=\sum_{n\geq0}x^n$. This defines a function on $(-1,1)$, equal to $\frac1{1-x}$. Using properties of power series, we know that $$\frac x{(1-x)^2}=xf'(x)=\sum_{n\geq1}nx^n$$ for the same values of $x$. Evaluating this equality at $\tfrac14$ sums your series.

A: Well, you can do some series manipulations... First you can write
$$\sum_{n = 1}^{\infty} {n \over 4^n} = \sum_{n = 1}^{\infty}\,\sum_{m = 1}^n {1 \over 4^n}$$
Note that the above summation is over all $(m,n)$ with $m \leq n$. So if you switch the order of summation you obtain
$$\sum_{m = 1}^{\infty}\,\sum_{n = m}^{\infty} {1 \over 4^n}$$
The inner sum is a geometric series with initial term ${\displaystyle{1 \over 4^m}}$ and ratio ${\displaystyle{1 \over 4}}$, so it sums to ${\displaystyle {{1 \over 4^m} \over 1 - {1 \over 4}} = {4 \over 3}{1 \over 4^m}}$. So the overall sum is
$${4 \over 3}\sum_{m = 1}^{\infty} {1 \over 4^m}$$
The sum here is a geometric series that sums to ${\displaystyle{1 \over 3}}$, so your final answer is
$${4 \over 3}\times{1 \over 3} = {4 \over 9}$$

A: A simple probabilistic approach:
Let $X$ be a geometric random variable with probability of success $p$, so that
$$
{\rm P}(X=n)=(1-p)^{n-1} p, \;\; n=1,2,3,\ldots.
$$
Then the expectation of $X$ is
$$
{\rm E}(X) = \sum\limits_{n = 1}^\infty  {n{\rm P}(X = n)}  = \sum\limits_{n = 1}^\infty  {n(1 - p)^{n - 1} p}  = \frac{p}{{1 - p}}\sum\limits_{n = 1}^\infty  {n(1 - p)^n } .
$$
Thus
$$
\sum\limits_{n = 1}^\infty  {n(1 - p)^n } = \frac{{1 - p}}{p} {\rm E}(X).
$$
On the other hand, from
$$
{\rm E}(X) = p \cdot 1 + (1-p)(1+{\rm E}(X)),
$$
we get
$$
{\rm E}(X)=\frac{1}{p}.
$$
Finally,
$$
\sum\limits_{n = 1}^\infty  {n(1 - p)^n } = \frac{{1 - p}}{p} {\rm E}(X) = \frac{{1 - p}}{p^2}.
$$
Letting $p=3/4$ gives
$$
\sum\limits_{n = 1}^\infty  {\frac{n}{{4^n }}}  = \frac{{1/4}}{{9/16}} = \frac{4}{9}.
$$

A: Your sum is equal to
$$\frac{1}{4} +\frac{2}{4^2}+\frac{3}{4^3}+\frac{4}{4^4}+ \cdots +\frac{n}{4^n}+\cdots.$$
Call this sum $S$.  Now subtract from $S$ the sum
$$\frac{1}{4}+\frac{1}{4^2}+\frac{1}{4^3}+\cdots.$$
If we do it in the obvious way, term by term, we obtain
$$\frac{1}{4^2}+\frac{2}{4^3}+\frac{3}{4^4}+ \cdots.$$
Note that this last sum is $(1/4)S$.
Putting things together, and using your computation for $1+1/4+1/4^2+\cdots$ (not quite, we start at $1/4$) we get
$$S-\frac{1}{3}=\frac{S}{4}.$$
Solve for $S$. We find that $S=4/9$.
Comment: The calculation is a little sloppy, it assumes that infinite sums can be manipulated much like finite sums.  There are theorems about power series that one could use to justify the manipulations.
But (in this case) we do not need such theorems.
Let $S_n$ be the sum of the terms up to the term $n/4^n$.  More or less the same sort of calculation as the one I did can be used to find an explicit formula for $S_n$.  Then we can calculate $\lim_{n\to\infty}S_n$, and get a fully rigorous derivation.
We could use the results of the calculation of $\sum n/4^n$ to tackle $\sum n^2/4^n$, and so on.  But the derivatives approach is certainly slicker!

A: As you have computed $\sum_{n>=0} x^n$ to be $1/(1-x)$, differentiate the series term-wise and multiply by x, which you can do for $x=1/4$ as the series converges. This gives $\sum_{n>=0} n x^{n} = x/(1-x)^{2}$. Substitute $x=1/4$ and observe that $\sum_{n>=0} n/4^n = 4/9$


text:
Q: Why is Magento 2.3 supporting PHP 7.1 from 7.1.3 and excludes previous 7.1 versions? Magento 2.3 system requirements says it supports PHP 7.1.3+, but this excludes 7.1.0, 7.1.1 and 7.1.2 versions:
https://devdocs.magento.com/guides/v2.3/install-gde/system-requirements-tech.html
Is it a mistake or is there any reason why the 3 previous minor versions are excluded?
Thanks.

A: Php7.1 has strict typing in it. Php 7.0 does not support that yet.


text:
Q: calling sub makefiles in an easy way fails I`m using a makefile and call some makefiles in subdirectories.
Can anyony explain me, why this works

 $(MAKE) -C stub
 $(MAKE) -C source

but this not

SUBDIRS = stub source

$(SUBDIRS):
 $(MAKE) -C $@

First time I`m working with makefiles.

A: When you do not explicitly specify the target(s) to make, it will use the first target whose name doesn't start with a dot.  Here, that target is stub.
Apparently, you expect all of the targets of the first rule to be used, but there can only be one default target.
The documentation isn't 100% clear on this.
You will get the desired behavior by prepending the rule:
all: $(SUBDIRS)


text:
Q: How to force XmlSerializer to include an empty tag for empty list For whatever reason, empty lists are not included by the XmlSerializer during serialization. I've not found much documentation on whether this behavior is correct or whether it can be overridden.  I'm including the code for the type I'm trying to serialize and the serialization code in the hopes someone can shed some light on this.
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://tempuri.org/FacilitySettings.xsd")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://tempuri.org/FacilitySettings.xsd", IsNullable=true)]
public class WeightSettings
{

          public List<string> WeightOZIdentifiers
          {
                get
                {
                    return this.weightOZIdentifiersField;
                }
                set
                {
                    this.weightOZIdentifiersField = value;
                }
           }
}

public static string ToXmlString<T>(this T obj)
{
     var builder = new StringBuilder();
     using (var stringWriter = new StringWriter(builder))
     {
         var xml = new XmlTextWriter(stringWriter);
         var serializer = new XmlSerializer(obj.GetType());
         serializer.Serialize(xml, obj);
         return builder.ToString();
     }
}

edited to reflect

A: The XmlSerializer cannot serialize an empty array because he doesn't know the size of this array.
try initialize the array first and then serialize it.
WeightOZIdentifiers = new string[10];