text:
Q: Would Gendry have inherited Storm's End? This is a question about the show. In the books, some characters are alive that are dead in the show, so the answer would be different.
In S08E04, Queen Daenerys makes a show of granting Storm's End to Gendry, the bastard of King Robert Baratheon. Before she does, she asks if anyone knows who the current Lord of Storm's End is. Nobody knows, and she gives it to Gendry.
Did Queen Daenerys give Gendry something he wouldn't have had otherwise? Or did she just make a big show of pointing out that he was the rightful heir?
Obviously a real Baratheon would inherit before Gendry. Was there an obscure Baratheon that nobody knew about? One that Queen Daenerys supplanted when she made Gendry the Lord of Storm's End?
Do bastards ever inherit property? When no true-born heirs are alive? If so, then as the oldest (possibly the last) bastard child of King Robert, wouldn't Gendry be the rightful heir?

A: Of all the known members of House Baratheon in the show they are all dead. So that leaves us with whether or not Bastards have rights, well that isn't a clear cut case as GRRM has said before.

What if there are no childen, only grandchildren and great grandchildren. Is precedence or proximity the more important principle? Do bastards have any rights? What about bastards who have been legitimized, do they go in at the end after the trueborn kids, or according to birth order? What about widows? And what about the will of the deceased? Can a lord disinherit one son, and name a younger son as heir? Or even a bastard?
There are no clear cut answers, either in Westeros or in real medieval history. Things were often decided on a case by case basis. A case might set a precedent for later cases... but as often as not, the precedents conflicted as much as the claims.
Westeros, So Spake Martin, The Hornwood inheritance and the Whents

However, Gendry is also an unacknowledged bastard of Robert's so wouldn't really have been in the line of succession and thinks so himself. And in the show bastards appear to have less rights of succession compared to the books, see Ramsay Snow for example.

Daenerys: Gendry. That's right, isn't it?
Gendry: Yes, Your Grace.
Daenerys: You're Robert Baratheon's son. You are aware he took my family's throne and tried to have me murdered?
Gendry: I didn't even know he was my father until after he was dead.
Daenerys: Yes, he's dead. His brothers are too. So who's Lord of Storm's End now?
Gendry: I don't know, Your Grace.
Daenerys: Does anyone? I think you should be Lord of Storm's End.
Gendry: I can't be. I'm a bastard.
Daenerys: No, you are Lord Gendry Baratheon of Storm's End, the lawful son of Robert Baratheon. Because that is what I have made you.
Game of Thrones, Season 8 Episode 4, "The Last of the Starks"

A: No
Bastards have no right to inherit property. However if a bastard gets legitimised as the son of the lord, they can infact inherit the property. An example of this is Ramsay Bolton, formerly known as Ramsay Snow, who was legitimised by King Tommen Baratheon on behest of Roose Bolton and became Ramsay Bolton, the rightful heir of his father.
Robert Baratheon however never acknowledged Gendry and did not legitimise him, therefore Gendry had no right to claim Storm's End.


text:
Q: Why do clang and g++ print 0 for a1.v and a2.v in this example in C++1z? See this example in [class.base.init]/11
struct A {
  A() = default;          // OK
  A(int v) : v(v) { }     // OK
  const int& v = 42;      // OK
};
A a1;                     // error: ill-formed binding of temporary to reference
A a2(1);                  // OK, unfortunately

Both clang and g++ compile the code (clang with a warning), but I'd like to understand why do they print 0 for the members a1.v and a2.v? See demo.

A: It doesn't matter that they print 0.
For a1, the initialization is ill-formed to begin with. For a2, you're binding a reference to a temporary so you end up with a dangling reference. There's no significance to the 0 - it's whatever garbage memory the reference happens to point to at that point. Once you're violating preconditions, the program is undefined behavior.
Undefined behavior is undefined. There's no reason to expect a particular behavior for the print. For instance, gcc 7 prints 32764 while clang 4 prints 32765. Why? Why not.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP unable to access Xpath node of a SimpleXMLElement Object $x = new DomDocument();
$x->loadXML($responseXml);
$xml = simplexml_import_dom($x);

Outputting the array using print_r($xml) gives the following:
SimpleXMLElement Object
(
    [Timestamp] => 2014-11-09T18:28:47.843Z
    [Ack] => Success
    [Version] => 897
    [Build] => E897_UNI_API5_17253832_R1
    [Store] => SimpleXMLElement Object
        (
            [Name] => test
            [SubscriptionLevel] => Basic
            [Description] => Welcome Message.
        )

)

Using $xml->Store->Description outputs "Welcome Message."
When I use xpath to return the Description node using the following code, I get an empty array:
$xpath = new DOMXPath($x);
$result = $xpath->query("/Store/Description");

Why does this fail?

A: Its easier with simple xml.
$xml = new SimpleXMLElement($string);
$result = $xml->xpath('/Store/Description');

http://php.net/manual/en/simplexmlelement.xpath.php

A: Simple really, I just needed to register the namespace:
$xml->registerXPathNamespace('urn', 'ebay:apis:eBLBaseComponents');


text:
Q: I am getting ERROR TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)) error I am using angular 8 at front end and java spring boot at back end while running the application I am getting this error. I am new to angular and I guess the error is because of response body from back end but I couldn't solve it.
I have tried the other answers but nothing seems to work.
auth.service.ts
// Method from server should return QueryResultsModel(items: any[], totalsCount: number)
    // items => filtered/sorted result
    findUsers(queryParams: QueryParamsModel): Observable<QueryResultsModel> {
        const httpHeaders = new HttpHeaders();
        httpHeaders.set('Content-Type', 'application/json');
        return this.http.post<QueryResultsModel>(API_USERS_URL + '/use' + '/findUsers', queryParams, { headers: httpHeaders});
    }

Web service java spring boot
// Get All User
@PostMapping(value = "/user/use/findUsers")
public ResponseEntity<List<User>> getAllUserFind() {
    try {
        return new ResponseEntity<>((List<User>)userService.getAllUser(), HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

A: You need to find out the exact cause of error by gracefully catching the error in your observable resolution. Use
return this.http.post<QueryResultsModel>(API_USERS_URL + '/use' + '/findUsers', queryParams, { headers: httpHeaders})
.pipe(catchError(error)=>{
    console.log(error);
    return of(null);
});

This will print out the exact error on your console. Remember to import Rx Operators.
import { of } from 'rxjs';
import { catchError } from 'rxjs/operators';

A: Metronic theme ?
It's an amazing Template.
QueryResultsModel is a Model
// fields
items: any[]; <---- This is where you should iterate
importedCount?: number;
activeCount?: number;
totalCount: number;
errorMessage: string;

Good Luck !


text:
Q: WSO2 Send a message to another endpoint after finish one transaction I have a situation here where as I need to create a API flow such as below.

I manage to create an API using the GET method and Call Mediator for the login request. However, when i change the API method to POST (because I need to send something in the body) and using Call Mediator for the Login request, it prompt me an error.
I am not sure whether POST method API is not allowed to be using together with the Call Mediator or not.
Is the flow I want to create above, is achievable just using API or do i need to create a Business Process Management Project?
If I wanna use POST method together with Send Mediator, how would it be ? I was aware that I can not put any mediator after the Send Mediator
Any advice would be grateful. Thank you again.

A: What is the error that you got? and Try removing REST_URL_POSTFIX property before calling to your endpoint.
<property name="REST_URL_POSTFIX" action="remove" scope="axis2"/>


text:
Q: LQ decomposition and inequalities Suppose I have an element-wise inequality: $Ax \ge b$, where $A$ is a rectangular matrix with full row rank, and $x$ and $b$ are appropriately sized column vectors.  I need to check if the inequality holds to branch some code I'm writing.
If I (thin) LQ decompose $A$, I have:
$$L Q x \ge b$$
where $L$ is a lower triangular square matrix of full rank and $Q$ is an orthogonal matrix.
As it turns out, I need to calculate $L^{-1} b$ anyway, so my first thought was to calculate it and just check:
$$Qx \ge L^{-1}b$$
However, this doesn't necessarily work, as depending on exactly how the matrix $A$ was decomposed, it might change the $\ge$ in to a $\le$.  For example, if $A = 1$, and we decompose it as $L = -1$, $Q = -1$, multiplying both sides by $L^{-1}$ switches the direction of the inequality.
Under what circumstances will multiplying both sides of an inquality system by a matrix not change the direction of the inequality?  My intuitive guess is that as long as the eigenvalues of the matrix are positive (that is, the matrix is positive definite), the inequality direction won't change.  But I'm not sure how to prove/disprove that.

A: In order that
$$
Mx \ge b
$$
implies
$$
x \ge M^{-1}b
$$
$M^{-1}$ has to be non-negative element-wise, i.e. all elements in $M^{-1}$ have to be non-negative. The prove that this suffices is easy.
Positive eigenvalues cannot help here. To see this consider
$$
A=\begin{pmatrix}1 & 10 \\ 0 & 1\end{pmatrix},\
A^{-1}=\begin{pmatrix}1 & -10 \\ 0 & 1\end{pmatrix},\
x = \begin{pmatrix} 1 \\ 1\end{pmatrix}, \
b = \begin{pmatrix} 1 \\ -1\end{pmatrix}.
$$
Then
$$
Ax = \begin{pmatrix} 11 \\ 1\end{pmatrix} \ge b
$$
but
$$
x\not\ge A^{-1}b = \begin{pmatrix} 11 \\ -1\end{pmatrix}.
$$


text:
Q: remove data from one list with another list data function not working properly public static void getIndividualsList() {
        List<Employee> individualList = new ArrayList<>();
        Employee individualDtls = new Employee();
        individualDtls.setDependentId(0);
        individualDtls.setDateOfBirth("06/06/1998");
        individualDtls.setEeId(1L);
        individualDtls.setFullName("MICHAEL K HERNANDEZ");
        individualDtls.setCovered(false);
        individualDtls.setDependentType("Self");

        individualList.add(individualDtls);

        List<Employee> individualList1 = new ArrayList<>();
        Employee individualDtls1 = new Employee();

        individualDtls1.setDependentId(0);
        individualDtls1.setDateOfBirth("06/06/1998");
        individualDtls1.setEeId(1L);
        individualDtls1.setFullName("MICHAEL K HERNANDEZ");
        individualDtls1.setCovered(false);
        individualDtls1.setDependentType("Self");

        individualList1.add(individualDtls1);

        individualList.removeAll(individualList1);

        for (Employee employee : individualList) {
            System.out.println(employee.getDateOfBirth());
        }
    }

Why removeAll is not working properly?
Applied removeAll but still getting data. Can someone please let me know why its not working?

A: Based on your comment: "In the employee class there is restriction. So its not allowing to modify like adding any other methods or comparator. Thats the problem. Thats why trying to find another solution for that."
If you have any unique field, maybe you can use that field to iterate over your first list to remove the required items.
import java.util.*;

public class MyClass {

    public static void main(String args[]) {
      List<Employee> listA = new ArrayList<>();
      listA.add(new Employee("gokul", "1", "gokul@domain.com"));
      listA.add(new Employee("user", "2", "user@domain.com"));

      List<Employee> listB = new ArrayList<>();
      listB.add(new Employee("user", "2", "user@domain.com"));

      for (Employee eB : listB) {
          for (Employee eA : listA) {
              if (eA.id.equals(eB.id)) {
                  listA.remove(eA);
                  break;
              }
          }
      }

      for (Employee e : listA) {
          System.out.println(e.name);
      }
    }

    static class Employee {
        String name;
        String id;
        String email;

        public Employee(String name, String id, String email) {
            this.name = name;
            this.id = id;
            this.email = email;
        }
    }
}

A: Both remove and removeAll relies on equal (and hashCode!) implementation. Most probably you didn't implement one of this methods.
Without custom implementation of equal an object equals only himself. Two variables must reference exactly the same object to be equal. Custom implementation looks like this:
class Employee {
    ....
    public boolean equals(Object obj) {
        if (obj instanceof Employee) {
            Employee oo = (Employee)obj;
            return Objects.equal(fullName, oo.fullName) && Objects.equal(dateOfBirth, oo.dateOfBirth)
        } else {
            return false;
        }
    }

    public int hashCode() {
        return Objects.hashCode(fullName, dateOfBirth);
    }
}

I took fullName and dateOfBirth to ensure equality. You must manually add all the fields you think important for two objects to be equal (spoiler - it is not trivial).

If you cannot modify the object Employee there are to ways:

*

*do it manually as described by "Gokul Nath KP"

*take some other collection structure instead of ArrayList. For example TreeSet uses an optionally provided custom Comparator instance instead of equal-Method.


text:
Q: How get EventLog info from LogLink using Get-WinEvent I'm trying to get EventLog entries for a certain process, 'Application Error'. I can list it with the following command, but I'm having trouble finding out how to list the log entries and not just the LogLink name.
powershell Get-WinEvent -ListProvider *Error

Gives:
Name:     Application Error
LogLinks: {Application}
Opcodes:  {}
Tasks:    {}

I found this example, but I'm unsure how they got the directory information used in the xml definition that got the log entries.  Get-WinEvent and xml filters
I tried
powershell Get-WinEvent -ListProvider *Error -logName Applicaiton
but get the error
Get-WinEvent : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:1
+ Get-WinEvent -ListProvider *Error -logName Applicaiton
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-WinEvent], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.GetWinEventCommand

I saw Get-eventlog, but again, they know where to find their event logs in the second case. Also, I'm not sure where PowerShell command goes since I'm doing this at the windows command line, and still get an error with what they are doing (and I'm unsure why they use SilentlyContinue so I left it out):
powershell (Get-WinEvent -ListProvider *Error -logName Applicaiton -ErrorAction).LogName

Get-WinEvent : Missing an argument for parameter 'ErrorAction'. Specify a parameter of type
'System.Management.Automation.ActionPreference' and try again.
At line:1 char:57
+ ... nEvent -ListProvider *Error -logName Applicaiton -ErrorAction).LogNam ...
+                                                      ~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-WinEvent], ParameterBindingException
    + FullyQualifiedErrorId : MissingArgument,Microsoft.PowerShell.Commands.GetWinEventCommand

Update
I tried
powershell (Get-WinEvent -ListProvider *Error -logName Applicaiton -ErrorAction Continue).LogName
and get this error:
Get-WinEvent : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:2
+ (Get-WinEvent -ListProvider *Error -logName Applicaiton -ErrorAction  ...
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-WinEvent], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.GetWinEventCommand

Update2:
Found mis-spelling in Application thanks to Theo, but still have error:
powershell (Get-WinEvent -ListProvider *Error -logName Application -ErrorAction Continue).LogName

Error:
Get-WinEvent : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:2
+ (Get-WinEvent -ListProvider *Error -logName Application -ErrorAction  ...
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-WinEvent], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.GetWinEventCommand

Update3:
I tried powershell Get-WinEvent -logName Application but it goes on forever.  How do I just get event log info for 'Application Error'?
Update4:
I tried in powershell ISE:
Get-WinEvent -logname Application | Where-Object {$_.ProviderName -Match 'Application Error' }

And it seemed to work for a while, then had this error from powershell ISE:
Get-WinEvent : The maximum number of replacements has been reached
At line:3 char:1
+ Get-WinEvent -logname Application | Where-Object {$_.ProviderName -Ma ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-WinEvent], EventLogException
    + FullyQualifiedErrorId : The maximum number of replacements has been reached,Microsoft.PowerShell.Commands.GetWinEventCommand

From the windows command line (which is the ultimate goal) I didn't have any output, but did have this error:
powershell (Get-WinEvent  -logName Application | Where-Object {$_.ProviderName -Match 'Application Error'})

'Where-Object' is not recognized as an internal or external command,
operable program or batch file.

A: I got this one working:
powershell (Get-WinEvent -FilterHashtable @{LogName='Application'; ProviderName='Application Error'} )


text:
Q: Error with pip install face_recognition module in python terminal I am trying to install the face_recognition module in my terminal for a project but I am having trouble with some of the error messages. I already ran pip install on cmake and dlib but whenever I try running pip install face_recognition or pipenv install face_recognition, I get the following error message:
note: This error originates from a subprocess, and is likely not a problem
with pip.
error: legacy-install-failure
× Encountered error while trying to install package.
╰─> dlib
I am not quite sure what this means and I have been looking around to the best of my ability to solve the problem. I have already installed dlib through pip.


text:
Q: cannot fetch token error when using cloudsql-proxy with GKE I am using GKE with istio add-on enabled. Myapp somehow gives 503 errors using when using websocket. I am starting to think that maybe the websocket is working but the database connection is not and that causes 503's, as the cloudsql-proxy logs give errors:
$ kubectl logs myapp-54d6696fb4-bmp5m cloudsql-proxy
2019/01/04 21:56:47 using credential file for authentication; email=proxy-user@myproject.iam.gserviceaccount.com
2019/01/04 21:56:47 Listening on 127.0.0.1:5432 for myproject:europe-west4:mydatabase
2019/01/04 21:56:47 Ready for new connections
2019/01/04 21:56:51 New connection for "myproject:europe-west4:mydatabase"
2019/01/04 21:56:51 couldn't connect to "myproject:europe-west4:mydatabase": Post https://www.googleapis.com/sql/v1beta4/projects/myproject/instances/mydatabase/createEphemeral?alt=json: oauth2: cannot fetch token: Post https://oauth2.googleapis.com/token: read tcp 10.44.11.21:60728->108.177.126.95:443: read: connection reset by peer
2019/01/04 22:14:56 New connection for "myproject:europe-west4:mydatabase"
2019/01/04 22:14:56 couldn't connect to "myproject:europe-west4:mydatabase": Post https://www.googleapis.com/sql/v1beta4/projects/myproject/instances/mydatabase/createEphemeral?alt=json: oauth2: cannot fetch token: Post https://oauth2.googleapis.com/token: read tcp 10.44.11.21:36734->108.177.127.95:443: read: connection reset by peer

Looks like the required authentication details should be in the credentials of the proxy service account I created and thus is provided for:
{
  "type": "service_account",
  "project_id": "myproject",
  "private_key_id": "myprivekeyid",
  "private_key": "-----BEGIN PRIVATE KEY-----\MYPRIVATEKEY-----END PRIVATE KEY-----\n",
  "client_email": "proxy-user@myproject.iam.gserviceaccount.com",
  "client_id": "myclientid",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/proxy-user%40myproject.iam.gserviceaccount.com"
}

My question:
How do I get rid of the errors/ get a proper google sql config from GKE?
At cluster creation I selected the mTLS 'permissive' option.
My config:
myapp_and_router.yaml:
apiVersion: v1
kind: Service
metadata:
  name: myapp
  labels:
    app: myapp
spec:
  ports:
  - port: 8089
    # 'name: http' apparently does not work
    name: db
  selector:
    app: myapp
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
  labels:
    app: myapp
spec:
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
        - name: myapp
          image: gcr.io/myproject/firstapp:v1
          imagePullPolicy: Always
          ports:
            - containerPort: 8089
          env:
            - name: POSTGRES_DB_HOST
              value: 127.0.0.1:5432
            - name: POSTGRES_DB_USER
              valueFrom:
                secretKeyRef:
                  name: mysecret
                  key: username
            - name: POSTGRES_DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: mysecret
                  key: password
          ## Custom healthcheck for Ingress
          readinessProbe:
            httpGet:
              path: /healthz
              scheme: HTTP
              port: 8089
            initialDelaySeconds: 5
            timeoutSeconds: 5
          livenessProbe:
            httpGet:
              path: /healthz
              scheme: HTTP
              port: 8089
            initialDelaySeconds: 5
            timeoutSeconds: 20
        - name: cloudsql-proxy
          image: gcr.io/cloudsql-docker/gce-proxy:1.11
          command: ["/cloud_sql_proxy",
                    "-instances=myproject:europe-west4:mydatabase=tcp:5432",
                    "-credential_file=/secrets/cloudsql/credentials.json"]
          securityContext:
            runAsUser: 2
            allowPrivilegeEscalation: false
          volumeMounts:
            - name: cloudsql-instance-credentials
              mountPath: /secrets/cloudsql
              readOnly: true
      volumes:
        - name: cloudsql-instance-credentials
          secret:
            secretName: cloudsql-instance-credentials
---
###########################################################################
# Ingress resource (gateway)
##########################################################################
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: myapp-gateway
spec:
  selector:
    istio: ingressgateway
  servers:
  - port:
      number: 80
      # 'name: http' apparently does not work
      name: db
      protocol: HTTP
    hosts:
    - "*"
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: myapp
spec:
  hosts:
  - "*"
  gateways:
  - myapp-gateway
  http:
  - match:
    - uri:
        prefix: /
    route:
    - destination:
        host: myapp
      weight: 100
    websocketUpgrade: true
---

EDIT 1: I had not enabled permissions (scopes) for the various google services when creating the cluster, see here. After creating a new cluster with the permissions I now get a new errormessage:
kubectl logs mypod cloudsql-proxy
2019/01/11 20:39:58 using credential file for authentication; email=proxy-user@myproject.iam.gserviceaccount.com
2019/01/11 20:39:58 Listening on 127.0.0.1:5432 for myproject:europe-west4:mydatabase
2019/01/11 20:39:58 Ready for new connections
2019/01/11 20:40:12 New connection for "myproject:europe-west4:mydatabase"
2019/01/11 20:40:12 couldn't connect to "myproject:europe-west4:mydatabase": Post https://www.googleapis.com/sql/v1beta4/projects/myproject/instances/mydatabase/createEphemeral?alt=json: oauth2: cannot fetch token: 400 Bad Request
Response: {
  "error": "invalid_grant",
  "error_description": "Invalid JWT Signature."
}

EDIT 2: Looks like new error was caused by the Service Accounts keys no longer being valid. After making new ones I can connect to the database!

A: I saw similar errors but was able to get cloudsql-proxy working in my istio cluster on GKE by creating the following service entries (with some help from https://github.com/istio/istio/issues/6593#issuecomment-420591213):
apiVersion: networking.istio.io/v1alpha3
kind: ServiceEntry
metadata:
  name: google-apis
spec:
  hosts:
  - "*.googleapis.com"
  ports:
  - name: https
    number: 443
    protocol: HTTPS
---
apiVersion: networking.istio.io/v1alpha3
kind: ServiceEntry
metadata:
  name: cloudsql-instances
spec:
  hosts:
  # Use `gcloud sql instances list` to get the addresses of instances
  - 35.226.125.82
  ports:
  - name: tcp
    number: 3307
    protocol: TCP

Also, I still saw those connection errors during initialization until I added a delay in my app startup (sleep 10 before running server) to give the istio-proxy and cloudsql-proxy containers time to get set up first.
EDIT 1: Here are logs with the errors, then the successful "New connection/Client closed" lines once things are working:
2019/01/10 21:54:38 New connection for "my-project:us-central1:my-db"
2019/01/10 21:54:38 Throttling refreshCfg(my-project:us-central1:my-db): it was only called 44.445553175s ago
2019/01/10 21:54:38 couldn't connect to "my-project:us-central1:my-db": Post https://www.googleapis.com/sql/v1beta4/projects/my-project/instances/my-db/createEphemeral?alt=json: oauth2: cannot fetch token: Post https://accounts.google.com/o/oauth2/token: dial tcp 108.177.112.84:443: getsockopt: connection refused
2019/01/10 21:54:38 New connection for "my-project:us-central1:my-db"
2019/01/10 21:54:38 Throttling refreshCfg(my-project:us-central1:my-db): it was only called 44.574562959s ago
2019/01/10 21:54:38 couldn't connect to "my-project:us-central1:my-db": Post https://www.googleapis.com/sql/v1beta4/projects/my-project/instances/my-db/createEphemeral?alt=json: oauth2: cannot fetch token: Post https://accounts.google.com/o/oauth2/token: dial tcp 108.177.112.84:443: getsockopt: connection refused
2019/01/10 21:55:15 New connection for "my-project:us-central1:my-db"
2019/01/10 21:55:16 Client closed local connection on 127.0.0.1:5432
2019/01/10 21:55:17 New connection for "my-project:us-central1:my-db"
2019/01/10 21:55:17 New connection for "my-project:us-central1:my-db"
2019/01/10 21:55:27 Client closed local connection on 127.0.0.1:5432
2019/01/10 21:55:28 New connection for "my-project:us-central1:my-db"
2019/01/10 21:55:30 Client closed local connection on 127.0.0.1:5432
2019/01/10 21:55:37 Client closed local connection on 127.0.0.1:5432
2019/01/10 21:55:38 New connection for "my-project:us-central1:my-db"
2019/01/10 21:55:40 Client closed local connection on 127.0.0.1:5432

EDIT 2: Ensure that Cloud SQL api is within scope of your cluster.

A: Since MySQL and PostgreSQL are based on the TCP/IP protocol(or unix socket on a specific situation) and Postgres isn't using HTTP, the problem comes from the Service's port name,.
First, try to change the port name, you can change it to "db" as example.
Another workaround is to use  jdbc Socket Factory connecting to CloudSQL Mysql with slight difference :

*

*No "Adresses field" /CIDR block in cloud-sql-instance service entry

*Resolution: DNS for the service entry that allows the connection to the CloudSQL Instance


text:
Q: Windows 7 boot option missing after installing CentOS 7, how can I get it back? After installing Centos7, windows 7 is not showing at the boot time. Centos 7 is accessible.
My boot folder entries:
[root@localhost boot]# ls -ltr
total 89176
-rw-------. 1 root root  2840084 Jun 30 07:17 System.map-3.10.0-123.el7.x86_64
-rw-r--r--. 1 root root   122059 Jun 30 07:17 config-3.10.0-123.el7.x86_64
-rwxr-xr-x. 1 root root  4902656 Jun 30 07:17 vmlinuz-3.10.0-123.el7.x86_64
-rw-r--r--. 1 root root   228562 Jun 30 07:20 symvers-3.10.0-123.el7.x86_64.gz
drwxr-xr-x. 2 root root     4096 Nov 21 05:27 extlinux
drwxr-xr-x. 2 root root       26 Nov 21 05:28 grub
-rw-r--r--. 1 root root   867424 Nov 21 05:38 initrd-plymouth.img
-rw-r--r--. 1 root root 42219459 Nov 21 05:39 initramfs-0-rescue-4d161cb1c811459b927aed6f75f7deed.img
-rwxr-xr-x. 1 root root  4902656 Nov 21 05:39 vmlinuz-0-rescue-4d161cb1c811459b927aed6f75f7deed
-rw-r--r--. 1 root root 17637360 Nov 21 05:40 initramfs-3.10.0-123.el7.x86_64.img
-rw-r--r--. 1 root root 17584068 Nov 21 11:59 initramfs-3.10.0-123.el7.x86_64kdump.img
drwxr-xr-x. 6 root root      104 Nov 25 02:52 grub2

fdisk -l output
[root@localhost boot]# fdisk -l
WARNING: fdisk GPT support is currently new, and therefore in an experimental phase. Use at your own discretion.

Disk /dev/sda: 250.1 GB, 250059350016 bytes, 488397168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: gpt

#         Start          End    Size  Type            Name
 1         2048       206847    100M  EFI System      EFI system partition
 2       206848       468991    128M  Microsoft reser Microsoft reserved partition
 3       468992    348162047  165.8G  Microsoft basic Basic data partition
 4    348162048    348164095      1M  BIOS boot parti
 5    348164096    349188095    500M  Microsoft basic
 6    349188096    488396799   66.4G  Linux LVM

Disk /dev/mapper/centos-swap: 8262 MB, 8262778880 bytes, 16138240 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/mapper/centos-root: 42.3 GB, 42341498880 bytes, 82698240 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/mapper/centos-home: 20.7 GB, 20669530112 bytes, 40370176 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

bklid output
[root@localhost boot]# bklid
bash: bklid: command not found...
Similar command is: 'blkid'
[root@localhost boot]# blkid
/dev/sr0: UUID="2011-04-12-02-38-58-00" LABEL="GSP1RMCPRXFRER_EN_DVD" TYPE="udf"
/dev/sda1: UUID="20DD-5268" TYPE="vfat" PARTLABEL="EFI system partition" PARTUUID="ef67b4eb-4514-4824-a1ba-d8d045e96f26"
/dev/sda3: UUID="EAD6EA4AD6EA169B" TYPE="ntfs" PARTLABEL="Basic data partition" PARTUUID="fa8c0ee9-2913-45ec-b016-0c6eb2e4aab8"
/dev/sda5: UUID="368a42d5-e9f9-4c81-81e2-70afe2344b6b" TYPE="xfs" PARTUUID="7447a676-d39b-46fc-948b-f1c4a3b4bf9c"
/dev/sda6: UUID="VfFTVf-Rdy5-kLFT-Zyys-PIEf-PnOo-gSZfLZ" TYPE="LVM2_member" PARTUUID="b2677b42-22fb-42f8-a287-77ad0638b674"
/dev/mapper/centos-swap: UUID="155e4385-547c-4c0b-94bd-13882f078548" TYPE="swap"
/dev/dm-2: UUID="a4709eae-75fd-4423-8f11-64762df974df" TYPE="xfs"
/dev/dm-1: UUID="24a077fa-6b00-4da0-9d07-34048d84d853" TYPE="xfs"

grub2-mkconfig -o /boot/grub2/grub.cfg command output
[root@localhost boot]#  grub2-mkconfig -o /boot/grub2/grub.cfg
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-3.10.0-123.el7.x86_64
Found initrd image: /boot/initramfs-3.10.0-123.el7.x86_64.img
Warning: Please don't use old title `CentOS Linux, with Linux 3.10.0-123.el7.x86_64' for GRUB_DEFAULT, use `Advanced options for CentOS Linux>CentOS Linux, with Linux 3.10.0-123.el7.x86_64' (for versions before 2.00) or `gnulinux-advanced-24a077fa-6b00-4da0-9d07-34048d84d853>gnulinux-3.10.0-123.el7.x86_64-advanced-24a077fa-6b00-4da0-9d07-34048d84d853' (for 2.00 or later)
Found linux image: /boot/vmlinuz-0-rescue-4d161cb1c811459b927aed6f75f7deed
Found initrd image: /boot/initramfs-0-rescue-4d161cb1c811459b927aed6f75f7deed.img
done

Here is the content of  /boot/grub2/grub.cfg
#
# DO NOT EDIT THIS FILE
#
# It is automatically generated by grub2-mkconfig using templates
# from /etc/grub.d and settings from /etc/default/grub
#

### BEGIN /etc/grub.d/00_header ###
set pager=1

if [ -s $prefix/grubenv ]; then
  load_env
fi
if [ "${next_entry}" ] ; then
   set default="${next_entry}"
   set next_entry=
   save_env next_entry
   set boot_once=true
else
   set default="${saved_entry}"
fi

if [ x"${feature_menuentry_id}" = xy ]; then
  menuentry_id_option="--id"
else
  menuentry_id_option=""
fi

export menuentry_id_option

if [ "${prev_saved_entry}" ]; then
  set saved_entry="${prev_saved_entry}"
  save_env saved_entry
  set prev_saved_entry=
  save_env prev_saved_entry
  set boot_once=true
fi

function savedefault {
  if [ -z "${boot_once}" ]; then
    saved_entry="${chosen}"
    save_env saved_entry
  fi
}

function load_video {
  if [ x$feature_all_video_module = xy ]; then
    insmod all_video
  else
    insmod efi_gop
    insmod efi_uga
    insmod ieee1275_fb
    insmod vbe
    insmod vga
    insmod video_bochs
    insmod video_cirrus
  fi
}

terminal_output console
if [ x$feature_timeout_style = xy ] ; then
  set timeout_style=menu
  set timeout=5
# Fallback normal timeout code in case the timeout_style feature is
# unavailable.
else
  set timeout=5
fi
### END /etc/grub.d/00_header ###

### BEGIN /etc/grub.d/10_linux ###
menuentry 'CentOS Linux, with Linux 3.10.0-123.el7.x86_64' --class centos --class gnu-linux --class gnu --class os --unrestricted $menuentry_id_option 'gnulinux-3.10.0-123.el7.x86_64-advanced-24a077fa-6b00-4da0-9d07-34048d84d853' {
    load_video
    set gfxpayload=keep
    insmod gzio
    insmod part_gpt
    insmod xfs
    set root='hd0,gpt5'
    if [ x$feature_platform_search_hint = xy ]; then
      search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt5 --hint-efi=hd0,gpt5 --hint-baremetal=ahci0,gpt5 --hint='hd0,gpt5'  368a42d5-e9f9-4c81-81e2-70afe2344b6b
    else
      search --no-floppy --fs-uuid --set=root 368a42d5-e9f9-4c81-81e2-70afe2344b6b
    fi
    linux16 /vmlinuz-3.10.0-123.el7.x86_64 root=UUID=24a077fa-6b00-4da0-9d07-34048d84d853 ro rd.lvm.lv=centos/swap vconsole.font=latarcyrheb-sun16 rd.lvm.lv=centos/root crashkernel=auto  vconsole.keymap=us rhgb quiet
    initrd16 /initramfs-3.10.0-123.el7.x86_64.img
}
menuentry 'CentOS Linux, with Linux 0-rescue-4d161cb1c811459b927aed6f75f7deed' --class centos --class gnu-linux --class gnu --class os --unrestricted $menuentry_id_option 'gnulinux-0-rescue-4d161cb1c811459b927aed6f75f7deed-advanced-24a077fa-6b00-4da0-9d07-34048d84d853' {
    load_video
    insmod gzio
    insmod part_gpt
    insmod xfs
    set root='hd0,gpt5'
    if [ x$feature_platform_search_hint = xy ]; then
      search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt5 --hint-efi=hd0,gpt5 --hint-baremetal=ahci0,gpt5 --hint='hd0,gpt5'  368a42d5-e9f9-4c81-81e2-70afe2344b6b
    else
      search --no-floppy --fs-uuid --set=root 368a42d5-e9f9-4c81-81e2-70afe2344b6b
    fi
    linux16 /vmlinuz-0-rescue-4d161cb1c811459b927aed6f75f7deed root=UUID=24a077fa-6b00-4da0-9d07-34048d84d853 ro rd.lvm.lv=centos/swap vconsole.font=latarcyrheb-sun16 rd.lvm.lv=centos/root crashkernel=auto  vconsole.keymap=us rhgb quiet
    initrd16 /initramfs-0-rescue-4d161cb1c811459b927aed6f75f7deed.img
}
if [ "x$default" = 'CentOS Linux, with Linux 3.10.0-123.el7.x86_64' ]; then default='Advanced options for CentOS Linux>CentOS Linux, with Linux 3.10.0-123.el7.x86_64'; fi;
### END /etc/grub.d/10_linux ###

### BEGIN /etc/grub.d/20_linux_xen ###
### END /etc/grub.d/20_linux_xen ###

### BEGIN /etc/grub.d/20_ppc_terminfo ###
### END /etc/grub.d/20_ppc_terminfo ###

### BEGIN /etc/grub.d/30_os-prober ###
### END /etc/grub.d/30_os-prober ###

### BEGIN /etc/grub.d/40_custom ###
# This file provides an easy way to add custom menu entries.  Simply type the
# menu entries you want to add after this comment.  Be careful not to change
# the 'exec tail' line above.

### END /etc/grub.d/40_custom ###

### BEGIN /etc/grub.d/41_custom ###
if [ -f  ${config_directory}/custom.cfg ]; then
  source ${config_directory}/custom.cfg
elif [ -z "${config_directory}" -a -f  $prefix/custom.cfg ]; then
  source $prefix/custom.cfg;
fi
### END /etc/grub.d/41_custom ###

I have tried adding below entry to 40_custom and ran "grub2-mkconfig -o /boot/grub2/grub.cfg", could not find windows in the output. The entry shows in the boot menu but gives an error "Missing BOOTMGR" when clicked.
menuentry 'Windows 7 (loader) (on /dev/sda3)' --class windows --class os $menuentry_id_option 'osprober-chain-EAD6EA4AD6EA169B' {
    insmod part_gpt
    insmod ntfs
    set root='hd0,gpt3'
    if [ x$feature_platform_search_hint = xy ]; then
      search --no-floppy --fs-uuid --set=root –hint-bios=hd0,gpt3 --hint-efi=hd0,gpt3 --hint-baremetal=ahci1, gpt3   EAD6EA4AD6EA169B
    else
      search --no-floppy --fs-uuid --set=root  EAD6EA4AD6EA169B
    fi
    chainloader +1
}


text:
Q: How to prevent Normalization Formula to produce NaN values? While trying to normalize my data with the following formula:
normalized_df=(df-df.mean())/df.std()

Some of the values become NaN. I think the only reason it can become NaN is if the stanard deviation is equal to zero (Divided by 0). This is very unlikely as that would mean all the values must have the same value.
Why does this happen then? How to avoid it?
I found a similar question here that suggest it might be a bug!

A: Without any extra input std will give the standard deviation over the columns. So the first obvious thing to check is what the columns look like for which you get NaN.
It can have more than one reason. Either, as you say, because their std is 0. Or because any of the columns entries is NaN.
So to go bug-hunting, check what's going on in the particular column. Explicitly compute mean and std for yourself and see what's going on. And check if any of the entries in the column is already NaN. I can't imagine that the numpy bug hasn't been fixed for over 4 years.


text:
Q: bridge rectifier made with 1N5408 Again I Have a question regarding Bridge Rectifier's Made using 4 Diodes
if I use 4 pieces of 1N5408 with rating of  3 amp in Bridge mode what will be current rating or handling capacity of rectifier ,does its rating will increase or will be same as single 1N5408

A: The diode rating is for the part itself.  The manufacturer states that the part is rated for 3A for each part, so you shouldn't exceed 3A.  There is some judgement in this statement, meaning that you can exceed the rating without damaging the part for short periods, but not for long periods.
A bridge rectifier uses 4 of these, two of which are conducting at a time.  This means that if the bridge rectifier is seeing an RMS current of 3A, then each diode is experiencing an RMS current of 1.5A.  So to answer your question, yes, your rating could be considered increased over that of the individual components.
Having said that, a 2x safety margin is a good thing in power electronics.  If you need 3A continuous output, I would recommend a 5A or higher diode.


text:
Q: Given $a\in \mathbb Z$ and a prime number $p\neq 2 $, when is $x^{p^{2}} \equiv a (\text{mod} \, p^{j}) $ solvable. Given an $a\in \mathbb Z$ and a prime number $p \neq 2 $, I want to know when is $x^{p^{2}} \equiv a (\text{mod}\, p^{j}$ ) solvable for all $j \geq 1 $.
I came up with a proof that given an $a\in \mathbb Z$ and a prime  $p\neq 2 $, $ x^{p} \equiv a (\text{mod}\ p^{j})$ is solvable if and only if $x^{p} \equiv a  (\text{mod}\ p^{2}$) is solvable. My question is to do similar thing with $p^{2}$-th power, rather than just p-th power.
I have a hunch that even for my question, solution modulo $p^{2}$ should be enough. However, the proof I had for p-th power does not seem to generalize to $p^{2}$-th power. This makes me wonder if my hunch is wrong.

A: For $p$ odd prime, given $p\nmid a$, let $ab\equiv 1\bmod p$ and $c=ab^{p^2}$ then $c\equiv 1\bmod p$.
$\{ (1+pu)^{p^2}\bmod p^j\} = \{ 1+p^3 v\bmod p^j\}$ so that

There is a solution for $x^{p^2}\equiv a\bmod p^j$ iff there is one for $(1+pu)^{p^2}\equiv c\bmod p^j$ iff $c\equiv 1\bmod p^3$.


text:
Q: Typescript add static method to a method I have a method defined that wraps fetch in order to automatically handle certain edge cases and provide a unified response class alerting system. I don't want to automatically parse responses as json (the platform will not only be requesting JSON) and came up with the idea to add to the fetch method's prototype a .json call to auto-parse and coerce the promise but found that I couldn't use the prototype when calling integratedFetch.json(//etc). Is is possible to add such a static method?
Example code:
const integratedFetch: (
    input: RequestInfo,
    init?: RequestInit | undefined,
    options?: Partial<IntegratedFetchOptions>
) => Promise<Response> = (input, init, options) => {
    return fetch(input, init).then(async (response) => {
        const { status } = response;
        const responseClass = getResponseClass(response);
        if (responseClass) {
            switch (Number(responseClass) as ResponseClass) {
                case ResponseClass.Informational:
                    //etc
                case ResponseClass.Successful:
                    //etc
                default:
                    throw Error(`Response class ${responseClass} unrecognized`);
            }
        }
        return Promise.resolve(response);
    });
};
integratedFetch.prototype.json = <T>(input: RequestInfo, init?: RequestInit | undefined, options?: Partial<IntegratedFetchOptions>) =>
    integratedFetch(input, init, options).then((response) => response.json() as Promise<T>);

With expected usage to be:
integratedFetch.json<MyType>(//request)
-vs-
integratedFetch(//request).then(r => r.json() as Promise<T>)

The current problem being that using integratedFetch.json() gives the error "Property 'json' does not exist on type '(input: RequestInfo, init?: RequestInit | undefined, options?: Partial | undefined) => Promise<...>'.ts(2339)"

A: Just assign the second function to a new property of the first function. Typescript keeps track of that. No adjust of the prototype is necessary.
const foo = () => 123
foo.bar = () => 'hello'

foo() // 123
foo.bar() // "hello"

See Playground

A: Turns out I had to be a little more inventive with typedefs here...
type FetchParams = (input: RequestInfo, init?: RequestInit | undefined, options?: Partial<IntegratedFetchOptions>) => Promise<Response>;
type StaticParams = <T>(input: RequestInfo, init?: RequestInit | undefined, options?: Partial<IntegratedFetchOptions>) => Promise<T>;

//Create an aggregate typedef which allows for the static methods on the object definition
type IntegratedFetch = FetchParams & { json: StaticParams };

const integratedFetch: IntegratedFetch = (input, init, options) => { //the previous implementation

integratedFetch.json = <T>(input: RequestInfo, init?: RequestInit | undefined, options?: Partial<IntegratedFetchOptions>) =>
    integratedFetch(input, init, options).then((response) => response.json() as Promise<T>);

This avoids the TS2339 error and allows me to use the static method assigned to the function definition!


text:
Q: Subscribing to Event Handlers I'm curious about the pros and cons when subscribing to event handlers.
<asp:DropDownList id="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" />

vs
protected void Page_Init(object sender, EventArgs e)
{
    this.DropDownList1.SelectedIndexChanged += new EventHandler(DropDownList1_SelectedIndexChanged);
}

A: From the technical point of view, there aren't any big differences between the two, so it is a question of coding style and personal preferences. Here are a couple of points that you can consider:

*

*The declarative approach using the ASP.NET markup is usually shorter and you don't need a large method that does all the initialization

*If you initialize handlers in the code-behind you don't pollute the declarative markup with aspects relevant only for the code-behind (though I don't think this is a big issue)

In some cases you can use features such as C# lambda expressions nicely in the code-behind:
protected void Page_Init(object sender, EventArgs e) {
   this.btnNext += (s1, e1) => MovePage(this.CurrentPage + 1);
   this.btnPrev += (s2, e2) => MovePage(this.CurrentPage - 1);
   // ...
}

Something like this can reduce the number of single-purpose event handling methods that you need to write, which should make the code-behind simpler.
However, I think that the general recommendation for simple ASP.NET applications is to use the declarative event handler binding, unless you have some good reason for not doing that (e.g. as in the example above).

A: One difference is in compile time checking.  If you use the declarative method and for some reason you change the handler method name or signature you won't know it until the ASP.NET run time processes the page.  If you use the explicit binding in the code-behind then you'll get a compile time check on it.  A bit more stable.
Also, some will likely argue that putting the event handlers in the markup contradicts the rules of separation of concerns. Although with ASP.NET web forms, there's still a bit of crossover unlike the discreet separation found in the MVC framework.


text:
Q: Why do I get the error, "Object reference not set to an instance of an object"? This is homework, a math game/quiz that populates the text boxes with random numbers instead of the question marks.  It's an ASP.NET Web Form in Visual Studio 2012 using C#.  The requirement is to use some type of storage, so I'm using "Application" to store the user's name and their score, and when they click "Check Results," the Results panel will display their name and the score.  The error is on this line of the code behind:  Ranking.Add(NameText.Text, Score);, "Object reference not set to an instance of an object."  Thanks in advance!!!

HTML:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MathGame.aspx.cs" Inherits="MvcApplication3.MathGame" %>

<!DOCTYPE html>

    <title></title>

        <asp:Panel ID="PanelGame" runat="server">
        <form id="MathGame" runat="server">

        <asp:Label runat="server" BorderStyle="None" Font-Names="Microsoft Sans Serif" Font-Size="18pt" style="z-index: 1; top: 142px; position: absolute; height: 33px; text-align: center; right: 762px; margin-right: 87px; bottom: 312px; width: 2px; left: 145px;" Text="-"></asp:Label>
        <asp:Label ID="plusLeftLabel" runat="server" BorderStyle="Solid" Font-Names="Microsoft Sans Serif" Font-Size="18pt" style="z-index: 1; left: 48px; top: 75px; position: absolute; height: 33px; text-align: center; margin-right: 87px" Text="?" Width="60px"></asp:Label>
        <asp:Label ID="plusRightLabel" runat="server" BorderStyle="Solid" Font-Names="Microsoft Sans Serif" Font-Size="18pt" style="z-index: 1; left: 193px; top: 75px; position: absolute; height: 33px; text-align: center; margin-right: 87px" Text="?" Width="60px"></asp:Label>
        <asp:Label runat="server" BorderStyle="None" Font-Names="Microsoft Sans Serif" Font-Size="18pt" style="z-index: 1; left: 270px; top: 208px; position: absolute; height: 33px; text-align: center; margin-right: 87px" Text="=" Width="60px"></asp:Label>
        <asp:Button ID="startButton" runat="server" Font-Size="14pt" style="z-index: 1; left: 265px; top: 379px; position: absolute; height: 34px;" TabIndex="1" Text="Check Results" OnClick="startButton_Click1" ValidationGroup="FormValidation" />

        <asp:Label ID="dividedLeftLabel" runat="server" BorderStyle="Solid" Font-Names="Microsoft Sans Serif" Font-Size="18pt" style="z-index: 1; left: 47px; top: 262px; position: absolute; height: 33px; text-align: center; margin-right: 87px; right: 717px;" Text="?" Width="60px"></asp:Label>
        <asp:Label ID="minusLeftLabel" runat="server" BorderStyle="Solid" Font-Names="Microsoft Sans Serif" Font-Size="18pt" style="z-index: 1; left: 48px; top: 139px; position: absolute; height: 33px; text-align: center; margin-right: 87px" Text="?" Width="60px"></asp:Label>
        <asp:Label ID="timesLeftLabel" runat="server" BorderStyle="Solid" Font-Names="Microsoft Sans Serif" Font-Size="18pt" style="z-index: 1; left: 47px; top: 201px; position: absolute; height: 33px; text-align: center; margin-right: 87px; bottom: 315px;" Text="?" Width="60px"></asp:Label>
        <asp:Label runat="server" BorderStyle="None" Font-Names="Microsoft Sans Serif" Font-Size="18pt" style="z-index: 1; top: 83px; position: absolute; height: 33px; text-align: center; right: 667px; margin-right: 87px; left: 145px; bottom: 426px;" Text="+" Width="20px"></asp:Label>
        <asp:Label runat="server" BorderStyle="None" Font-Names="Microsoft Sans Serif" Font-Size="18pt" style="z-index: 1; top: 269px; position: absolute; height: 33px; text-align: center; right: 667px; margin-right: 87px; left: 145px;" Text="÷" Width="20px"></asp:Label>
        <asp:Label runat="server" BorderStyle="None" Font-Names="Microsoft Sans Serif" Font-Size="18pt" style="z-index: 1; top: 205px; position: absolute; height: 33px; text-align: center; right: 750px; margin-right: 87px; left: 145px;" Text="x" Width="20px"></asp:Label>
        <asp:Label ID="dividedRightLabel" runat="server" BorderStyle="Solid" Font-Names="Microsoft Sans Serif" Font-Size="18pt" style="z-index: 1; left: 193px; top: 262px; position: absolute; height: 33px; text-align: center; margin-right: 87px" Text="?" Width="60px"></asp:Label>
        <asp:Label ID="minusRightLabel" runat="server" BorderStyle="Solid" Font-Names="Microsoft Sans Serif" Font-Size="18pt" style="z-index: 1; left: 193px; top: 138px; position: absolute; height: 33px; text-align: center; margin-right: 87px" Text="?" Width="60px"></asp:Label>
        <asp:Label ID="timesRightLabel" runat="server" BorderStyle="Solid" Font-Names="Microsoft Sans Serif" Font-Size="18pt" style="z-index: 1; left: 192px; top: 202px; position: absolute; height: 33px; text-align: center; margin-right: 87px" Text="?" Width="60px"></asp:Label>
        <asp:Label runat="server" BorderStyle="None" Font-Names="Microsoft Sans Serif" Font-Size="18pt" style="z-index: 1; left: 269px; top: 82px; position: absolute; height: 33px; text-align: center; margin-right: 87px; width: 60px;" Text="="></asp:Label>
        <asp:Label runat="server" BorderStyle="None" Font-Names="Microsoft Sans Serif" Font-Size="18pt" style="z-index: 1; left: 270px; top: 269px; position: absolute; height: 33px; text-align: center; margin-right: 87px" Text="=" Width="60px"></asp:Label>

        <asp:Panel ID="Panel1" runat="server" style="z-index: 1; left: 49px; top: 333px; position: absolute; height: 19px; width: 367px">

Please enter your name: <asp:TextBox ID="NameText" runat="server" Height="17px"></asp:TextBox><asp:RequiredFieldValidator EnableClientScript="false" ID="RequiredFieldValidator1" runat="server" ErrorMessage="
Your name is required." ForeColor="Red" ControlToValidate="NameText" ValidationGroup="FormValidation"></asp:RequiredFieldValidator></asp:Panel>

        <asp:Label runat="server" BorderStyle="None" Font-Names="Microsoft Sans Serif" Font-Size="18pt" style="z-index: 1; left: 269px; top: 147px; position: absolute; height: 33px; text-align: center; margin-right: 87px" Text="=" Width="60px" ID="Label1"></asp:Label>
        <asp:TextBox ID="TimesResult" runat="server" style="z-index: 1; left: 324px; top: 210px; position: absolute; width: 87px; height: 19px"></asp:TextBox>
        <asp:TextBox ID="MinusResult" runat="server" style="z-index: 1; left: 324px; top: 146px; position: absolute; width: 87px; height: 19px"></asp:TextBox>
        <asp:TextBox ID="DivideResult" runat="server" style="z-index: 1; left: 324px; top: 269px; position: absolute; width: 87px; height: 19px"></asp:TextBox>
        <asp:TextBox ID="PlusResult" runat="server" style="z-index: 1; left: 324px; top: 81px; position: absolute; width: 87px; height: 19px"></asp:TextBox>

    </form></asp:Panel>

    <asp:Panel ID="PanelRanking" runat="server">
        <asp:BulletedList ID="RankingList" runat="server">
        </asp:BulletedList>
    </asp:Panel>

Code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MvcApplication3
{
    public partial class MathGame : System.Web.UI.Page
    {
        // Create a Random object to generate random numbers.
        Random randomizer = new Random();

        public void Page_Load(object sender, EventArgs e)
        {
            PanelRanking.Visible = false;
            plusLeftLabel.Text = randomizer.Next(51).ToString();
            plusRightLabel.Text = randomizer.Next(51).ToString();
            minusLeftLabel.Text = randomizer.Next(51).ToString();
            minusRightLabel.Text = randomizer.Next(51).ToString();
            timesLeftLabel.Text = randomizer.Next(51).ToString();
            timesRightLabel.Text = randomizer.Next(51).ToString();
            dividedLeftLabel.Text = randomizer.Next(51).ToString();
            dividedRightLabel.Text = randomizer.Next(51).ToString();
        }

        public void startButton_Click1(object sender, EventArgs e)
        {
            int Score = 0;
            // Check the answers

            if (int.Parse(plusLeftLabel.Text) + int.Parse(plusRightLabel.Text) == int.Parse(PlusResult.Text))
                Score += 1;

            if (int.Parse(minusLeftLabel.Text) - int.Parse(minusRightLabel.Text) == int.Parse(MinusResult.Text))
                Score += 1;

            if (int.Parse(timesLeftLabel.Text) + int.Parse(timesRightLabel.Text) == int.Parse(TimesResult.Text))
                Score += 1;

            if (int.Parse(dividedLeftLabel.Text) + int.Parse(dividedRightLabel.Text) == int.Parse(DivideResult.Text))
                Score += 1;

            Dictionary<string, int> Ranking = (Dictionary<string, int>)Application["Ranking"];
            *Ranking.Add(NameText.Text, Score);*
            Application.Lock();
            Application["Ranking"] = Ranking;
            Application.UnLock();

            foreach (KeyValuePair<string, int> element in Ranking){
                RankingList.Items.Add(element.ToString());
            }

        }

    }
}

A: Is this all of your code?  What is(Dictionary<string, int>)Application["Ranking"]; referencing?  Where is that data initialized?
You probably need to initialize it somewhere, or else its going to return null and Ranking.Add() will be trying to add to a null object.

A: you are using Application["Ranking"] directly. please check it against null before using it.
if(Application["Ranking"] != null){
}


text:
Q: Задать корневой каталог при подключении по ssh При подключении к сайту по ssh мы попадаем в корневой каталог. Где и что прописать чтоб при подключении ssh user@ip.host -p 22 я попадал не в /home/user/ , а в /home/user/var/www/ ?

A: По теме заголовка вопроса.
Использование ssh с логином в минимальное изолированное chroot окружение.
Установка сервера rsync+chroot+ssh
Установите необходимые пакеты:
apt-get install rsync rssh patch

Настройка chroot:
chmod u+s /usr/lib/rssh/rssh_chroot_helper
mkdir -p /var/lib/rsync_chroot/var/lib/rsync_chroot
ln -s ../../../home /var/lib/rsync_chroot/var/lib/rsync_chroot/home
mkdir -p /var/lib/rsync_chroot/{dev,etc,lib64,lib/x86_64-linux-gnu,usr/bin,home}
mknod -m 666 /var/lib/rsync_chroot/dev/null c 1 3
mknod -m 666 /var/lib/rsync_chroot/dev/zero c 1 5
ln -s /run/systemd/journal/dev-log /var/lib/rsync_chroot/dev/log
cp -r /etc/{ld.so.conf.d,ld.so.cache,ld.so.conf,nsswitch.conf} /var/lib/rsync_chroot/etc/
cp /lib/x86_64-linux-gnu/{libattr.so.1,libacl.so.1,libpopt.so.0,libc.so.6} /var/lib/rsync_chroot/lib/x86_64-linux-gnu/
cp /lib64/ld-linux-x86-64.so.2 /var/lib/rsync_chroot/lib64/
cp /usr/sbin/nologin /usr/bin/{rssh,rsync} /var/lib/rsync_chroot/usr/bin/

echo "13c13
< allowrsync
---
> #allowrsync
17c17
< umask = 022
---
> umask = 022
23c23
< chrootpath = /var/lib/rsync_chroot
---
> # chrootpath = /usr/local/chroot
" | patch -R /etc/rssh.conf

Настройка пользователя для синхронизации:
adduser --system --no-create-home --home /var/lib/rsync_chroot/home/repository --shell /usr/bin/rssh --group --disabled-password repository
mkdir -p /var/lib/rsync_chroot/home/repository/.ssh
chown repository:repository /var/lib/rsync_chroot/home/repository
chmod 0750 /var/lib/rsync_chroot/home/repository
cat > /var/lib/rsync_chroot/home/repository/.ssh/authorized_keys
  no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa AAAAB ... user@host

Отправка данных:
rsync -rlHpti --del --delete-excluded ./data_dir/ repository@hostname:~/data

A: добавьте команду
cd /нужный/каталог

в конец файла, интерпретируемого программой, выполняющей роль оболочки (shell), при запуске интерактивной сессии.
имя файла смотрите в документации к этой программе.
например, для программы

*

*bash это ~/.bashrc

*zsh это ~/.zshrc

*dash это ~/.profile


text:
Q: How to POST data to a server in Sencha Touch without using AJAX I am using Sencha Touch, I need post some data to a Server with a simple HTTP POST (NO AJAX)
At the moment I use
Ext.data.JsonP.request

Ext.Ajax.request

for my understanding both work with AJAX.
I would like to know how to disable the AJAX functionality and allow me to send some paramenters only via HTTP without using xhr and ajax.

A: You can create a form panel and then call the submit method with a url for the form to be submitted to:
// define your form
var form = Ext.create('Ext.form.Panel', {
  ...
  // your form fields, etc
});

// later, in some handler for a button click, etc
form.submit({
  url: 'url/to/submit.php',
  method: 'POST',
  success: function() {
    // handle successful form submit
  },
  failure: funciton() { ... }
});


text:
Q: Regarding ANCOVA and regression So i have a question with 1 continuous independent variable, 1 continuous dependent variable, 1 continuous co-variate while controlling for a categorical variable.
So i know analysis of co-variate is probably out of the question because of the continuous IV and i will probably have to use a regression.
Can anyone help with how i should do a regression with these 4 variables?

A: ANCOVA is not out of the question - that's just the situation it was intended for.
ANOVA, ANCOVA and multiple regression are all the same model.
Questions about how to code are off topic here, and you don't even say what programming language you use. But all statistical packages will have methods for multiple regression. If you need help, look at user manuals or at sites devoted to the package you are using.


text:
Q: Unable to call getWidth() on an Image I have an Image displayStartText and originalStartText initialized thusly:
Image originalStartText = new ImageIcon(getClass().getClassLoader().getResource( "GAME/resources/ready_set_fight.gif" )).getImage();
Image displayStartText = originalStartText;

I try to draw displayStartText centered in my background with:
g2d.drawImage( displayStartText, (int)((bgDispWidth-displayStartText.getWidth())/2), (int)((bgDispHeight-displayStartText.getHeight())/2), null );

But a compiler error that I don't understand shows up
Gameplay.java:694: error: method getWidth in class Image cannot be applied to given types;
     g2d.drawImage( displayStartText, (int)((bgDispWidth-displayStartText.getWidth())/2), (int)((bgDispHeight-displayStartText.getHeight())/2), null );
                                                                         ^
  required: ImageObserver
  found: no arguments
  reason: actual and formal argument lists differ in length

Any insights on why I might run into this issue?

A: Image doesn't have a getWidth() method, if you look at the JavaDocs you will find that it requires a parameter of ImageObserver, because the image might not be loaded when you request the value (because of the way it works), you can use an ImageObserver to be notified when data becomes available.
All Swing components implement ImageObserver, so you could (in theory) use this if the class was Swing based object or null if you don't have one.
If you're using null, then you should ensure that the image is loaded first, using MediaTracker for example, otherwise getWidth(ImageObsever) may return -1
A better solution (IMHO) would be to use ImageIO.read which will return a BufferedImage which is gurenteed to be loaded when it returns and saves you some of these problems.
Have a look at Reading/Loading an image for more details


text:
Q: How to replace all 'None's in a complex (nested) structure of lists and dictionaries Say I have a complex structure, consisting of nested dictionaries and lists. For example:
test_variable = [{'key1': [{'sub_key1': None}], 'key2': 'Value2'}, {'Key3': None}]

Is there anyway I can find and replace all of the None's, and replace them with, say, 'book'? I do know how to access each entry/key/value, but I'm looking for a way that works for any kind of given structure (no matter how nested), and not just the above example.
I have this code for a given structure, for example:
for key in test_dict:
    if isinstance(test_dict, list):
        for item in test_dict[key]:
            if isinstance(item, dict):
                for sub_key in item:
                    if item[sub_key] == None:
                        item[sub_key] = 'Book'

But I want something to work for any given structure.

A: Okay this is actually a really neat & tricky problem; to be able to remove all the "complexity" from our nested list and dive deep into our None's!

I'm assuming the structure follows the one provided in the example (nested lists & dictionaries),
though it can handle even more complicated structures (i.e. it can solve any form of nested dictionaries within lists and vice-versa)*

One can achieve the that by recursively iterating through the list's entrees (or dictionary's values) and checking their types then acting accordingly, until reaching a dictionary who's key value is None:
def none_eliminator(structure):
    if type(structure) == dict:  # Check whether the (main or sub) structure is a dictionary
        for thing in structure:  # If so, loop over its key values not keys themselves
            if structure[thing] is None:
                structure[thing] = 'insert_something'
            elif type(structure[thing]) == list or type(structure[thing]) == dict:  # In case the key's value was another dictionary or list
                none_eliminator(structure[thing])  # Iterate over it again until finding a key with a value of type "None"!

    else:  # (If list)
        for thing in structure:  # Iterate over all main entrees of the list
            if type(thing) == list:
                none_eliminator(thing)  # Keep looping over its sub entrees (thing) until it's a dictionary

            elif type(thing) == dict:  # Nested dictionary within a list
                for key in thing:
                    if type(thing[key]) == list:  # Just in case the key's value was a list itself
                        none_eliminator(thing[key])

                    if type(thing[key]) == dict:  # Just in case the key's value was a dictionary itself
                        none_eliminator(thing[key])

                    if thing[key] is None:
                        thing[key] = 'insert_something'

    return structure


text:
Q: Sort JSON arrays within a JSON array, with a custom order in PHP I'm trying to sort the array below, by id with a custom order, preferably by creating an array (2177,1073,2951). I've attempted to use various PHP functions, but can't figure out how to specify a custom order. The data is returned via an API in a random order, and I need it sorted so I can use it.
{
    "data": {
        "people": [
            {
                "id": "1073",
                "name": "rob",
            },
            {
                "id": "2951",
                "name": "cam",
            },
            {
                "id": "2177",
                "name": "mike",
            }
        ]

    }
}

I want to turn the above into this:
{
    "data": {
        "people": [
            {
                "id": "2177",
                "name": "mike",
            },
            {
                "id": "1073",
                "name": "rob",
            },
            {
                "id": "2951",
                "name": "cam",
            }
        ]

    }
}


text:
Q: Multiplexing problem with Arduino, MAX7219 e BJT I tested the circuit below with an Arduino UNO, a MAX7219 and BC338. The sketch in Arduino is a chaser, so the leds should turn on in sequence. It consist of 7 segment (A-G) and two Digit (0-1).
The problem is that when one segment is turned on (and only that led sould be), also the same segment on the other digit is turned on. The problem si showed in the image below.
I tried with pull-up resistor and other tests, but I don't know what's the problem. Thank you for your help.

A: Brhans is right you can't put NPN transistors there you either need a pullup resistor or PNP there but i fail to see the point since inside max u already have a NPN transistor driving that line. I think you will have better luck if you explain what you are trying to accomplish, im guessing some weird dimming or something similar witch wont work anyway. Have in mind that 7219 uses multiplexing as a means to drive more than 8 leds.

A: You don't need those transistors in your circuit.
The DIG outputs of the MAX7219 are designed to sink current directly from the common point of your LEDs.
If for some reason you really think you need transistors in there, then use PNPs instead of the NPNs you have.


text:
Q: Converting from int[] to int* I have a C++ .DLL and C# application. In DLL I have a function like:
namespace Sample
   {
    public ref class SampleClass
    {
     public:
      int f(int arr[], int length);
    };
   }
How can I call it from C# application? Problem is that in C++ I can use only int* argument and cannot declare int[], and only int[] variable in c#.
I have tried to declare int*[] type in C# but it is impossible due to

Cannot take address of a managed type

error. I have no idea how can I put an array into this function.
Upd:
trying to dllimport like
[DllImport("samplelib.fll", EntryPoint = "Sample.SampleClass.f")]

but that seems to be wrong.

A: I'm not sure, if this is what you want. Your example seems at bit incomplete ...
Let's say you have something like this in C/C++:
void TakesAnArray(int size, int array[]) {
   printf_s("[unmanaged]\n");
   for (int i=0; i<size; i++)
      printf("%d = %d\n", i, array[i]);
}

Then you want to call ist from C#, so you create a wrapper class.
internal static class NativeMethods
{
   [DllImport("SomeLib.dll" )]
   public static extern void TakesAnArray(int size, [In, Out] int[] array);
}

A: int[] arr = new int[10];
int ptrsize = arr.Length * Marshal.SizeOf(typeof(int));
IntPtr arrptr = Marshal.AllocHGlobal(ptrsize);
Marshal.Copy(arr, 0, arrptr, ptrsize);
NativeFunction(arr.Length, arrptr);
//after
Marshal.FreeHGlobal(arrptr);

Use the array as a pointer
void NativeFunction(int length, int* array) { /*...*/ }

Import(.\\ is executable path)
[DllImport(".\\MyLib.dll")]
static extern void NativeFunction(int length, IntPtr array);


text:
Q: Keycloak 16 docker default ${jboss.server.data.dir} location I would like to add a password-blacklist to Keycloak 16 running in a docker container. I have tried to add the blacklist to /opt/jboss/keycloak/password-blacklists/ and /opt/jboss/keycloak/standalone/data/password-blacklists/ but in both places the file could not be found.
The documentations says the following: "Blacklist files resolve against ${jboss.server.data.dir}/password-blacklists/ by default."
So what is path is the default ${jboss.server.data.dir} using the docker container?

A: https://docs.jboss.org/author/display/WFLY8/Command%20line%20parameters.html
jboss.server.data.dir = jboss.server.base.dir/data
->
jboss.server.base.dir = jboss.home.dir/standalone
->
jboss.home.dir = Set by standalone.sh to $JBOSS_HOME

and $JBOSS_HOME is:
docker run --rm -ti --entrypoint bash quay.io/keycloak/keycloak:16.1.0 -c 'echo $JBOSS_HOME'
/opt/jboss/keycloak

So jboss.server.data.dir = /opt/jboss/keycloak/standalone/data/
Keep in mind that Keycloak is running under jboss user (uid=1000), so set file permissions accordingly.


text:
Q: Descobrir o usuário que atualizou o wordpress É possível descobrir qual usuário realizou o update do wordpress?
Sabem se fica algum registro no banco de dados ou algo do tipo? Eu tenho acesso ao FTP, tive que fazer um backup e voltar a hospedagem para 7 dias atrás, algum usuário atualizou o wordpress e limpou toda a programação php que eu havia feito.
Valeu


text:
Q: Wifi Signal Strengths I hope that I have asked this question in the right topic.
Basically I use BT (In the U.K.) and I have problems with my router receiving a weak signal in certain rooms of the house, which, therefore makes the internet really slow in some cases it won't work at all.
I have had experience working with Virgin Media (UK) before and just changed the channel number and this worked fine, but, do not know if I would receive the same outcome on BT.
Could anyone suggest any other things that I could try alongside of the channel change in order to /hopefully/ get a stronger signal, without having to install Ethernet cable?

A: This should be on SuperUser, but...
Use a program like InSSIDer to get an idea if there are any conflicting WiFi networks in your area, and set yours to a non-conflicting channel For b/g networks, the channels go from 1-11 (at least in the US), with channels 1, 6, and 11 the recommended channels to use. Also, make sure that your WiFi access point isn't next to a microwave, enclosed behind a solid metal wall, or have its Ethernet cable run along the length of a fluorescent bulb (all will cause interference and signal degradation). Placing the AP on top of a bookshelf or other high place will give it a better ability to broadcast its signal as well.


text:
Q: Eclipse debugger - not work suddenly ( waiting for debugger forever) I have coded Android by Eclipse IDE for such a long time. However Eclipse is working fine, and can not debug suddenly.
The message is "... is waiting for debugger to attach." and keep that screen forever.
I have tried to add android.permission.SET_DEBUG_APP to Manifest file but nothing is changed.
I realize that in Log cat mentioned "waiting for debugger at port 8100" while in console, the message is "Attempting to connect .... port 8609". Anything's wrong with this?
Help me, please. Thanks.

A: Several ways to get around this:

*

*Unplug then plug in again usb-cable ( if you're connecting with usb port)

*Restart device

*Restart java

I've met this case so many times and still have no idea why, but after doing some above tricks, it works :o really weird Android :(

A: Once try to clean the project, open the project in debug view, check once the breakpoints and try to debug again. If not restart the eclispe once. Hope this helps

A: Run debug app once then again try using run app...this will do.


text:
Q: Filtering on a ProjectToList in LINQ I am using MediatR to request A visualizationDto
public VisualizationResponse Handle(VisualizationQuery message)
{
    return new VisualizationResponse
    {
        LoadTick = DateTime.Now.Ticks,
        Visualization = new VisualizationDto
        {
            infeed = context.Unloaders.ProjectToList<InfeedDto>(),
            Levels = context.Levels.ProjectToList<LevelDto>()
        }
    };
}

These get mapped directly from a DbContext. Now the problem is that ProjectToList<> maps recursively. In the level there's a list of buffers and in each buffer there's a list of stacks. Now i only need to map the stacks that have a TimeOut value of null. I don't want to filter trough everything after mapping because this might slow down things. And i tried
var lq = context.Levels;
var stacks = lq
    .SelectMany(l => l.Buffers)
    .SelectMany(b => b.StackLocations)
    .Where(s => s.TimeOut == null);

Levels = lq.ProjectTo<LevelDto>().Select(l => new {l, stacks}).ToList().Select(x => x.l).ToList()

But the values i receive aren't the filtered ones still the full dataset. Are there any other ways to filter on a ProjectToList?
right now i have an output that looks like
List<LevelDto>
-List<BufferDto>
  -List<StackLocationDto>
    -stack timeIn- TimeOut
    -stack timeIn- TimeOut
    -stack timeIn- null
    -stack timeIn- null

i need to filter out the stacks that are already finished so those that do not have a TimeOut of null.

A: The Where condition is only executed to stacks not to lq. Try stacks.ProjectTo<LevelDto>(), that should do the trick.


text:
Q: issues when installing Ruby on Rails on Ubuntu-12.04 LTS I have been trying to install Ruby On Rails on my Ubuntu-12.04 machine. I am installing through a Ubuntu blog as it was suggested by people to be a successful installation guide . But when I tried to run the command " rvm requirements ", I get
" Error running 'requirements_debian_update_system ',
please read /home/arsalan/.rvm/log/1386743809/update_system.log
Requirements installation failed with status: 100."

I have no idea of how to resolve this error . I will appreciate every help.
Thanks
Regards


text:
Q: Uploading image to server(mysql database) using android and php In my code i am having two images and two edittext fields to send to the database using php file.Here in my code i am able to insert 2 images along with the edittext fileds without any problem.
Now whats my problem is when a user enters two  edittext fields and selects only one image to insert, it is throwing NullPointerException.Here with this code i have to select 2 images mandatorily..how can i make that one optional.?I mean user can select one/two image based on his requirement.But if i select only one image,it is throwing null pointer exception.please help me..!!

MainActivity.java
package com.example.test;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;

public class MainActivity extends Activity implements View.OnClickListener {

    private Button buttonUpload;
    private Button buttonChoose;
    private Button buttonChoose1;

    private EditText edithouse;
    private EditText editbuild;
    private ImageView imageView;
    private ImageView imageView1;

    public static final String KEY_IMAGE = "image";
    public static final String KEY_IMAGE1 = "image1";
    public static final String KEY_TEXT = "house";
    public static final String KEY_TEXT1 = "build";
    public static final String UPLOAD_URL = "http://oursite/PhotoUploadWithText/upload.php";

    private int PICK_IMAGE_REQUEST = 1;
    private int PICK_IMAGE_REQUEST1 = 2;

    private Bitmap bitmap;
    private Bitmap bitmap1;

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

        buttonUpload = (Button) findViewById(R.id.save);
        buttonChoose = (Button) findViewById(R.id.choose);
        buttonChoose1 = (Button) findViewById(R.id.choose1);

        edithouse = (EditText) findViewById(R.id.houseno);
        editbuild = (EditText) findViewById(R.id.buildno);
        imageView = (ImageView) findViewById(R.id.imageViews);
        imageView1 = (ImageView) findViewById(R.id.imageViews1);

        buttonChoose.setOnClickListener(this);
        buttonChoose1.setOnClickListener(this);
        buttonUpload.setOnClickListener(this);
    }

    private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }
          private void showFileChooser1() {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST1);
        }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                //bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                imageView.setImageBitmap(bitmap);
               // imageView1.setImageBitmap(bitmap1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (requestCode == PICK_IMAGE_REQUEST1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();
            try {
                //bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                //imageView.setImageBitmap(bitmap);
                imageView1.setImageBitmap(bitmap1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String getStringImage(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }

    public String getStringImage1(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }

    public void uploadImage(){
        final String house = edithouse.getText().toString().trim();
        final String build = editbuild.getText().toString().trim();
        final String image = getStringImage(bitmap);
        final String image1 = getStringImage1(bitmap1);
        class UploadImage extends AsyncTask<Void,Void,String>{
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(MainActivity.this,"Please wait...","uploading",false,false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
            }

            @Override
            protected String doInBackground(Void... params) {
                RequestHandler rh = new RequestHandler();
                HashMap<String,String> param = new HashMap<String,String>();
                param.put(KEY_TEXT,house);
                param.put(KEY_TEXT1,build);
                param.put(KEY_IMAGE,image);
                param.put(KEY_IMAGE1,image1);
                String result = rh.sendPostRequest(UPLOAD_URL, param);
                return result;
            }
        }
        UploadImage u = new UploadImage();
        u.execute();
    }

    @Override
    public void onClick(View v) {
        if(v == buttonChoose){
            showFileChooser();
        }
        if(v == buttonUpload){
            uploadImage();
        }
        if(v == buttonChoose1){
            showFileChooser1();
        }
    }
}

upload.php

<?php

    if($_SERVER['REQUEST_METHOD']=='POST'){
        $image = $_POST['image'];
        $house = $_POST['house '];
        $image1 = $_POST['image1'];
        $build = $_POST['build '];

        require_once('dbConnect.php');

        $sql ="SELECT id FROM uploads ORDER BY id ASC";

        $res = mysqli_query($con,$sql);

         $id = uniqid();

        while($row = mysqli_fetch_array($res)){
                $id = $row['id'];
        }

        $path = "uploads/".uniqid().".png";
                $path1 = "uploads/".uniqid().".png";

        $actualpath  = "$path";
        $actualpath1  = "$path1";

        $sql = "INSERT INTO uploads (image,house,image1,build) VALUES ('$actualpath','$house','$actualpath1','$build')";

        if(mysqli_query($con,$sql)){
            file_put_contents($path,base64_decode($image));
                        file_put_contents($path1,base64_decode($image1));
            echo "Successfully Uploaded";
        }

        mysqli_close($con);
    }else{
        echo "Error";
    }
?>

Here is the error..
Logcat

02-17 17:28:33.261: E/AndroidRuntime(14710): FATAL EXCEPTION: main
02-17 17:28:33.261: E/AndroidRuntime(14710): java.lang.NullPointerException
02-17 17:28:33.261: E/AndroidRuntime(14710):    at com.example.test.MainActivity.getStringImage1(MainActivity.java:118)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at com.example.test.MainActivity.uploadImage(MainActivity.java:129)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at com.example.test.MainActivity.onClick(MainActivity.java:168)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at android.view.View.performClick(View.java:4191)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at android.view.View$PerformClick.run(View.java:17229)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at android.os.Handler.handleCallback(Handler.java:615)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at android.os.Handler.dispatchMessage(Handler.java:92)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at android.os.Looper.loop(Looper.java:137)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at android.app.ActivityThread.main(ActivityThread.java:4960)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at java.lang.reflect.Method.invokeNative(Native Method)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at java.lang.reflect.Method.invoke(Method.java:511)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
02-17 17:28:33.261: E/AndroidRuntime(14710):    at dalvik.system.NativeStart.main(Native Method)

A: When you call  public void uploadImage()
check
String image = null;
String image1 = null;
    if(bitmap != null)
        image = getStringImage(bitmap);
    if(bitmap1 != null)
        image1 = getStringImage1(bitmap1);

also Check
if(image != null)
    param.put(KEY_IMAGE,image);
if(image1 != null)
    param.put(KEY_IMAGE1,image1);

String result = rh.sendPostRequest(UPLOAD_URL, param);

and then also in php check if

KEY_IMAGE

and

KEY_IMAGE1

exists then do whatever you want to do, otherwise php will throw an error for undefined index.

A: You are selecting one image and uploading two in uploadimage method...
just use below code it will work for you..
String image1 = "";
     if(bitmap1!=null)
     image1 = getStringImage1(bitmap1);


text:
Q: RavenDB performance for large XML documents We're evaluating whether to use RavenDB for handling XML documents of varying sizes. In our use cases, the performance of retrieving documents is far more important than that of storing documents.
We're using the embedded version of RavenDB, because we're running a standalone Windows application - I don't know if that has a negative impact on performance ?
In our tests, retrieving larger XML documents (e.g. 2.5Mb) seems to be quite slow - even when storing them in RavenFS.
We've tried to run some comparison tests, and here are the results:
-Reading directly from an on-disk XML file: ~20ms
-Reading from RavenDB (RavenFS): ~400ms
-Reading from RavenDB (string property in DocumentStore): ~500-600ms
-Reading as binary data from an embedded relational database (SQL-CE4): ~75ms

We were expecting RavenDB to be slower than accessing a file directly, but we're quite surprised that even when using RavenFS, it's still 5 times slower than using a relational database.
Are we missing something, or is it simply because RavenDB is designed for different use cases ?
TIA,
Kenneth


text:
Q: Client caching overrides custom Last-Modified when rendering a View I recently started working on a MVC.NET project and soon noticed there was no caching of the front-page. Setting [OutputCache(Duration = 60), Location = Client] on the Index() method added the right Expires headings, but since Last-Modified was set to the time the page was created the caching would never kick in.
As an experiment, I then manually tried setting the Last-Modified header to some time in the past, to see how that worked, but it seems as if is being overwritten somewhere! I added this code to the end of my Index() action:
    DateTime dt = DateTime.Parse("2015-12-01");
    var timeString = dt.ToUniversalTime().ToString("R");

    var v =  View("Index", homeViewModel);
    Response.AddHeader("Last-Modified", timeString);

    return v;

Even though I could debug and inspect the headers in the Response and see the header being added, the returned page in the browser still had Last-Modified: Wed, 09 Mar 2016 15:34:12 GMT (the current time). My manually set header was thus overwritten by some other code after the action returned.
What is causing this behaviour, and how can I manually set the last-modified timestamp to enable caching?

Addendum
using Location = ServerAndClient will make client caching work again, which beats me as somewhat odd ... If, so what use is the Client option? How can it ever work?

A: It is the OutputCache attribute that is overwriting the relevant headers I pass along. Removing that will make it possible to set whatever headers I like.

And to answer the second question of when the Client option makes sense, be aware that you will never see any effect when refreshing the browser window. It is only when you click links that the browser will decide if it should reuse the cached version.


text:
Q: Image registration, construction of Composite Image I'm working in an image registration algorithm. I have the reference image(I1) and the sensed image(I2). The images are numpy arrays.
I implemented an fft algorithm that take I1 and I2 and returns a new image(I3) that is the result of aplying at I2 the transformations that would make possible the match between reference and sensed images.
Also this fft algorithm returns the transformations parameters that I used to transform I2 in I3. More specifically also I3, the algorithm returns: scale factor, rotation angle and translation vector.
How I can generate a new composite image between I1 and I3? Is there any function in any python library that makes this possible?
What I want to do is something like the image of the link(http://i.stack.imgur.com/Yv0ls.png) . Having the reference Image, sensed with the transformations to match with reference image,create the composite image between them (the picture of the bottom of the image). In my case I have only two images.

A: Use skimage.transform.AffineTransform to represent the transformations.  Apply them to the individual images using skimage.transform.warp.  While you can implement your own blending algorithms, I'd recommend Enblend (http://enblend.sf.net).  Here's a small demo for registering two images:
https://github.com/stefanv/scikit-image-demos/blob/master/register.py


text:
Q: How do I set the colour of brackets/braces/parentheses in Emacs? I'd like to specify the colour of {}, () and [] in a custom colour theme. Is this possible?
Update: Here's the source. Please note the in-development status of this theme; it is unsafe for use both at the workplace and around the home.
;;; Color theme based on Moria for VIM.
(defun color-theme-moria ()
  "A color theme based on Moria for VIM."
  (interactive)
  (color-theme-install
   '(color-theme-moria
     ((foreground-color . "#000000") ;done
      (cursor-color . "#ffffff")
      (background-color . "#f0f0f0") ;done
      (background-mode . light)) ;done
     (default ((t (nil)))) ;done
     (underline ((t (:underline t)))) ;done
     (modeline ((t (:foreground "black" :background "#000000"))))
     (modeline-buffer-id ((t (:foreground "red" :background "#0000ff"))))
     (modeline-mousable ((t (:foreground "cyan" :background "#007080"))))
     (modeline-mousable-minor-mode ((t (:foreground "cyan" :background "#007080"))))
     (highlight ((t (:background "#d0d0d0")))) ;done
     (region ((t (:background "#c0c0c0")))) ;done
     (font-lock-builtin-face ((t (:foreground "black"))))
     (font-lock-constant-face ((t (:foreground "#ff0000")))) ;hmmm
     (font-lock-comment-face ((t (:foreground "#786000")))) ;done
     (font-lock-function-name-face ((t (:foreground "#000000" )))) ;done
     ; highlight ma brackets
     (font-lock-add-keywords nil '(("\\([\{\}\\[\]\(\)]+\\)" 1 font-lock-keyword-face prepend)))
     (font-lock-preprocessor-face ((t (:foreground "#912F11" :bold t))))
     (font-lock-keyword-face ((t (:foreground "#1f3f81" :bold t)))) ; done e.g. defun

     (font-lock-string-face ((t (:foreground "#077807")))) ;done
     (font-lock-variable-name-face ((t (:foreground "#ff0000" )))) ;hmmm
     (font-lock-warning-face ((t (:foreground "#ff0000"))))
     (highlight-changes-face ((t (:background "#ff0000"))))
     (highlight-changes-delete-face ((t (:foreground "red" :background "pink"))))
     (show-paren-match ((t (:foreground "#2e3436" :background "#73d216"))))

     (widget-field-face ((t (:foreground "pink" :background "red"))))
     (widget-inactive-face ((t (:foreground "gray"))))
     (custom-button-face ((t (:foreground "yellow" :background "dark blue"))))
     (custom-state-face ((t (:foreground "mediumaquamarine"))))
     (custom-face-tag-face ((t (:foreground "goldenrod" :underline t))))
     (custom-documentation-face ((t (:foreground "#10D010"))))
     (custom-set-face ((t (:foreground "#2020D0"))))
     )
   )
  )

A: Try:
(font-lock-add-keywords nil '(("\\([\{\}\\[\]\(\)]+\\)" 1 font-lock-keyword-face prepend)))

For parent match only:
Evaluate the following expression or put it into your .emacs:
(custom-set-faces
 '(show-paren-match ((t (:background "blue"))))
 '(show-paren-mismatch ((((class color)) (:background "red" :foreground "white")))))

A: You can use rainbow-delimiters mode, you can install it from MELPA in Emacs24 packages system or download rainbow-delimiters.el from:
emacswiki-RainbowDelimiters
place rainbow-delimiters.el on your emacs load-path
write init code in your .emacs file:
(require 'rainbow-delimiters)

(global-rainbow-delimiters-mode)


text:
Q: How to retrieve students data based on teachers ID According to a simple scenario ER diagram as follows.

Based on that, I developed a database mapping as follows.

In there, orange color columns shows the primary key of the tables and yellow color columns shows foreign key of the tables. Is this mapping correct? Now my problem is I need to retrieve students data who learned from some teacher, which means need to retrieve some teacher's sudents who learned from his/her.

A: You need to learn about how to join tables using different types of available JOINs.
For your scenario , try like following, it will give you Student and the Teacher mapping.
select s.*
tbl_student s
inner join tbl_Course_Subjects tcs on s.Course_Id= tcs.Course_Id
inner join tbl_Subjects_Teacher tst on tst.SubjectId=tcs.Subject_Id
inner join tbl_Teacher t on t.Teacher_Id=tst.Teacher_Id
where t.Teacher_Id = @SomeTeacherId