text:
Q: Does a class inherit an abstract inner class declared within an interface when the class implements that interface? I am running the following java version
openjdk version "10.0.1" 2018-04-17
OpenJDK Runtime Environment (build 10.0.1+10-Ubuntu-3ubuntu1)
OpenJDK 64-Bit Server VM (build 10.0.1+10-Ubuntu-3ubuntu1, mixed mode)
Program 1
class Outer{
abstract class Inner{
    void m1(){
        System.out.println("Inner class m1 method");
    }
  }

 }

class Outer2 extends Outer.Inner{
Outer2(){
new Outer().super();
  }
}
class Test{
public static void main(String[] args) {
new Outer2().m1();
 }
}

input: deep (master *) JavaStuffs $ javac sample.java
deep (master *) JavaStuffs $ java Test
output: Inner class m1 method
Program 2
interface Outer{
    abstract class Inner{
    void m1(){
        System.out.println("Inner class m1 method");
    }
  }
}
class J implements Outer{

}
class Outer2 extends J.Inner{

Outer2(){
    new J().super();
  }
}
class Test{
public static void main(String[] args) {
    new Outer2().m1();

  }
}

input: deep (master *) JavaStuffs $ javac sample.java
output: sample.java:1309: error: illegal qualifier; Inner is not an inner class
        new J().super();
               ^
   1 error
Program 3
interface Outer{
abstract class Inner{
    void m1(){
        System.out.println("Inner class m1 method");
   }
 }
}
class J implements Outer{
class InnerJ extends Inner{

 }
}
class Outer2 extends J.Inner{
Outer2(){
new J().super();
 }
}
class Test{
public static void main(String[] args) {
    new J().new InnerJ().m1();
    new Outer2().m1();
 }
}

input: deep (master *) JavaStuffs $ javac sample.java
output: sample.java:1372: error: illegal qualifier; Inner is not an inner class
        new J().super();
               ^
   1 error
Here in Program 2 and Program 3 I expected that the class will inherit the inner abstract class when it implements the interface. But it's not happening so! Can anyone explain? A precise reason will be highly appreciated!

A: A member class defined inside an interface is always implicitly static. It's not an inner class, but a static member class, and it doesn't have an outer class instance associated with it.
The Java Language Specification states this in section 9.5:

A member type declaration in an interface is implicitly public and
  static. It is permitted to redundantly specify either or both of these
  modifiers.

Hence, in your program 2, inside the constructor of class Outer2, you cannot say new J().super();, because Outer2 doesn't have an outer instance - it is not an inner class. The error from javac says as much: "illegal qualifier; Inner is not an inner class"

A: No.  Classes inherit instance variables and instance methods from their parents, and they implement the same interfaces.  They can access static members of their parent classes and directly or indirectly implemented interfaces as if they were inherited, but that's technically a different story.
Nested classes and interfaces are not inherited, neither from parent classes nor from implemented interfaces, but an instance of a child class can serve as the containing instance of its parent class's inner class.
Nesting a class or interface inside another provides first and foremost an additional level of namespacing.  Parent.Inner is a different class from Child.Inner -- without considering any other factor, you know because their names are different.  Child classes do not, therefore, inherit nested classes.  There's no good way to do it, and no particular advantage either.


text:
Q: I got an error: (POST net::ERR_SSL_PROTOCOL_ERROR) I'm trying to deploy model (deep learning, classification for cats and dogs) using Flask on web app. When I upload an image of cat or a dog, I should get some predictions, but get only an error. I have code written in python and javascript.
This is an error:
"jquery-3.3.1.min.js:2 POST https://127.0.0.1:5000/static/predict.html net::ERR_SSL_PROTOCOL_ERROR"
<!DOCTYPE html>

    <title>Predict the bottle</title>

    <input type="file" id="image-selector">
    <button id="predict-button">Predict</button>

Predictions

Dog:

Cat:

import base64
import numpy as np
import io

import keras
from keras import backend as K
from keras.models import Sequential
from keras.models import load_model
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import img_to_array
from flask import request
from flask import jsonify
from flask import Flask
from PIL import Image

app = Flask(__name__)

def get_model():
    global model
    model = load_model('VGG16_cats_and_dogs.h5')
    print(" * Model loaded!")

def preprocess_image(image, target_size):
    if image.mode != "RGB":
        image = image.convert("RGB")
    image = image.resize(target_size)
    image = img_to_array(image)
    image = np.expand_dims(image, axis=0)

    return image

print(" * Loading Keras model...")
get_model()

@app.route("/predict", methods=["POST"])
def predict():
    message = request.get_json(force=True)
    encoded = message['image']
    decoded = base64.b64decode(encoded)
    image = Image.open(io.BytesIO(decoded))
    processed_image = preprocess_image(image, target_size=(224, 224))

    prediction = model.predict(processed_image).toList()

    response = {
        'Prediction': {
            'dog': prediction[0][0],
            'cat': prediction[0][1]
        }
    }
    return jsonify(response)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use the Firebase to send data to my PHP code I am working with arduino project and I used PHP to connect to the Firebase.
I want to receive a data from firebase using PHP. I want the $new_ssid and $new_password to received from Firebase.
Here's my code:
<?php

require 'firebaseLib.php';
$Trash = $_GET["trash"];

$Distance = $_GET["distance"];
$Temperature = $_GET["temp_f"];
$Humidity= $_GET["humidity"];

$baseURI = 'x';
$token = 'x';

$devicestatus= array('Distance' => $Distance,'Temperature' =>
$Temperature,'Humidity' => $Humidity);

$firebasePath = '/x/';
$full= array($Trash => $devicestatus);

$fb = new Firebase($baseURI, $token);
$fb -> update($firebasePath, $full);

$new_ssid = "arduino";
$new_pass = "mechanical";
echo $new_ssid."/".$new_pass ;
?>


text:
Q: CRC32 checksum different during runtime and JUnit test I currently have a strange problem. I read a file using the following function, create an object from it and store the file content as a byte array in the object as well.
public static Iodd readFile(File file) throws IOException {
    if (!file.getName().endsWith(".xml"))
        throw new InvalidObjectException("Not a valid IODD XML file");

    String s = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
    Iodd i = new XmlMapper().readValue(s, Iodd.class);

    i.setFile(Files.readAllBytes(file.toPath()));

    return i;
}

In the file there is a CRC32 checksum. During the runtime of the program I can reproduce the checksum without problems using the java.util.zip.CRC32 class. But if I want to test the same way using a JUnit test now, I get a completely different checksum.
The test file you can find here. Please use the the XML-file without country code.
Am I missing something?
I have already checked if the byte arrays are different in the JUnit test and during runtime but everything matches. For testing purpose I created a MD5 checksum from the file content and check it with the MD5 from the JUnit test but they are equal.
Function for interest
This is the function which calculates the CRC32 checksum. The method removeStamp removes the crc-value from the stamp tag.
public static boolean isValidInternal(final byte[] data, final long checkCrc) {
    CRC32 c = new CRC32();
    c.update(removeStamp(data));

    return (c.getValue() == checkCrc);
}

Update 1
I add a new class with a main and add an output to the crc calculation method.
public class App {
    private final static String TESTFILE = "testfile-iodd-tv7105.xml";

    public static void main(String[] args) throws IOException {
        File f = new File(Iodd.class.getClassLoader().getResource(TESTFILE).getFile());
        Iodd i = Iodd.readFile(f);
        System.out.println(i.isValid());
    }
}

Output from the IntelliJ Run:
checkCrc: 1195433981
CRC32: 1195433981
true
Output from the Maven test command in IntelliJ:
checkCrc: 1195433981
CRC32: 2019633554

A: Thank you. I hope the problem is solved now. mvn test runs without problems from IntelliJ and Bash.
The solution was that I set the following configurations for the maven-surefire-plugin in the pom.xml:

*

*reuseForks: false

*forkCount: 0

*useSystemClassLoader: false (surpress warning that this option is not used when reuseForks option is false)

<plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.1</version>
    <configuration>
        <reuseForks>false</reuseForks>
        <forkCount>0</forkCount>
        <useSystemClassLoader>false</useSystemClassLoader>
    </configuration>
</plugin>


text:
Q: XML Document System.Net.WebException This part of my code throws an exception. How can I fix that?
XmlDocument locrequest = new XmlDocument();
locrequest.Load(String.Format("http://api.geoips.com/ip/{0}/key/.myapikey./output/xml/", player.IP));
XmlNode root = locrequest.DocumentElement;
string from = root.SelectSingleNode("country_name").InnerText.ToLower();

System.Net.WebException: Error: ConnectFailure (Not enough buffer space is available)

Full error http://pastebin.com/8u6MpeWS
Edit:
If I add
locrequest.XmlResolver = null;
it throws another exception:

System.NullReferenceException: Object reference not set to an instance of an object

What's wrong with that?

A: You can use WebRequest class in order to load file
Link : http://msdn.microsoft.com/library/system.net.webrequest.aspx
WebRequest request = WebRequest.Create ("...");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream ();
.....

A: Building on Aghilas' post...
The returned stream is a non-seekable stream, so you need to read to the end of it using a function similar to the following:
static byte[] readFullStream(Stream st)
    {
        Array Buffer = (byte[])Array.CreateInstance(typeof(byte), 32768);
        System.Int32 Size;
        bool eof = false;
        MemoryStream ms = new MemoryStream();
        while (!eof)
        {
            Size = st.Read((byte[])Buffer, 0, Buffer.Length);
            if (Size > 0)
            {
                ms.Write((byte[])Buffer, 0, Size);
            }
            else
            {
                eof = true;
            }
        }
        return ms.ToArray();
    }

Then once you have the byte array from the function above, load up your XmlDocument with it.
Remember, we're starting from the bottom of Aghilas' code...
byte[] buffer = readFullStream(dataStream);
XmlDocument locrequest = new XmlDocument();
locrequest.LoadXML(new UFT8Encoding().GetString(buffer));

Hope this helps.

A: Ingo,
Building on your original post for this problem here, perhaps this will put the pieces together for you a bit more clearly. Assuming that there is something more basic at hand for the connection failures than just that the server is, for whatever reason, not accepting connections, you can bypass the default Load() mechanism of the XmlDocument class by using, as Aghilas pointed out, a WebRequest object.
A WebRequest object contacts the URL you specify, and then uses the Request/Response model to create a Response object. From that Response object, you can get a stream to the data for the response via the GetResponseStream() method; that's what Aghilas demonstrated. You can then take that stream, placed in the variable dataStream in his sample, and pass that to the overload for the XmlDocument.Load() method that expects a Stream:
   //assuming prior code from Aghilas is here as appropriate...
   Stream dataStream = response.GetResponseStream();
   XmlDocument locRequest = new XmlDocument();
   locRequest.Load(dataStream);

Hope this helps.


text:
Q: Rails better way to use array in raw postgres query I am writing raw query in rails and executing it with:
ActiveRecord::Base.connection.execute(query)

Is there any better way to convert this?:
completions.type IN ('#{params[:certification].join("','")}')

where
params[:certification]
#=> ['Gold', 'Platinum']

and I want it to be like
completions.type IN ('Gold', 'Platinum')

Same way Active record does
Completion.where(type: ['Gold', 'Platinum'])

This is my query which I can't write with active record
SELECT type, json_array_elements(
              replace(
                (completions::json)::character varying,
                'null',
                '[]'
              )::json) AS completions_json
FROM completions
WHERE completions.type IN ('#{params[:certification].join("','")}')
AND (
  date(completions_json->>'completed_at')
    BETWEEN date('2015-10-01')
    AND     date('2015-12-01')
)

A: From: http://guides.rubyonrails.org/active_record_querying.html#subset-conditions
Client.where(orders_count: [1,3,5])

so in your case:
Completions.where(type: params[:certification])

Assuming that you are using an active record model; with raw queries your milage may vary.


text:
Q: How to fix dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream. while using maven surefire plugin 3.0.0-M4 I got the below error while executing the command mvn clean test. Even though I changed the versions of the surefire plugin but still I'm facing the same error.
Error Log:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:3.0.0-M4:test (default-test) on pr
oject info: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\Sheik Mohammed\eclipse-workspace\info\target\surefire-reports for the individua
l test results.
Error 1:
[ERROR] Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
Error 2:
[ERROR] ExecutionException The forked VM terminated without properly saying goodbye. VM crash or System.exit called?
Error 3:
[ERROR] Command was cmd.exe /X /C ""C:\Program Files\Java\jdk1.8.0_311\jre\bin\java" "-javaagent:C:\Users\Sheik
Mohammed.m2\repository/org/aspectj/aspectjweaver/1.8.10/aspectjweaver-1.8.10.jar" "    -Dcucumber.options=--plu
gin io.qameta.allure.cucumber4jvm.AllureCucumber4Jvm"   --add-modules java.base ${argLine} -Xmx1024m -XX:MaxPerm
Size=256m org.apache.maven.surefire.booter.ForkedBooter "C:\Users\Sheik Mohammed\AppData\Local\Temp\surefire8647
270359642587079" 2022-02-27T09-33-26_575-jvmRun1 surefire8833373504517140594tmp surefire_08041519546226636871tmp
"
Error 4:
[ERROR] Error occurred in starting fork, check output in log
[ERROR] Process Exit Code: 1
[ERROR] org.apache.maven.surefire.booter.SurefireBooterForkException: ExecutionException The forked VM terminate
d without properly saying goodbye. VM crash or System.exit called?
[ERROR] Command was cmd.exe /X /C ""C:\Program Files\Java\jdk1.8.0_311\jre\bin\java" "-javaagent:C:\Users\Sheik
Mohammed.m2\repository/org/aspectj/aspectjweaver/1.8.10/aspectjweaver-1.8.10.jar" "    -Dcucumber.options=--plu
gin io.qameta.allure.cucumber4jvm.AllureCucumber4Jvm"   --add-modules java.base ${argLine} -Xmx1024m -XX:MaxPerm
Size=256m org.apache.maven.surefire.booter.ForkedBooter "C:\Users\Sheik Mohammed\AppData\Local\Temp\surefire8647
270359642587079" 2022-02-27T09-33-26_575-jvmRun1 surefire8833373504517140594tmp surefire_08041519546226636871tmp
"
[ERROR] Error occurred in starting fork, check output in log
pom.xml
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <aspectj.version>1.8.10</aspectj.version>
     <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

    <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M4</version>

            <configuration>
                <useSystemClassLoader>false</useSystemClassLoader>
                <forkedProcessExitTimeoutInSeconds>120</forkedProcessExitTimeoutInSeconds>
                <forkCount>3</forkCount>
                <reuseForks>true</reuseForks>
                <argLine>
                    -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
                    -Dcucumber.options="--plugin io.qameta.allure.cucumber4jvm.AllureCucumber4Jvm"
                    --add-modules java.base ${argLine} -Xmx1024m -XX:MaxPermSize=256m
                </argLine>

                <systemPropertyVariables>
                    <allure.results.directory>${project.build.directory}/allure-results</allure.results.directory>
                    <allure.link.issue.pattern>https://example.org/browse/{}</allure.link.issue.pattern>
                    <allure.link.tms.pattern>https://example.org/browse/{}</allure.link.tms.pattern>
                </systemPropertyVariables>
            </configuration>

            <dependencies>
                <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
                <dependency>
                <groupId>org.aspectj</groupId>
                    <artifactId>aspectjweaver</artifactId>
                    <version>${aspectj.version}</version>

                </dependency>

            </dependencies>
        </plugin>
    </plugins>
  </build>

  <dependencies>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.1</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.141.59</version>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>io.github.bonigarcia</groupId>
      <artifactId>webdrivermanager</artifactId>
      <version>4.2.2</version>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>tech.grasshopper</groupId>
      <artifactId>extentreports-cucumber6-adapter</artifactId>
      <version>2.6.0</version>
      <scope>compile</scope>
      <exclusions>
        <exclusion>
          <artifactId>pdfbox2-layout</artifactId>
          <groupId>com.github.ralfstuckert.pdfbox-layout</groupId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>6.14.3</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
      <version>1.7.25</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>4.1.2</version>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>4.1.2</version>
      <scope>compile</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-java -->
    <dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>4.8.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/io.cucumber/cucumber-testng -->
    <dependency>
    <groupId>io.cucumber</groupId>
    <artifactId>cucumber-testng</artifactId>
    <version>4.8.1</version>
    </dependency>

    <dependency>
        <groupId>io.cucumber</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>6.9.0</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-core</artifactId>
        <version>1.2.5</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/io.qameta.allure/allure-cucumber4-jvm -->
    <dependency>
    <groupId>io.qameta.allure</groupId>
    <artifactId>allure-cucumber4-jvm</artifactId>
    <version>2.13.3</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/io.qameta.allure/allure-maven -->
    <dependency>
    <groupId>io.qameta.allure</groupId>
    <artifactId>allure-maven</artifactId>
    <version>2.10.0</version>
    </dependency>

     <dependency>
            <groupId>io.qameta.allure</groupId>
            <artifactId>allure-testng</artifactId>
            <version>2.13.0</version>
     </dependency>

    <!-- <dependency>
     <groupId>org.apache.maven.surefire</groupId>
     <artifactId>surefire</artifactId>
     <version>3.0.0-M4</version>
     <type>pom</type>
     </dependency>-->

  </dependencies>

A: You can try this:
Add this code in the plugins section of your pom.xml
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.22.2</version>
    <configuration>
    <skipTests>true</skipTests>
    </configuration>
</plugin>

You can see this link
https://programmerah.com/solved-there-are-test-failures-please-refer-to-djava_studyspringbootspringboot-sugon-3targetsurefire-reports-for-the-individual-test-results-28892/

A: <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<skip>true</skip>
 </configuration>
</plugin>

A: The problem can be solve by changing the environnement excecution of MVN.
Try this command:
- apt install locales-all
- update-locale LANG=fr_FR.UTF-8 LANGUAGE
- update-locale LC_TIME=fr_FR.UTF-8
- update-locale LANG="fr_FR.UTF-8" LANGUAGE="fr_FR"
- dpkg-reconfigure locales
- apt-get update >/dev/null
- apt-get install -y locales >/dev/null
- echo "fr_FR UTF-8" > /etc/locale.gen
- locale-gen fr_FR.UTF-8
- export LANG=fr_FR.UTF-8
- export LANGUAGE=fr_FR:fr
- export LC_ALL=fr_FR.UTF-8

A: I had this error and it happened because of a failed unit test. So, you just need to check the failed unit test and make it pass to bypass this error.


text:
Q: Phalcon Fatal error: Class 'Phalcon\Mvc\Application' not found in I have this file directory:

When I open this project in browser: Fatal error: Class 'Phalcon\Mvc\Application' not found in...
I read that I have to install composer but when I install composer this errors occure:

How can I run my project?
My composer.json file consists:
    "require": {
        "phalcon/incubator-mailer": "^1.0",
        "smi2/phpclickhouse": "^1.4",
        "hybridauth/hybridauth": "^3.8"
    }
}```

A: There are in fact two problems.

*

*You are missing the phalcon php extension. You can find the instructions on how to install the extension in the official Phalcon documentation.

*You need at least php version 7.3 to satisfy the requirements of smi2/phpclickhouse. Since php 7.x is EOL since 26th of November 2022, I'd strongly suggest to upgrade to the latest version which currently is php 8.1.
Once you resolved the two problems, composer install should run successfully, and the missing classes should be placed in the vendor directory.

A: Following up on some of the other comments, Phalcon 4 is NOT compatible with PHP 8.1.  Phalcon 4 requires PHP 7.4.
If you plan on running PHP 8.1, you will need to install Phalcon 5.1.1.
You can find the Phalcon installation documentation on at https://phalcon.io


text:
Q: SQLite - complex queries I am getting random row from my table using the following query:
SELECT value_id FROM table1 ORDER BY RANDOM() LIMIT 1

I have 3 tables:
table1 and table2 - they are tables that have an id of a row and its value.
there is as well table3 which has as its columns IDs of rows in table1 and table2.
i.e. :
table1:
1 - Canada
2 - USA
3 - UK
4 - France
5 - Africa
6 - China

table2:
1 - New York
2 - Vancouver
3 - Paris
4 - London
5 - Ottawa
6 - Los Angeles

table3: (without table3 rowid)
1 - 2
1 - 5
2 - 1
2 - 6
3 - 4
4 - 3

So from table 3 I can say that New York is a city in USA, and so on. And as well in table3 I can have undefined values. (In the example they are Africa and China so I don't want to get them in a result)
What I want to do is to get from table1 random IDs but only those that are defined in table3. In this particular case I don't want to receive 5 and 6 as a result.
How can I rewrite my query to achieve my goal?
Thank you in advance.
Edit:
The problem is that when I am trying to get a row which row in table3 is not defined, application cruses. It is not NULL, as I wrote before, it just doesn't exist in table3. How can I rewrite the query to properly handle my case?

A: You haven't told us how the fields in table3 are named, but supposing for example they're named tab1_id and tab2_id with the obvious meanings, try:
SELECT table1.value_id
FROM table1 INNER JOIN table3 ON table1.value_id=table3.tab1_id
WHERE table3.tab2_id IS NOT NULL
ORDER BY RANDOM() LIMIT 1

A: Order by Random() means that it will randomly order by different column.
Use this:
SELECT value_id FROM table3
  WHERE rowid>=random() % (SELECT max(rowid) FROM table3)
  AND second_value IS NOT NULL
  LIMIT 1;

don't know the name of column2, so I've called it second_value

A: Not an SQLite question but a generic SQL issue. You want to test for NULL in the field values, e.g.
SELECT f1 FROM table
 WHERE f2 IS NOT NULL
ORDER BY RANDOM() LIMIT 1;

A: SELECT rowid FROM table1
WHERE rowid IN ( SELECT DISTINCT table1_id FROM table3 )
ORDER BY RANDOM() LIMIT 1;

This query means "choose at random a row from table1 which has an entry in table3".
Every row in table1 equal likelihood of being selected (DISTINCT) as long as it is referenced at least once in table3.
If you are trying to get ALL columns from table1 that are in table3, then you should remove the "ORDER BY RANDOM() LIMIT 1" clause.


text:
Q: ORA-00918: column ambiguously defined: how to find the column I'm getting the classic error:

ORA-00918: column ambiguously defined

Usually, I know how to solve it but my problem now is that I'm working with a 700 row query.
Is there a way to identify the column?

A: Have you tried to do a binary search?
e.g.
If your original query looks like
Select  col1
       ,col2
       ,col3
       ,col4
from MyTable

*

*you can start with commenting the 2nd half

Select  col1
       ,col2
       /*,col3
       ,col4 */
from MyTable

*If you still get the error, run the query again commenting some column from the other half:

Select col1
       /*,col2 */
      ,col3
      ,col4
from MyTable

If you still get an error then your problem is with col1, otherwise you need to change col2.

A: The ambiguous column error message indicates that you have joined two (or more) columns in your query which share the same column name.
The proper way to solve this is to give each table in the query an alias and then prefix all column references with the appropriate alias.  I agree that won't be fun for such a large query but I'm afraid you will have to pay the price of your predecessor's laxness.

A: In Oracle, you can use all_tab_cols to query the columns names of your tables. The following query will return the common column names between TABLE1 and TABLE2. Then you just need to prefix those common columns instead of all 100 column references.
select column_name from all_tab_cols
where table_name='TABLE1' and owner ='OWNER1'
and column_name in (
select column_name from all_tab_cols
where table_name='TABLE2' and owner ='OWNER2')

A: For posterity's sake:
I had this issue when I selected columns TABLE1.DES and TABLE2.DES in a query without aliasing the result.  When I ran it alone my SQL editor turned these into DES and DES_1, no complaint.
However when I turned the same query into a subquery
SELECT a.col1, a.col2, a.col3, b.*
from TABLE3 a
INNER JOIN (
--that query as a subquery
) b
on a.PK=b.FK`

it threw the same ORA-00918 error message you described.  Changing the SELECT in my subquery to
SELECT TABLE1.DES AS T1_DES, TABLE2.DES AS T2_DES ...
fixed the issue.

A: you can check common columns by using :
 select COLUMN_NAME from ALL_TAB_COLS where TABLE_NAME = 'tablenamefirst'
intersect
select COLUMN_NAME from ALL_TAB_COLS where TABLE_NAME = 'tablenamesecond';


text:
Q: Rails: making sure after_create runs in rspec I'm having issues with getting Rspec to run my after_create hook.
My User model:
class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable, :recoverable, :rememberable,
         :trackable, :validatable, :confirmable

  has_one :user_profile

  after_create :create_user_profile

  protected

  def create_user_profile
    self.user_profile = UserProfile.new(user: self)
    self.user_profile.save
  end
end

My UserProfile model:
class UserProfile < ActiveRecord::Base
  belongs_to :user

  has_attached_file :avatar,
    styles: { medium: "300x300>", thumb: "100x100>" },
    default_url: "/images/:style/missing.png"
  validates_attachment :avatar,
    content_type: { content_type: "image/jpeg" }
end

My spec:
require 'rails_helper'

RSpec.describe UserProfile, :type => :model do
  describe 'initial create' do
    before do
      @user = User.new(email: 'user@example.com',
                       password: 's3kr3t',
                       password_confirmation: 's3kr3t')
      @user.save
    end

    it 'should have profile' do
      expect(@user.user_profile).to be_valid
    end
  end
end

Fails with error:
Failures:                                                                                │~
                                                                                │~
  1) UserProfile initial create should have profile                                                                                │~
     Failure/Error: expect(@user.user_profile).to be_valid                                                                             │~
     NoMethodError:                                                                                │~
       undefined method `valid?' for nil:NilClass                                                                                │~
     # ./spec/models/user_profile_spec.rb:16:in `block (3 levels) in <top (required)>'                                                 │~

A: You could do something like this:
RSpec.describe UserProfile, :type => :model do
  describe 'initial create' do
    let(:user) { User.new(email: 'user@example.com',
                       password: 's3kr3t',
                       password_confirmation: 's3kr3t') }

    it 'should have profile' do
      @user.save
      expect(@user.user_profile).to_not be_nil
    end

    it "shouldn't have valid profile if not saved" do
      expect(@user.user_profile).to be_nil
    end
  end
end

A: It turns out the given code had multiple errors, most of which had to do with an invalid User model:

*

*Devise expects a password to be 8 chars minimum (so my User model wasn't saved due to its invalidity).

*I missed adding the 3 "confirmable" fields to the User model migration.

*After migrating my User model, I needed to add a "confirmed_at" attribute to the instantiated User model.

*My UserProfile model was also missing a "user_id" attribute in its migration.

Once I fixed these issues, the code worked as expected.


text:
Q: VueJS mounted function has effect throughout the app and not just on a required Route I have an app on VueJS. I am turning on my browser camera and microphone when I got to a route /golive , when I go back to my main page I see that my camera and microphone remain on.
I am added the functions to turn media on in my mounted() function, Is there any other way to implement this?


text:
Q: Server excution failed error I suffer from this problem since updating to windows 1o. It Happens after every new start when I paly music files with windows media player. At the same time the network and homegroup done t work. The only solution is to reboot.

A: This happens a lot to me. When this happens, do NOT close Windows Media Player, but instead re-open the file you were trying to open.
To avoid this, you can also open Windows Media Player first and then open the file you are trying to play.
If the above doesn't work:
You can try resetting Windows Media Player, which should hopefully get rid of this problem,

*

*Open the Run command and type the following without quotes. This will reset Windows Media Player.
    "msdt.exe -id WindowsMediaPlayerConfigurationDiagnostic"

*If Step 1 didn't work, you can also reset WMP following these instructions: http://answers.microsoft.com/en-us/windows/forum/windows_7-pictures/how-to-reset-windows-media-player-to-default/60c1903d-7bde-465a-8361-2e522ed742f1


text:
Q: Javascript not functioning when clicking the back button I have this code in place
let showAboutSection = () => {
  if(userInfo.logged && userInfo.subscriber && !userInfo.in_trial) {
  let section = document.querySelector('.cbt-tabs')
   if(section) {
    if(!section.classList.contains('touched')) {
    section.style.display = 'block'
    section.classList.add('touched')
    return
  }
}
}
setTimeout(showAboutSection, 500)
}

showAboutSection()

But if you click on the back button or on one of my navigation tabs without refreshing the screen, it does not function. Please help!


text:
Q: How to get the order of JQGrid Columns displayed? I have a jqGrid in my page. I am giving an option to hide/show columns to the user(using columnchooser) and also he will be able to rearrange the columns using the same columnchooser option. Once the user has done the configuration he can export the grid as it is to excel.
I have managed to do everything. But only problem i am facing is the column order. My Grid's column model will have the same order as grid columns order or i have to find out the order?
If i have to find the order of columns, how can we do that?

A: The key point of the solution of your problem are

*

*the usage of remapColumns parameter of jqGrid which hold the information about the last permutation of the columns

*the usage of remapColumns method of jqGrid to apply the permutation to the grid.

*the overwriting of the default implementation of done callback of the columnChooser method

Please don't confuse the remapColumns method with the internal remapColumns parameter (the same name!!!) of jqGrid which represent array on the column indexes.
I recommend you to examine the code of the demo or this one and read the answer and another answers to the close problems referenced in the "UPDATED X" part of the answer. The demos shows how you can use remapColumns method and parameter and how to use done callback of columnChooser to save and later restore the order of columns.


text:
Q: Literal parenthesis with python regex I have a dictionary ( e.g. English - Croatian). It may contain sentences and phrases. I'm translating a file of form "english text" = "english text" into form "english text" = "croatian text" and using python regex module to do so.
The regex I'm using looks like this (given variable original which is text in English that should be translated:
regexString = '(?<= = ")'+original+'(?=")'

That way I'am able to capture exactly the english text inside the quotes on the right-hand side and substitute it with Croatian. However, the problem appears if the original text contains parenthesis inside. In example:
original = 'This is a wonderland :)'

In that case an error "unbalanced parenthesis" is raised. If original would be hard-coded, I could solve the problem by putting
original = 'This is a wonderland :\\)'

However, there is a whole file full of *original * variables.
Is there any solution to this problem other than changing original variable by preceeding all parenthesis in it with a backslash?

A: You can use re.escape to handle this:
regexString = '(?<= = ")' + re.escape(original) + '(?=")'


text:
Q: PHP Unit Testing - Mock static autoloaded class with Mockery I want to unit test a wrapper class for the official Segment PHP integration. Therefore I'll have to mock the Segment class with Mockery so there won't be any real API requests.
The Problem
The class to mock consists only of static methods. Because of this I try to mock it like this (with alias):
$segment = Mockery::mock('alias:Segment');
This works, but only if the class isn't autoloaded by composer. If I load it - like I have to for the rest of the app - I'll get the error
Could not load mock Segment, class already exists.
(That makes sense, because the docs state that an aliased class must not be loaded before.)
The question
How can I mock this (evil?) class, but still use it as usual in the rest of my app?

A: Essentially, you cannot mock classes with static calls.
Static calls always reference exactly the class and method to be called, which is equivalent to pointing to exactly the file and line of code to be executed (if you assume basic autoloading capability is available).
The only way to execute different code is to NOT having included the original class, but to load the mock class code first. It does not matter if you have an alternative code file, or if you are calling eval() by using Mockery. Both ways will work.
But they will also work only one time. You cannot switch back to the original code in a later test, because the class can only be defined once per script run. And not being able to switch implementations (like original vs. mocked vs. another mocked) is the problem here.
The solution, which also was mentioned in the comments: Don't have classes with static methods. Always create instances of classes and call dynamic methods. This way you can easily mock the class, but it requires to create an instance first, and offer a way to inject the class (or at least the mocked class) into the code you want to test.
As a generic pattern I am using this if dependency injection is not available in the project (I have to deal with some legacy stuff at times):
public function __construct(MyClass $class = null) {
    $this->class = $class ?: new MyClass();
}

This way I don't have to inject the class, but I would be able to inject a mock instead of the real class.
For situations where dependency injection is available, the constructor will be a very basic initializer:
public function __construct(MyClass $class) {
    $this->class = $class;
}

This works great if your dependency injection framework is able to do auto wiring (like PHP-DI), and you only have exactly one MyClass, because this will be automatically injected without you having to define anything.


text:
Q: Como passar o data com o id para a controller sem permitir que o usuário faça manipulação pela tela? Botão:

Função ajax:

Controller:
 [CotacaoContratoSecure(Tela = new[] { enuDominioTela.Produtos }, Acao = new[] { enuDominioTelaAcao.Excluir })]
        public ActionResult Delete(ProdutoDeleteViewModel produtoDeleteViewModel)
        {
            ProdutoDeleteDTO produtoDeleteDTO = new ProdutoDeleteDTO(produtoDeleteViewModel.UserCredentials)
            {
                Id = produtoDeleteViewModel.ProdutoId,
                SegmentoId = produtoDeleteViewModel.SegmentoId.HasValue ? produtoDeleteViewModel.SegmentoId.Value : 0
            };

            ProdutoService.Excluir(produtoDeleteDTO);

            return JsonResultHelper.Redirect(Url.Action("Index", obterListaGrid()));
        }


text:
Q: How to create a powershell script that reads an xml file that has just been created? I am using Bamboo to create a an .xml file that will read all the attributes that I require.  At the moment my script looks like this:
[xml]$XmlDocument = Get-Content C:\Users\c.d\TestResult.xml
foreach ($Success in $XmlDocument.'test-results')
{
   Write-Host  $XmlDocument.'test-results'.'test-suite'.'results'.'test-suite'.'results'.'test-suite'.'results'.'test-suite'.'results'.'test-suite'.'results'.'test-suite'.'results'.'test-suite'.'results'.'test-case'.success
   Write-Host $XmlDocument.'test-results'.'test-suite'.'results'.'test-suite'.'results'.'test-suite'.'results'.'test-suite'.'results'.'test-suite'.'results'.'test-suite'.'results'.'test-suite'.'results'.'test-case'.result
}

This all works perfectly fine but as you can see this is me having to go through so many child nodes just to get to the attributes I need (and this is a relatively small amount of tests for this project)
The problem is that the script will be used for many .xml results files, so some with have a greater amount of child node paths than others but all with have the final attributes that I need, so I was trying to figure out if I could just serach for the final attribute e.g. success by doing somethign like "~/.success" or "//success" but everything I have tried will not display anything then, is there a way of doing this?
For example if this was my xml file
<myUsers>
<Users>
  <User>
    <Name>a</Name>
  </User>
  <User>
    <Name>b</Name>
  </User>
</Users>
</myUsers>

Instead of doing:
   Write-Host $userfile.'myUsers'.'Users'.'User'.Name

Can I do:
   Write-Host '~/'.Name

Also I should note that in me example the node names that are create as the exact same so I don't know if this would affect the solution.


text:
Q: mysqldiff tool drops indexes and adds duplicates and causes errors I'm using the mysqldiff tool (v1.5.3) from MySQL to synchronize the schema between two databases.  The databases should have the same schema, but would like to produce a file that only has the ALTER TABLE differences between them so it can (after thorough testing) be run in production.
The problem is that the mysqldiff tool produces some weirdness.  For example:
ALTER TABLE `database1`.`ACCOUNT_TRANSACTIONS`
DROP INDEX MATCHING_TRANSACTION_ID,
DROP INDEX PAYEE_ID,
ADD INDEX CHECK_NUMBER (ACCOUNT_ID),
ADD INDEX PAYEE_ID (PAYEE_ID),
ADD INDEX CHECK_NUMBER (PAYEE_ID,CHECK_NUMBER);

It seems to not only drop the indexes, but tries to recreate the new index through two statements that produce an error.  The final schema should have CHECK_NUMBER (ACCOUNT_ID, PAYEE_ID, CHECK_NUMBER) as the index.
What might be causing this?

Final version:
CREATE TABLE `ACCOUNT_TRANSACTIONS` (
`TRANSACTION_ID` int(12) NOT NULL AUTO_INCREMENT,
`ACCOUNT_ID` int(1) DEFAULT NULL,
`REF_NUMBER` varchar(15) DEFAULT NULL,
`PAYEE_ID` int(6) DEFAULT NULL,
`ACCOUNT_CHART_ID` int(12) DEFAULT NULL,
`TRANSACTION_AMOUNT` decimal(10,2) DEFAULT NULL,
`TRANSACTION_DATE` date DEFAULT NULL,
`MEMO` varchar(100) DEFAULT NULL,
`ACCOUNT_BALANCE` decimal(10,2) DEFAULT NULL,
`DEBIT_OR_CREDIT` char(1) DEFAULT 'D',
`MATCHING_TRANSACTION_ID` int(11) DEFAULT '0',
`RECONCILED_DATE` date DEFAULT NULL,
`RECONCILED_EMPLOYEE_ID` int(12) DEFAULT NULL,
`TIME_UPDATED` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`CHECK_NUMBER` bigint(20) unsigned DEFAULT NULL,
`STATEMENT_ID` int(12) DEFAULT NULL,
PRIMARY KEY (`TRANSACTION_ID`),
KEY `PAYEE_ID` (`PAYEE_ID`),
KEY `CHECK_NUMBER` (`CHECK_NUMBER`,`ACCOUNT_ID`,`PAYEE_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=xxx DEFAULT CHARSET=latin1

Original version (needs to be altered to be final version)
CREATE TABLE `ACCOUNT_TRANSACTIONS` (
`TRANSACTION_ID` int(12) NOT NULL AUTO_INCREMENT,
`ACCOUNT_ID` int(1) DEFAULT NULL,
`REF_NUMBER` varchar(15) DEFAULT NULL,
`PAYEE_ID` int(6) DEFAULT NULL,
`ACCOUNT_CHART_ID` int(12) DEFAULT NULL,
`TRANSACTION_AMOUNT` decimal(10,2) DEFAULT NULL,
`TRANSACTION_DATE` date DEFAULT NULL,
`MEMO` varchar(100) DEFAULT NULL,
`ACCOUNT_BALANCE` decimal(10,2) DEFAULT NULL,
`DEBIT_OR_CREDIT` char(1) DEFAULT 'D',
`MATCHING_TRANSACTION_ID` int(11) DEFAULT '0',
`RECONCILED_DATE` date DEFAULT NULL,
`RECONCILED_EMPLOYEE_ID` int(12) DEFAULT NULL,
`TIME_UPDATED` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`CHECK_NUMBER` bigint(20) unsigned DEFAULT NULL,
`STATEMENT_ID` int(12) DEFAULT NULL,
PRIMARY KEY (`TRANSACTION_ID`),
KEY `PAYEE_ID` (`PAYEE_ID`),
KEY `MATCHING_TRANSACTION_ID` (`MATCHING_TRANSACTION_ID`)
) ENGINE=MyISAM AUTO_INCREMENT=xxx DEFAULT CHARSET=latin1


text:
Q: Google Slides API seemingly ignoring API key I believe I'm having the same issue outlined here but that thread never achieved a satisfactory resolution. Essentially I already have a working interface for the Google Sheets API, I added the discoveryDoc and scope for the Slides API to my gapi.client.init() call but when I try to read from my Google presentation with gapi.client.slides.presentations.get() I am met with error code 401 "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential." I have verified that the Slides API is enabled for my API key and I have verified that the presentation I am trying to read from is public, in fact the example presentation provided for the API example page doesn't work either, seemingly my API key is being completely ignored.
gapi.load('client:auth2', () =>
  {
    gapi.client.init({ apiKey: API_KEY,
                       clientId: CLIENT_ID,
                       discoveryDocs: ["https://slides.googleapis.com/$discovery/rest?version=v1", "https://sheets.googleapis.com/$discovery/rest?version=v4"],
                       scope: "https://www.googleapis.com/auth/presentations.readonly https://www.googleapis.com/auth/spreadsheets.readonly"})
    .then(()=>{}, (e)=>{console.log(e)});
  });

EDIT: This is clearly an issue on Google's end. If I use the example documents for the Google Sheets API and the Google Slides API, the id for the public spreadsheet provided for the example documentation is "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms" while the id for the public presentation provided for the Slides API is "1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc".
If I replicate the https GET request being generated through the Sheets API for the provided public example spreadsheet (format is https://sheets.googleapis.com/v4/spreadsheets/[spreadsheetId]?key=[apiKey]) and enter that into my browser with the provided spreadsheet id and my own API key I get the following:

If I replicate the http GET request being generated by the Slides API for the example presentation (format is https://slides.googleapis.com/v1/presentations/[presentationId]?key=[apiKey]) and enter that into my browser with the given presentation id and my API key I get the following:

And since I already verified that I have both the Sheets API and the Sides API enabled for my API Key the issue clearly lies on googles end since the process laid out in their own documentation works for one but not the other. In fact, if I cut the API key in half or scramble it or leave it off altogether i will get an error for the Sheets url that says the API key is not valid, whereas if I do all the same to the Slides url I never get a message about the API key being invalid and still get the same error 401 I've been getting. The Google Slides API blatantly ignores API keys.
Edit 2: This has been reported here over 2 years ago and has been blatantly ignored. Glad a wasted my whole day trying to solve this. Someone should tell google to scrap their API documentation


text:
Q: FOR - getElementByName and i value Following my code:
for(var i =0; i < document.getElementById('test').getElementsByTagName("li").length; i++){
    document.getElementById('test').getElementsByTagName("li")[i].onmouseover= function(){
    alert(document.getElementById('test').getElementsByTagName("li")[i].innerHTML);
    }
}

HTML:

test

test2

test3

test4

JSfiddle: http://jsfiddle.net/Pwddf/1/
"i" is always assigned the last value and then does not work. How to solve?

A: The problem is scoping. If you create a function inside of a loop, the loop variables will always have their last loop values. Basically, the loop executes, but the variables inside the function declaration are not evaluated until the function is called, at which point "i" is equal to the last value. You can use a closure to make the vars resolve immediately.
for(var i =0; i < document.getElementById('test').getElementsByTagName("li").length; i++){
    (function(i) {
        document.getElementById('test').getElementsByTagName("li")[i].onmouseover= function(){
            alert(document.getElementById('test').getElementsByTagName("li")[i].innerHTML);
        };
    })(i);
}

I also agree with tymeJV that you should store your elements first, rather than reselecting them.

A: Looks like you want querySelectorAll instead:
var elems = document.querySelectorAll("#test ul li");
for (var i = 0; i < elems.length; i++) {
    elems[i].onmouseover = function() {
        console.log("See?");
    }
}

If you actually need that i value, use a closure inside the for:
(function(i) {
    elems[i].onmouseover = function() {
        console.log("See?" + i);
    }
})(i)

Demo: http://jsfiddle.net/Pwddf/2/

A: Here is a very concise solution that works in jsfiddle inside Firefox and IE9:
var elems = document.getElementById("test").getElementsByTagName("li");
for(var i =0; i < elems.length; i++){
    elems[i].onmouseover= function(e){
       console.log(this.innerHTML);
       console.log(e);
    }
}

http://jsfiddle.net/8LyhN/1/
Not knowing what all you are planning to do inside your mouseover event, I recommend passing in the event so you can reference it as 'e'.

A: You need to cache i;
    for(var i =0; i < document.getElementById('test').getElementsByTagName("li").length; i++)
    {
       var _i = i;
        document.getElementById('test').getElementsByTagName("li")[i].onmouseover= function()
        {

        alert(document.getElementById('test').getElementsByTagName("li")[_i].innerHTML);
        }
    }

// Even better;
var elements = document.getElementById('test').getElementsByTagName("li");
for(var i =0; i < elements.length; i++)
{
    elements[i].addEventListener('mouseover', function()
    {
    alert(this.innerHTML);
    });
}

A: You should do like this if you really want to use javascript than JQuery.
var ul = document.getElementById("test");
var li = ul.getElementsByTagName("li");

for(var i =0; i <li.length; i++){
    li[i].onmouseover= function(){
        alert(this.innerHTML);
    }
}

check here : http://jsfiddle.net/alaminopu/Pwddf/5/


text:
Q: request parameter in a Cloud Page I made a cloud page in MC that allows me to update some field in SC
>   %%[ if RequestParameter("submitted") == true then ]%%
>
Dziękujemy!

>
 sans-serif ;font-size:14px;"> Zmiany zostały zapisane.

>       %%[ else ]%%
>       <form action="%%=RequestParameter('PAGEURL')=%%" method="post">

>           Jesteś pewien, że chcesz zrezygnować z otrzymywania od nas wiadomości?

>
 <input type="radio" id="NIE" name="Optin" value="False">
>           NIE

>
<input type="radio" id="TAK" name="Optin" value="True">
>           TAK

>          <input name="submitted" type="hidden" value="true" />
>          <input type="submit" value="POTWIERDŹ">
>       </form>
>       %%[ endif ]%%   </fieldset>

>     %%[ Set @Id= '00Q9E000005akYkUAI'
>
> if RequestParameter("submitted") == true then
> UpdateSingleSalesforceObject("Lead",@Id,"OptInEmail__c", False,
> "OptInSMS__c", False)
> endif   ]%%

and when I run the page and click on the button I have a server error(500 - Internal server error.)

A: The problem comes certainly from the UpdateDE function.
Fist of all, you need to use UpdateData instead of UpdateDE. UpdateDE only works in an email send while UpdateData is used with landing pages and SMS messages
The first parameter of the UpdateDE stands for the number of columns used to build WHERE clause. And since you are using one field to do the where, you need to use something like:
UpdateData("DE_Lead_PL", 1, "Id", @Id,"OptInEmail", False, "OptInSMS", False)

Update:
Your problem can be related to the UpdateSingleSalesforceObject function. You need to check that you have the permission to update data on Leads on your Sales/Service Cloud org.
Also, you need to take a look at validation rules (if there are any) on OptInEmail__c and OptInSMS__c fields.
And since you are using a hardcoded lead's id, I assume the lead exists. However, I would recommend checking if the lead exists before calling UpdateSingleSalesforceObject.
You can use something like:
SET @LookUpLeads = RetrieveSalesforceObjects('Lead', 'Id', 'Id', '=', '00Q9E000005akYkUAI')
 IF RowCount(@LookUpLeads) > 0 then
  UpdateSingleSalesforceObject("Lead",@Id,"OptInEmail__c", 'false',"OptInSMS__c", 'false')
ENDIF


text:
Q: How to retrieve cookies in express via browser? I've been trying to figure this out for 2 days now, but to no avail.  I'm using cookie-parser and have followed the code of other people but it's still not working. It works perfectly in postman, but not on the browser. The browser I'm currently using is google chrome, but I've also tested it on microsoft edge which gives the same result.
app.get('/testCookie',(req,res) => {
    res.cookie('username','flavio');
    res.json({message:req.cookies});
})

// frontend
 const data = await axios.get('http://localhost:5000/testCookie');
 console.log(data); // returns {}

A: Asper, I understand you want to set cookies and access it in the client-side, then this might help you.
Server-side
 const cookieConfig = {
 httpOnly: false,
 maxAge: 315569260000,//age of cookie any value possible
 }

 app.get('/testCookie',(req,res) => {
  res.cookie('username','flavio',cookieConfig);
 })

Client side
 let data = document.cookie
            .split('; ')
            .find(row => row.startsWith('username'))
            .split('=')[1];
 console.log(data)


text:
Q: How does PHP determine the character encoding in browser POST request data? When the browser sends data in the body of a POST request (i.e. the name=value pairs from form elements), how does PHP determine the character encoding so it can properly decode the bit stream into characters for its own internal usage?
I can understand for some tasks where PHP won't need to decode, e.g. for SQL INSERT queries, it may simply pass the data/string along to the DBMS with no additional processing.
But for text processing/regex operations, I imagine PHP will need to decode the bit stream into characters, before it can perform test, pattern matches etc on them.
Also, it seems that because the encoding is determined by the browser, PHP will need guidance from the browser on what charset it used to encode the  POST data.
Expecting this guidance would be in the request headers, I set up a text form with
<meta charset="utf-8">

in the head of the webpage containing the form, then after entering some values and submitting the form, the request headers contains no obvious information about how it encoded the POST data
POST /experiments/foo.php HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 57
Pragma: no-cache
Cache-Control: no-cache
Origin: http://localhost
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Referer: http://localhost/experiments/how_does_php_encode_data_it_receives_from_browser.php
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6

Or is there something else going on? e.g. is the browser expected to encode characters to some pre-determined standard?
How does PHP know how to decode data it receives from the browser POST requests?

A: In regard to GET data, the W3C standard states

Note. The "get" method restricts form data set values to ASCII characters.
  Only the "post" method (with enctype="multipart/form-data") is specified to cover the entire [ISO10646] character set.

So with GET the browser seems to be locked into ASCII, if the form element has the attribute enctype="multipart/form-data" it seems the standard supports the larger charset [ISO10646].
And I guess because it is closer to a pure bitstream, the default Content-type of application/x-www-form-url-encoded supports all character encodings. in particular this article states:
http://www.herongyang.com/PHP/Non-ASCII-Form-Basic-Rules.html

URL encoding converts all non ASCII bytes in the form of "%xx", "xx" is the HEX value of the byte.

So this seems to explain what charsets the browser can possibly send, but not how it instructs PHP as to what actual charset it sent. (with the exception of GET, which PHP will know can only be ASCII).  O
Other wise from what I can understand there is essentially no direct guidance from the browser as to the character encoding of the form data it's sending.
I could be wrong though and would be interested in any feedback/alternatives to this theory.
Otherwise, from what I can tell the integrity of the scheme essentially relies on the server simply "remembering" what
<meta charset="utf-8">

or
<form ... accept-charset="utf-8">

values it was sending to users (and hoping users didn't change the character encoding via browser "settings") and expecting that the browser will faithfully send subsequent requests in that charset.
So in other words, if you had a web designer on your team responsible for HTML and they set the HTML meta tag <meta charset="utf-8"> they would need to inform the database admin, hey, you need to set up your database schema,  tables etc to expect UTF-8 encoding.
This is because the server side devs/DBA's won't be able to dynamically check for the encoding (e.g. if a form submission came from a user in a different country, whose browser may be set to some different charset).
and potentially reject or log a warning etc...
Basically it seems the devs need to explicitly set charset for every HTML page containing forms, e.g. with <meta charset="utf-8"> and then just trust that the browser will send the POST data in the same charset that the HTML containing the form was encoded in.
Further reading

*

*https://www.w3.org/TR/html401/interact/forms.html

*UTF-8 all the way through

*http://www.herongyang.com/PHP/Non-ASCII-Form-Basic-Rules.html

A: From PHP.net - Description of core php.ini directives:

default_charset string
In PHP 5.6 onwards, "UTF-8" is the default value and its value is used as the default character encoding for htmlentities(), html_entity_decode() and htmlspecialchars() if the encoding parameter is omitted. The value of default_charset will also be used to set the default character set for iconv functions if the iconv.input_encoding, iconv.output_encoding and iconv.internal_encoding configuration options are unset, and for mbstring functions if the mbstring.http_input mbstring.http_output mbstring.internal_encoding configuration option is unset.
All versions of PHP will use this value as the charset within the default Content-Type header sent by PHP if the header isn't overridden by a call to header().

Example:
Content-Type: text/html; charset=UTF-8

The <meta charset="utf-8"> tag is only useful on responses that don't have this header. But because the content-type header has higher precedence than the meta tag, and PHP always adds this header, the value of the mega tag charset attribute is ignored.
When you submit a form with method=POST (or GET) it URL encodes the name-value pairs in the declared charset and adds them to the body of the POST request. Then PHP decodes them again and adds them to the $_POST array still in the declared charset. (Usually this will be UTF-8.)
PHP's internal functions work based of the settings in php.ini. For example if default_charset is set to UTF-8, then functions like htmlspecialchars will return an empty string if it is passed a string containing any invalid UTF-8 byte sequences. From PHP.net:

Return Values
The converted string
If the input string contains an invalid code unit sequence within the given encoding an empty string will be returned, unless either the ENT_IGNORE or ENT_SUBSTITUTE flags are set.


text:
Q: Why is my program only returning an initial and not the word in Python? I am trying to write a program that requests a three-
part name and then displays the middle
name.
Repex:
fullname = str(input('Enter a 3-part name:'))
Roger Dupont Federer
print('Middle name:', fullname[1]
Output: R

However, I want to extract Dupont. What is wrong with my code?
)

A: Use split():
print(input('Enter a 3-part name:').split(' ')[1])

when you do fullname[1] you're indexing the second character not the second word


text:
Q: Symfony 3 Unique constraint error I am getting the following error while adding a UniqueEntity constraint on the email field of my User entity.

Attempted to load class "Unique" from namespace
  "\Symfony\Component\Validator\Constraints". Did you forget a "use"
  statement for another namespace?

If I remove the validation the error disappears. The contents of my validation.yml file are as followed.
LB\CoreBundle\Entity\User:
constraints:
    - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
            fields: [email]
            groups: [registration,userEdit]

I have tried importing the validation constraint in my User.php file but the error still persists. Any help to get rid of this error is greatly appreciated.

A: use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity
 * @ORM\Table(name="cab_fos_user")
 * @ORM\HasLifecycleCallbacks()
 * @UniqueEntity("email")
 * @ExclusionPolicy("all")
 * @Vich\Uploadable
 */
class User extends BaseUser


text:
Q: Date format YYYY-MM-DD not working in Safari I have this problem with Safari not recognizing the date format 2012-01-03 (being 2012 January 3rd). I have the dates within an array and then I want to convert them to this format - Tuesday Jan 3
Works in Chrome, but Safari is throwing undefined undefined NaN.
Some code below...
(function() {
    var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
        months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
    Date.prototype.getDayName = function() {
        return days[this.getDay()];
    };
    Date.prototype.getMonthName = function() {
        return months[this.getMonth()];
    };
})();

var issues = ['2012-01-03', '2012-01-02', '2012-01-01', '2011-12-31'];

for (var i = 0; i < issues.length; i++) {
      var d = new Date(issues[i]);
      var date = d.getDate(),
      weekday = d.getDayName(),
      month = d.getMonthName();
      day = weekday + ' ' + month + ' ' + date;
      $('.datepicker').find('ul').append('
' + day + '
');
}

I only need this to work for Safari/Mobile Safari, so prefer not to use any js library.

A: Simple debugging shows you the error:
var d = new Date(issues[i]);
console.log(d);

It does not like the date format. You can change it something like this:
var issues = ['01/03/2012', '01/02/2012', '01/01/2011', '12/31/2011'];

or you can do a split and do it in a format all browsers support
var dateParts = issues[i].split(/-/);
var d = new Date(dateParts[0],parseInt( dateParts[1], 10) -1,dateParts[2]);

http://jsfiddle.net/TveJU/

A: Date parsing in the various browsers is notoriously inconsistent and finicky.  I've always used Datejs (http://www.datejs.com/), a nice little js library that augments the built-in Date object.  Check it out.


text:
Q: Functional inverse of $z=1+w+\cdots+w^{n-1}$ Migrated to MO.

I am interested in the functional inverse of
$$
z=1+w+\cdots+w^{n-1},\quad w\geq0,\ n>1.
$$
This function is strictly increasing on $w\geq0$ and thus admits an inverse.

My attempt:
By Lagrange's theorem we may write the inverse:
$$
w(z)=a+\sum _{k=1}^\infty g_k\frac{(z-f(a))^k}{k!},
$$
with $f(w)=1+w+\cdots+w^{n-1}$ and
$$
g_k=\lim_{w\to a}\partial_w^{k-1}\left({\frac {w-a}{f(w)-f(a)}}\right)^k.
$$
Expanding $f(w)$ around $w=1$ gives $f(w)=nF(1,1-n;2;1-w)$, which is a hypergeometric function. Choosing $a=1$ we write
$$
\frac{f(w)-f(1)}{w-1}=-n\frac{F(1,1-n,2,1-w)-1}{1-w}=\frac{n(n-1)}{2}F(1,2-n;3;1-w).
$$
It follows
$$
w(z)=1+\sum _{k=1}^\infty a_k\frac{2^k}{n^k(n-1)^k}\frac{(z-n)^k}{k!},
$$
with
$$
a_k=\lim_{w\to 1}\partial_w^{k-1}\left(F(1,2-n;3;1-w)\right)^{-k}.
$$
Evaluating the limit for $a_k$ is certainly non-trivial. One thought was to use the Faà di Bruno formula but I am a little unclear on the details of this calculation and am curious if $a_k$ can be written in a "nice" form that does not involve Bell polynomials. Could someone please fill me in on the details of computing the $a_k$'s? Also, for which values of $z$ does this series converge?
I was able to write a quick one line code in Mathematica to compute the $a_k$'s, which may lend itself to finding a pattern:
a[k_] := Limit[D[Hypergeometric2F1[1, 2 - n, c, 1 - w]^-k, {w, k - 1}], w -> 1] /. c -> 3

$a_1$, $a_2$, and $a_3$ seem to factor nicely while $a_4$ does not.

Edit:
Using Faà di Bruno's formula I was able to write down an explicit form for the $a_k$'s giving a final solution of
$$
\bbox[5px,border:2px solid #C0A000]{%
w(z)=1+\frac{2(z-n)}{n(n-1)}+\sum_{k=2}^\infty\sum_{\ell=1}^{k-1}(-k)^{(\ell)}B_{k-1,\ell}\left(\left\{(-1)^m\tfrac{m!(2-n)_m}{(3)_m}\right\}_{m=1}^{k-\ell}\right)\frac{\left(\frac{2(z-n)}{n(n-1)}\right)^k}{k!},%
}
$$
where $(s)^{(n)}=\Gamma(s+1)/\Gamma(s-n+1)$ is the falling factorial, $(s)_n=\Gamma(s+n)/\Gamma(s)$ is the Pochhammer symbol, and $B_{n,k}$ is the partial Bell polynomial. It is interesting to note that this result also works for the more general case $\{n\in\Bbb R:n>1\}$.
All that I am still curious about is the radius of convergence for this series which I believe is $|z-n|<n-1$.
Here is Mathematica code to compare the exact function $w(z)$ to approximation obtained by truncating its series expansion:
a[k_, n_] :=
 Sum[FactorialPower[-k, l] BellY[k - 1, l,
    Table[(-1)^m (m! Pochhammer[2 - n, m])/Pochhammer[3, m], {m, 1,
      k - l}]], {l, 1, k - 1}]
g[z_, n_, K_] :=
 1 + (2 (z - n))/(n (n - 1)) +
  Sum[a[k, n] ((2 (z - n))/(n (n - 1)))^k/k!, {k, 2, K}]
gAprx[z_, n_] :=
 Quiet[N[Solve[(1 - w^n)/(1 - w) - z == 0, w, PositiveReals][[1, 1,
     2]]]]
P[n_] := Manipulate[
  Plot[{gAprx[z, n], g[z, n, m]}, {z, 1, 2 n - 1}], {m, 2, 20, 1}]
P[5]

A: Let $f:\mathbb C \to \mathbb C$ be the polynomial $\sum_{k=0}^{n-1} w^k$. We are interested in the radius of convergence of the power series of the inverse $w=f^{-1}(z)$ about $z=n$ corresponding to $w=1$. It is known that the radius of convergence of a power series represents the distance in the complex plane from the expansion point to the nearest singularity of the function expanded. Therefore, we have to locate the singularities of $f^{-1}$. The inverse of an entire function can have two types of singularities: $(1)$ algebraic singularities at the images of its saddle points $(2)$ transcendental singularities at its finite asymptotic values at infinity. There is no curve flowing to infinity along which a polynomial function tends to a finite value, hence the only singularities of our $f^{-1}$ will be algebraic singularities at the images of the saddle points of $f$. In formula, the singularities of $w=f^{-1}(z)$ are $z_k=f(w_k)$ where $w_k$ is one of the $n-2$ roots of the polynomial $f'(w)$. For the statement about the singularities of the inverse of an entire function, see Section 3, Appendix D in the book Lectures on the General Theory of Integral Functions by Georges Valiron.

A: Here is a solution based on the answer here which works as seen here when looking at the alternate forms section of the link. The derivation:
$$z=\sum_{k=0}^{n-1}w^k=\frac{w^n-1}{w-1}=a$$
so
$$w^n-1=a(w-1)=aw-a\implies w^n-aw+a-1=0$$
Remember the series definition of the Inverse of the Regularized Beta function where the series extends the domain of the function. It is also the quantile for a distribution using the Regularized Beta function:
$$\text I_z(a,b)=\frac{\int_0^z t^{a-1}(1-t)^{b-1}dt}{\text B(a,b)}=y\implies z=\text I^{-1}_y(a,b)$$
and using special cases of the Regularized Beta function:
$$\text I_{1-abw}(2,-n)=0\iff (c+1)a^n b^n w^n-abnw+n-1=0\implies w^n-\frac{abn}{a^n b^n (c+1)}w+\frac{n-1}{a^nb^n(c+1)}\mathop=^\text{set}w^n-aw+a-1=0$$
therefore:
$$c=n a^{-n}b^{1-n}-1:w^n-aw+\frac{n-1}{bn}$$
and
$$b=\frac{n-1}{(a-1)n}$$
Combining all of these identities, we put the problem in terms of the Regularized Beta Function:
$$w^n-aw+a-1=0\iff\text I_{1-\frac{a(n-1)}{(a-1)n}w}(2,-n)+\frac{(n-1)n^n (a-1)^{n-1}}{(a(n-1))^{n}}-1=0$$
Using the definition of the inverse and plugging in $w=0$:
$$a=\sum_{k=0}^{n-1}w^k=\frac{w^n-1}{w-1}\implies \boxed{w= -\frac{(a-1)n}{a(n-1)}\left(\text I^{-1}_{1-\left(\frac{a-1}{n-1}\right)^{n-1}\left(\frac na\right)^n}(2,-n)-1\right)}$$
where:
$$\boxed{\text I^{-1}_z(2,b)=\frac{2(b-1)z}{3b(b+1)}+\sqrt{\frac{2z}{b(b+1)}}+\frac{(b-1)(11b-2)\left(\frac z{b(b+1)}\right)^\frac32}{18\sqrt 2} +\frac{(b-1)(43b^2-5b-2)}{135b^2(b+1)^2}+… }$$
The function works for more general $a,w,n\in\Bbb R^+$,but here is the $a=5,n=7$ case:
$$w^7+…+1=5\iff w^7-5 w+ 4=0\implies w=.885128…= \frac{14}{15}-\frac{14}{15}\text I^{-1}_\frac{4246373}{56953125}(2,-7)$$
Using the $x$th partial sum and $y$=estimation, the above sum evaluates to:
$$(0,0.9333…)$$
$$(1,0.94217…)$$
$$(2,0.8865…)$$
$$(3,0.88482…)$$
$$(4,0.885197…)$$
Technically, $\text I^{-1}_z(a,b)$ is only defined for $a,b>0,0\le z\le1$, but the series extends the function's domain. This method is more experimental, but it still works. The goal of this answer is the closed form, not the approximation. Please correct me and give me feedback!
Here is a graphical demo of the solution.

A: Extended Comment:
For the case $n=2$, the radius of convergence for the inverse series $w(z)$ is infinite, which can be deduced from the fact that $a_k=0$ for all $k\geq 2$.
For $n=3,4,\dots$, the approach given by @Gary provides a means for finding the radius of convergence of the inverse series either exactly or numerically. Let $w_k$ represent any one of the $n-2$ solutions of $f^\prime(w)=0$. Evaluating the derivative of $f(w)=(1-w^n)/(1-w)$ and equating with zero we find
$$
\begin{align}
f^\prime(w_k)=0
&\implies(n-1)w_k^n-nw_k^{n-1}+1=0,\quad w_k\neq 1\\
&\implies w_k^n=\frac{w_k}{n-(n-1)w_k},\quad w\neq 1\\
\end{align}
$$
Substituting $w_k^n$ into $f$ then gives
$$
z_k:=f(w_k)=\frac{n}{n-(n-1)w_k}.
$$
Now, after a bit of algebra
$$
|z_k-n|=(n-1)\biggl|\left(1+\tfrac{w_k}{n(1-w_k)}\right)^{-1}\biggr|;
$$
thus, the radius of convergence for any $n$ can be found by computing the minimum $|z_k-n|$, that is
$$
r(n)=\min_{k\in\{1,\dots,n-2\}}(n-1)\biggl|\left(1+\tfrac{w_k}{n(1-w_k)}\right)^{-1}\biggr|.
$$
This can be implemented in Mathematica as
fprime[w_, n_] := (1 - w^n)/(1 - w)^2 - ((n w^(-1 + n))/(1 - w));
wk[n_] := Solve[fprime[w, n] == 0, w][[All, 1, 2]];
ROC[n_] :=
  ToRadicals[
   Min[FullSimplify[(n - 1) Abs[(1 + wk[n]/(n (1 - wk[n])))^-1]]]];

For $n=3,4,5$ we obtain exact solutions, namely,
$$
\begin{align}
n=3: &|z-3|<\frac{9}{4}\\
n=4: &|z-4|<4\sqrt{\frac{2}{3}}\\
n=5: &|z-5|<\frac{5}{8 \sqrt{\frac{3}{140-5\ 2^{2/3} \sqrt[3]{\frac{5}{3 \sqrt{6}-2}}+5^{2/3} \sqrt[3]{2
   \left(3 \sqrt{6}-2\right)}}}}\\
\end{align}
$$
Mathematica is not able to find closed forms for larger values of $n$; however, we can compute the radius of convergence numerically with the modified code
fprime[w_, n_] := (1 - w^n)/(1 - w)^2 - ((n w^(-1 + n))/(1 - w));
wk[n_] := NSolve[fprime[w, n] == 0, w][[All, 1, 2]];
ROC[n_] :=
  Min[FullSimplify[(n - 1) Abs[(1 + wk[n]/(n (1 - wk[n])))^-1]]];

This code also works for noninteger values of $n$, e.g.
ROC[10.7]=9.75823


text:
Q: Design question? I am building music app, where user can do several tasks including but not limited to listening song, like song, recommend song to a friend and extra.
currently I have this model:
class Activity(models.Model):
    activity = models.TextField()
    user = models.ForeignKey(User)
    date = models.DateTimeField(auto_now=True)

so far I thought about two solutions.
1. saving a string to database. e.g "you listened song xyz".
2. create a dictionary about the activity and save to the database using pickle or json.
e.g.
dict_ = {"activity_type":"listening", "song":song_obj}

I am leaning to the second implementation, but not quite sure.
so what do you think about those two methods? do you know better way to achieve the goal?

A: Looks like all you need is an enumeration to match a table in your database.
So in your UserActivity table, you will have
userid, activityid, songid, datetime etc etc

A: What about GenericForeignKey? You could have userid, activityid and content_object on your UserActivity where content_object is a song, an user or something completely different.
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')


text:
Q: How to change color bar to be non linear, whilst data is displayed normally? I would like to achieve similar results to this:
Data=magic(100);
c=[1 10/3 10 100/3 100 1000/3 1000 10000/3 10000];
contourf(log(Data(:,:)),log(c));
colormap(bone);  %Color palate named "bone"
caxis(log([c(1) c(length(c))]));
colorbar('FontSize',11,'YTick',log(c),'YTickLabel',c);

With the results here:

Except, I want to instead plot pcolor(x,y,z), where x, y, z are 3 matrices of 1000-by-90. I want the data in x, y, z to not be logarithmic, instead I want values that are not seen well to be easier to see. See image below for example of data:

I would like to see more the variability above the yellow layer at the bottom between 13-16.
So I tried the code for MATLAB 2012b (I managed to get it remotely) and tried the code below given by the first answer:
figure;
ax1=subplot(2,1,2)
hp = pcolor(x,y,z);
shading flat
cdat = get(hp,'cdata');
hc = colorbar;
set(hc,'yscale','log','ytick',logspace(log10(min(cdat(:))),log10(max(cdat(:))),11));

But I obtained the same plot with different colorbar tick marks...

A: Just set the yscale property of the colorbar from 'linear' to 'log'. You'll have to adjust the tick positions manually.
HG1 version, i.e. for older versions of MATLAB:
n = 10;
[x,y] = meshgrid(1:n);
z = 1000*rand(n);

figure;
hp = pcolor(x,y,z);
cdat = get(hp,'cdata');
hc = colorbar;
set(hc,'yscale','log','ytick',logspace(log10(min(cdat(:))),log10(max(cdat(:))),11));

You'd still need to set the colorbar tick positions to prettier, manual values:

Unfortunately, I couldn't get a HG2-compliant solution to work. The problem is that while hc.Ticks is still present, I can't find a reference in the documentation to any properties relating to the linear/logarithmic scale of the colorbar. I'll update if I find a solution.


text:
Q: only single selection in CListCtrl Checkbox in MFC In a MFC dialog, I have used a CListCtrl with checkbox. I want to disable multi checkbox selection , so that user can only select a single checkbox at a time. What is the best way to achieve this.I have done this
    void SomeClass::OnClickList(NMHDR *pNMHDR, LRESULT *pResult)
    {
        LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);

        int nSelectedItemIndex = -1;
        nSelectedItemIndex = m_ListCtrl.GetNextItem(-1, LVNI_SELECTED);
        int nCount = m_ListCtrl.GetItemCount();
        for(int nItem = 0; nItem < nCount; nItem++)
        {
            m_ListCtrl.SetCheck(nItem,false);
        }
        if(nSelectedItemIndex != -1)
            m_ListCtrl.SetCheck(nSelectedItemIndex,true);

        *pResult = 0;
    }

Somehow I think this method is not so proper and can be made better in other way. All suggesions are welcomed.
EDIT: UPDATE: after writing the code , everything is working but I am facing a new problem.
calling SetCheck() function inside OnItemChanged message handler function, it is calling the same function again, creating a recursion.Thus selection change is somehow slow. How to avoid this.Please help. ????

A: Finally I have solved it . Now the checkbox and selection works at par. selecting checkbox selects the row and vice versa and one selection is possible. the code:
    void SomeClass::ResetAllCheckBox()
    {
        int nCount = m_ListCtrl.GetItemCount();
        for(int nItem = 0; nItem < nCount; nItem++)
        {
            m_ListCtrl.SetCheck(nItem,false);
        }

    }

    //Handler for ON_NOTIFY(NM_CLICK,...)
    void SomeClass::OnClickList(NMHDR *pNMHDR, LRESULT *pResult)
    {
        LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
        NMLISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
        LVHITTESTINFO hitinfo;
        int nPosCB=-1,nPos=-1;
        hitinfo.pt = pNMListView->ptAction;

        //Make the hit test...
        nPosCB = m_ListCtrl.HitTest(&hitinfo);

        if(hitinfo.flags != LVHT_ONITEMSTATEICON)
            return;
        ResetAllCheckBox();

        nPos = m_ListCtrl.GetNextItem(-1,LVNI_SELECTED);
        m_ListCtrl.SetItemState(nPos, ~LVIS_SELECTED, LVIS_SELECTED);
        m_ListCtrl.SetItemState(nPosCB, LVIS_SELECTED, LVIS_SELECTED);
        m_ListCtrl.SetSelectionMark(nPosCB);
        *pResult = 0;
    }

    //Handler for ON_NOTIFY(LVN_ITEMCHANGED,...)
    void SomeClass::OnItemchangedList(NMHDR *pNMHDR, LRESULT *pResult)
    {
        LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
        int nPos = -1;

        ResetAllCheckBox();

        nPos = m_ListCtrl.GetNextItem(-1,LVNI_SELECTED);
        if(nPos != -1)
            m_ListCtrl.SetCheck(nPos);

        int nCount = m_ListCtrl.GetItemCount();
        int nSelectedItemIndex = -1;
        for(int nItem = 0; nItem < nCount; nItem++)
        {
            if(m_ListCtrl.GetCheck(nItem)== 1)
                nSelectedItemIndex = nItem;
        }

        *pResult = 0;
    }

A: When creating the control make sure this style is used LVS_SINGLESEL.
It is passed in the CreateEx/CreateEx function. Also available from the resource editor (if control is added through it).

A: I found a shorter solution. The idea is to detect if the user checked a checkbox. If it is the case, unchecked all the other checboxes, otherwise do nothing. Contrary to the answer by @egur, this solution does not check the checkbox upon selection of the row.
static void DisableAllItemsExcept(CListCtrl& ctrl, int indexToKeepChecked)
{
    for (int nItem = 0; nItem < ctrl.GetItemCount(); nItem++)
        if (nItem != indexToKeepChecked)
            ctrl.SetCheck(nItem, FALSE);
}

//in begin message map
//ON_NOTIFY(LVN_ITEMCHANGED, IDC_SC_LIST, &CMyDlg::OnLvnItemchangedScList)

void CMyDlg::OnLvnItemchangedScList(NMHDR *pNMHDR, LRESULT *pResult)
{
    LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);

    //detect if we checked a new element
    if ( (pNMLV->uChanged & LVIF_STATE) && (pNMLV->uNewState & 0x2000) && (pNMLV->uOldState & 0x1000) )
        DisableAllItemsExcept(m_lcList, pNMLV->iItem);

    *pResult = 0;
}

The detection of state change was based on the following article : Get the notification code from Listview Control checkboxes. The values 0x1000 and 0x2000 do not seems to be defined anywhere in the header file, so maybe I'm using an undocumented feature.


text:
Q: onClick Event Using react-bootstrap nav dropdown and react-router-dom not working I have the following Navbar using react-bootstrap. The second brand is always the one that is active, as if the dropdown is consistently clicked on the last item in the chain (in this case Tommy Hilfiger). I need to have the brand set based on which item in the dropdown is clicked.
const [brand, setBrand] = useState("");

 const brandSet = (value) => {
    setBrand(value);
  };

<Navbar bg="light" expand="lg">

              <NavDropdown title="Brands" id="basic-nav-dropdown">
                <NavDropdown.Item href="/#/products">
                  All Products
                </NavDropdown.Item>
                <NavDropdown.Item
                  href="/#/products:PoloRalphLauren"
                  onClick={brandSet("Polo Ralph Lauren")}
                >
                  Polo Ralph Lauren
                </NavDropdown.Item>
                <NavDropdown.Item
                  href="/#/products:TommyHilfiger"
                  onClick={brandSet("Tommy Hilfiger")}
                >
                  Tommy Hilfiger
                </NavDropdown.Item>

A: Because you are calling that function instead of passing the function to onClick, change that line to this:
        <NavDropdown.Item
             href="/#/products:PoloRalphLauren"
             onClick={() => brandSet("Polo Ralph Lauren")}
         >
            Polo Ralph Lauren
        </NavDropdown.Item>

=> called Arrow Function, which was introduced in ES6, and will be supported on React 0.13.3 or upper.


text:
Q: Whats wrong with my delete core object method? I have a method that is called in the app delegate by the UIViewControllers which deletes the core object that matches the selected objects name.  It deletes from the UIListView which is correct and the refresh method (which checks core data for all objects)doesn't bring it back to the list view.  However, when I close the application and restart it it brings back the just deleted objects.  Here is the method:
-(void)deleteObject:(NSString *)configName
{
    //Generates the request context for core data
    NSManagedObjectContext *context = [self managedObjectContext];
    NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"StoredSetups" inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    [request setEntity:entityDesc];
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"(config_name = %@)", configName];
    [request setPredicate:pred];
    NSManagedObject *matches = nil;
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request error:&error];

    if (objects.count == 0)
    {
        NSLog(@"No Matches");
    }
    else
    {
        matches = objects[0];
        [context deleteObject:matches];
    }
}

Any help or feed back will be greatly appreciated.  Thanks in advance!

A: you have to save the context after delete like this :
if (objects.count == 0)
    {
        NSLog(@"No Matches");
    }
    else
    {
        matches = objects[0];
        [context deleteObject:matches];
        [context save:&error];
    }


text:
Q: Problem in fetching data from multiple collections using lookup in Mongoose Currently I have three Collection "User" , "UserLocation" & "UserAddress" which are related with each other.
Below are the Schema
UserModel
var userTable = new Schema({
  name: String,
  email : String
});

module.exports = mongoose.model('user', userTable );

UserLocationModel
var userLocationTable = new Schema({
  location : String,
  user_id :{
    type : ObjectId,
    ref : 'user',
  }
});

module.exports = mongoose.model('userLocation',userLocationTable);

UserAddressModel
var userAddressTable = new Schema({
    userLocationID : {
      type : ObjectID,
      ref : 'userLocation',
    },
   address : String
});

module.exports = mongoose.model('userAddress',userAddressTable);

My Code
UserModel.aggregate([
        {
            "$lookup": {
                "from": "userlocations",
                "localField": "_id",
                "foreignField": "user_id",
                "as": "location"
            }
        },
        {
            "$unwind" : "$location"
        },
        {
            "$lookup": {
                "from": "useraddresses",
                "localField": "location._id",
                "foreignField": "userLocationID",
                "as": "location.address"
            }
        },
    ]).exec((err, data) => {
        if (err) throw err;
        res.send(data);
    })

Current Output
[
{
    "_id": "5d8b1e6ca4d1ab5e54f1b8ee",
    "name": "Shivam",
    "email": "ee@gmail.com",
    "__v": 0,
    "location": {
        "_id": "5d8b1e6ca4d1ab5e54f1b8ef",
        "location": "Mumbai",
        "user_id": "5d8b1e6ca4d1ab5e54f1b8ee",
        "__v": 0,
        "address": []
    }
},
{
    "_id": "5d8b3a740b6fee55ac39a61d",
    "name": "ameet",
    "email": "ddt@gmail.com",
    "__v": 0,
    "location": {
        "_id": "5d8b3a740b6fee55ac39a61e",
        "location": "sion",
        "user_id": "5d8b3a740b6fee55ac39a61d",
        "__v": 0,
        "address": []
    }
}
]

Here the problem is I am not able to fetch the data from UserAddress Model. I have tried all the possible ways but unable to fetch the data from UserAddress Collection. Can someone help me in this?


text:
Q: Basic - Understanding PHP object from Doctrine query I'm trying to work out how to handle the object this returns:
$data = $this->getDoctrine()->getRepository('MyBundle:EntityName')->findAll();

I know I can pass it to Twig and use it that way, but I need to do further PHP code on it.
I suppose this is a general PHP question in dealing with objects.
Using serialise($data) returns so much info I don't know what to do with it.
I suppose I need to know something like this:
//to get record 1 / field 1
$data[1]['field1']

...but of course that doesn't work.

A: I don't think you need to serialize it, I think that would make it harder to work with.  Since Doctrine knows the type/class of entity your retrieved, its returned them as instances and you can interact with them normally.
An example based on your question:
lets say you want the record 1 - field 1 value, and this entity you searched for was structured something like this making field 1 the id:
Class Person {
    private $id;
    private $someValue;

    public function getId()
    {
        return $this->id;
    }
    public function setSomething($value)
    {
        $this->someValue = $value;
    }
}

You could do as Kris stated and use $data[0]->getId()
You can access any field you had getters and setters for (or was public)
If as you said you needed to perform some modifications to these retrieved objects, remember that $data is just an array objects/entities. You could do something like this:
foreach($data as $object)
{
    $object->setSomething($something);
}

I thinks it's definitely better to use them as objects


text:
Q: constructor on type not found error in PrivateObject I'm writing a unit test for calculation software.in test case i used of "PrivateObject" for accessing to private method"sendNumberToCalculation()" , but i get error constructor on type not found.
    public class CalculationTest
{
    [TestMethod]
    public void sendNumberToCalculationTest()
    {

        // -- Act
        PrivateObject obj = new PrivateObject(typeof(Calculation));
        Tokenization token = new Tokenization("5*10-18/(3+19)");
        PolishNotation polish = new PolishNotation(token.MathExpressionParser());

        double expected = 49.19;

        // -- Actual
        double actual = Convert.ToDouble(obj.Invoke("sendNumberToCalculation", polish));

        // -- Assert
        Assert.AreEqual(expected, actual);
    }
}

    public class Calculation
{

    private Tokenization token;

    private PolishNotation polish;
    private Stack<double> numbers = new Stack<double>();
    private Stack<string> operators = new Stack<string>();

    public Calculation(string expression)
    {
        token = new Tokenization(expression);
        polish = new PolishNotation(token.MathExpressionParser());
    }

    private double sendNumberToCalculation()
    {
        int number;
        int number1 = 0;
        int number2 = 0;
        string operatorName = "";
        int counter = 1;
        foreach (var item in polish.InfixToPostfix())
        {
            numbers.Push(Convert.ToDouble(item));
            if (!int.TryParse(item, out number))
            {
                operators.Push(item);
                while (counter <= 2 && numbers.Count > 1)
                {
                    if (counter == 1)
                    {
                        number2 = Convert.ToInt32(numbers.Pop());
                    }
                    else if (counter == 2 && operators.Count > 0)
                    {
                        number1 = Convert.ToInt32(numbers.Pop());
                        operatorName = operators.Pop();
                    }
                }
            }
            operatorDetect(number1, number2, operatorName);
        }
        var result = numbers.Pop();

        return result;
    }

    private void operatorDetect(int number1, int number2, string operatorName)
    {
        switch (operatorName)
        {
            case "+":
                Add(number1, number2);
                break;

            case "*":
                Multipy(number1, number2);
                break;

            case "/":
                Divide(number1, number2);
                break;

            case "-":
                Subtract(number1, number2);
                break;
        }
    }

    private void Add(int number1, int number2)
    {
        double number = number1 + number2;
        numbers.Push(number);
    }

    private void Multipy(int number1, int number2)
    {
        double number = number1 * number2;
        numbers.Push(number);
    }

    private void Subtract(int number1, int number2)
    {
        double number = number1 / number2;
        numbers.Push(number);
    }

    private void Divide(int number1, int number2)
    {
        double number = number1 - number2;
        numbers.Push(number);
    }
}

A: Calculation class does not contain a parameterless constructor. to pass the constructor parameters to the PrivateObject constructor:
string expression = "5*10-18/(3+19)";

PrivateObject obj = new PrivateObject(
    typeof(Calculation),      // The type of the object to create
    new[] { typeof(string) }, // The type of each parameter
    new[] { expression });    // The value for each parameter

to invoke the sendNumberToCalculation method with one parameter of the PolishNotation type, but that method doesn't have any parameters. to remove the second argument from the Invoke call:
double actual = Convert.ToDouble(obj.Invoke("sendNumberToCalculation"));

A: There is an easier way to achieve this, simply create the object first and then call the PrivateObject constructor that takes an object instead of a type.


text:
Q: Symfony/Doctrine - QueryException - [Semantical Error] line 0, col 48 near 'pizza-mia': Error: 'pizza' is not defined I want to make this query in SQLite using DQL
//// src/Repository/PostRepository.php
public function hasPreviousPost($id,$slug): array
{

    $em = $this->getEntityManager();

    $query = $em->createQuery('SELECT p FROM App\Entity\Post p WHERE p.id < '.$id.' AND p.slug = '.$slug);
    $posts = $query->getResult();

    return $posts;
}

And I call this function from the PostController like that
//// src/Controller/PostController.php
        $posts = $this->getDoctrine()->getRepository(Post::class)->findAll();

        foreach ($posts as $post){

        $hasPreviousPost = $this->getDoctrine()->getRepository(Post::class)->hasPreviousPost($post->id(),$post->Slug());
        }

But when I run the code, I get this error
" [Semantical Error] line 0, col 48 near 'pizza-mia': Error: 'pizza' is not defined. "
pizza-mia is what $slug contains, a string.
This is my Post entity.
    <?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

$countPosts = 0;

/**
 * @ORM\Entity(repositoryClass="App\Repository\PostRepository")
 * @ORM\Table(name="post")
 */
class Post
{

/**
 * @ORM\Column(type="integer")
 * @ORM\Column(unique=true)
 */
private $id;

/**
 * @ORM\Id
 * @ORM\Column(type="text")
 * @ORM\Column(unique=true)
 */
private $postId;

/**
 * @ORM\Column(type="text")
 */
private $slug;

/**
 * @ORM\Column(type="text")
 */
private $message;

/**
 * @ORM\Column(type="boolean",nullable=true)
 */
private $isScheduled;

/**
 * @ORM\Column(type="integer")
 */
private $scheduledPublishTime;

function __construct($postId,$slug,$message)
{
    global $countPosts;
    $countPosts++;
    $this->postId=$postId;
    $this->id=$countPosts;
    $this->slug=$slug;
    $this->message=$message;
    $this->isScheduled=false;
    $this->scheduledPublishTime=0;
}

public function PostId(): ?string
{
    return $this->postId;
}

public function id(): ?int
{
    return $this->id;
}

public function Slug(): ?string
{
    return $this->slug;
}

public function Message(): ?string
{
    return $this->message;
}

public function IsScheduled(): ?bool
{
    return $this->isScheduled;
}

public function changeIsScheduled(?bool $isScheduled): self
{
    $this->isScheduled = $isScheduled;

    return $this;
}

public function ScheduledPublishTime(): ?int
{
    return $this->scheduledPublishTime;
}

public function changeScheduledPublishTime(int $scheduledPublishTime): self
{
    $this->scheduledPublishTime = $scheduledPublishTime;

    return $this;
}
}

Any help will be appreciated.

A: Try it this way.
$query = $em->createQuery('SELECT p FROM App\Entity\Post p WHERE p.id < :id AND p.slug = :slug');
$query->setParameter('id', $id);
$query->setParameter('slug', $slug);

:id and :slug stand for a named parameter
My strong assumption is that you simply are missing the ' ' to have your $slug defined as string in your query.
But using parameters like above makes it more readable as well.
Find an explanation about named or numbered parameters in the documentation