问:
Loading 4-channel texture data in iOS
I want to load 4-channel texture data from a file in iOS, so I consider the texture as a (continuous) map

```<code>[0,1]x[0,1] -> [0,1]x[0,1]x[0,1]x[0,1]
</code>```

If I use the fileformat .png, XCode/iOS consider the file as an image, and so multiplies each component rgb with a (premultiplied alpha), corrupting my data. How should I solve this? Examples may be

use two textures with components rgb (3-channel)

postdivide alpha

use another file format

Of these, I consider the best solution to be to use another file format. The GL-compressed file format (PVRTC?) is not Apple-platform independent and seems to be of low resolution (4 bits) (reference).

EDIT:
If my own answer below is true, it is not possible to get the 4 channel data of png's in iOS. Since OpenGL is about creating images rather than presenting images, it should be possible to load 4-channel data in some way. png is a fileformat for images (and compression depends on all 4 channels but compression of one channel is independent of the other channels), so one may argue that I should use another file format. So which other compressed file formats should I use, which is easy to read/integrated in iOS?

UPDATE: "combinatorial" mentioned a way to load 4-channel non-premultiplied textures, so I had to give him the correct answer. However, that solution had some restrictions I didn't like. My next question is then "Access raw 4-channel data from png files in iOS" :)

I think it is a bad library design not making it possible to read 4 channel png data. I don't like systems trying to be smarter than myself.

答:
There is better solution, faster(about 3x~5x) and cross platform</p>

```<code>    #define STB_IMAGE_IMPLEMENTATION
    #include "stb_image.h"

    // force 4 channel rgba, force flipy

    // image: first pixel is top left, OpenGL assume first is bottom left, so need flipy
    bool flipy = true;
    int width, height, nrChannels;
    stbi_set_flip_vertically_on_load(flipy);

    unsigned char *imageData = stbi_load(path.c_str(), &width, &height, &nrChannels, 4);

    // load data to your texture
    // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, bytes);

    free(imageData);
</code>```

Title: Loading 4-channel texture data in iOS

Body:
I want to load 4-channel texture data from a file in iOS, so I consider the texture as a (continuous) map

[0,1]x[0,1] -> [0,1]x[0,1]x[0,1]x[0,1]

If I use the fileformat .png, XCode/iOS consider the file as an image, and so multiplies each component rgb with a (premultiplied alpha), corrupting my data. How should I solve this? Examples may be

use two textures with components rgb (3-channel)

postdivide alpha

use another file format

Of these, I consider the best solution to be to use another file format. The GL-compressed file format (PVRTC?) is not Apple-platform independent and seems to be of low resolution (4 bits) (reference).

EDIT:
If my own answer below is true, it is not possible to get the 4 channel data of png's in iOS. Since OpenGL is about creating images rather than presenting images, it should be possible to load 4-channel data in some way. png is a fileformat for images (and compression depends on all 4 channels but compression of one channel is independent of the other channels), so one may argue that I should use another file format. So which other compressed file formats should I use, which is easy to read/integrated in iOS?

UPDATE: "combinatorial" mentioned a way to load 4-channel non-premultiplied textures, so I had to give him the correct answer. However, that solution had some restrictions I didn't like. My next question is then "Access raw 4-channel data from png files in iOS" :)

I think it is a bad library design not making it possible to read 4 channel png data. I don't like systems trying to be smarter than myself.

Body:
There is better solution, faster(about 3x~5x) and cross platform

    #define STB_IMAGE_IMPLEMENTATION
    #include "stb_image.h"

    // force 4 channel rgba, force flipy

    // image: first pixel is top left, OpenGL assume first is bottom left, so need flipy
    bool flipy = true;
    int width, height, nrChannels;
    stbi_set_flip_vertically_on_load(flipy);

    unsigned char *imageData = stbi_load(path.c_str(), &width, &height, &nrChannels, 4);

    // load data to your texture
    // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, bytes);

    free(imageData);


来源: stackexchange

问:
Mongoose, Matching a field of string array type with a given string array
Suppose there is a Schema and there is a field

```<code> phoneNumber:{
    type:[String],
    required:true
},
</code>```

now i want to compare this column with an array , example ["ABC","DEF"]. How can i check if any element in this array matches with an element in a document

```<code>Like if there are documents A =  { phoneNumber :["ACD, "BFG"]} and B= {phoneNumber:["GCD"]}
</code>```

The query should return the B document if i check using C= ["GCD"], as B is the only document that contains "GCD" element.
I did try to use myDoc.find({phoneNumber:{$in:["GCD"]}) but it isnt returning anything. What is the correct query which is to be used

答:
Use $in:</p>
```<code>db.collection.find({"phoneNumber.type": { $in: ["ACD", "BFG"] } })
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Suppose there is a Schema and there is a field

 phoneNumber:{
    type:[String],
    required:true
},

now i want to compare this column with an array , example ["ABC","DEF"]. How can i check if any element in this array matches with an element in a document

Like if there are documents A =  { phoneNumber :["ACD, "BFG"]} and B= {phoneNumber:["GCD"]}

The query should return the B document if i check using C= ["GCD"], as B is the only document that contains "GCD" element.
I did try to use myDoc.find({phoneNumber:{$in:["GCD"]}) but it isnt returning anything. What is the correct query which is to be used

Body:
Use $in:

db.collection.find({"phoneNumber.type": { $in: ["ACD", "BFG"] } })


问:
Is my application exiting due to a memory leak or privacy violation?
I am developing a simple application, which requires a user to register to login to the application.  I am using firebase as my database.  The application loads as expected and displays correctly, yet as soon as I enter the required registration details instead of uploading the data to firebase and loading the login page the application crashes.

Looking at Logcat it appears I have a memory leak or I am in violation of privacy rules, however being relatively new to this I'm not entirely sure where I am going wrong.

```<code>import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class MainActivity extends AppCompatActivity {

    private EditText userEmail, userPassword;
    private Button register;
    private TextView login;
    private FirebaseAuth firebaseAuth;

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

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (validate()){
                    // Upload data to the database.

                    String user_email = userEmail.getText().toString().trim();
                    String user_password = userPassword.getText().toString().trim();

                    firebaseAuth.createUserWithEmailAndPassword(user_email, user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()){
                                Toast.makeText(MainActivity.this, "Registration Successful!", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(MainActivity.this, Login.class));
                            } else {
                                Toast.makeText(MainActivity.this, "Registration Failed!", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }

                login.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(MainActivity.this, Login.class));
                    }
                });
            }
        });
    }

    private void setupUiViews(){
        userEmail = (EditText) findViewById(R.id.etEmail);
        userPassword = (EditText) findViewById(R.id.etPassword);
        register = (Button) findViewById(R.id.btnRegister);
        login = (TextView) findViewById(R.id.tvRegistered);
    }

    private boolean validate(){
        boolean result = false;

        String email = userEmail.getText().toString();
        String password = userPassword.getText().toString();

        if (email.isEmpty() && password.isEmpty()){
            Toast.makeText(this, "Please enter all details", Toast.LENGTH_SHORT).show();
        } else {
            result = true;
        }

        return result;
    }
}
</code>```

As requested Logcat below:

```<code>2020-05-28 12:56:32.695 5462-5462/com.devops.ignite E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.devops.ignite, PID: 5462
    java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.tasks.Task com.google.firebase.auth.FirebaseAuth.createUserWithEmailAndPassword(java.lang.String, java.lang.String)' on a null object reference
        at com.shayledevops.ignite.MainActivity$1.onClick(MainActivity.java:42)
        at android.view.View.performClick(View.java:7125)
        at android.view.View.performClickInternal(View.java:7102)
        at android.view.View.access$3500(View.java:801)
        at android.view.View$PerformClick.run(View.java:27336)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
</code>```

答:
You forgot to initialize firebaseAuth before calling createUserWithEmailAndPassword on it.

Something likeL

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setupUiViews();

    firebaseAuth = FirebaseAuth.getInstance(); // this line is new

    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (validate()){
                // Upload data to the database.

                String user_email = userEmail.getText().toString().trim();
                String user_password = userPassword.getText().toString().trim();

                firebaseAuth.createUserWithEmailAndPassword(user_email, user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    ...
</code>```

Body:
I am developing a simple application, which requires a user to register to login to the application.  I am using firebase as my database.  The application loads as expected and displays correctly, yet as soon as I enter the required registration details instead of uploading the data to firebase and loading the login page the application crashes.

Looking at Logcat it appears I have a memory leak or I am in violation of privacy rules, however being relatively new to this I'm not entirely sure where I am going wrong.

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class MainActivity extends AppCompatActivity {

    private EditText userEmail, userPassword;
    private Button register;
    private TextView login;
    private FirebaseAuth firebaseAuth;

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

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (validate()){
                    // Upload data to the database.

                    String user_email = userEmail.getText().toString().trim();
                    String user_password = userPassword.getText().toString().trim();

                    firebaseAuth.createUserWithEmailAndPassword(user_email, user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()){
                                Toast.makeText(MainActivity.this, "Registration Successful!", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(MainActivity.this, Login.class));
                            } else {
                                Toast.makeText(MainActivity.this, "Registration Failed!", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }

                login.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(MainActivity.this, Login.class));
                    }
                });
            }
        });
    }

    private void setupUiViews(){
        userEmail = (EditText) findViewById(R.id.etEmail);
        userPassword = (EditText) findViewById(R.id.etPassword);
        register = (Button) findViewById(R.id.btnRegister);
        login = (TextView) findViewById(R.id.tvRegistered);
    }

    private boolean validate(){
        boolean result = false;

        String email = userEmail.getText().toString();
        String password = userPassword.getText().toString();

        if (email.isEmpty() && password.isEmpty()){
            Toast.makeText(this, "Please enter all details", Toast.LENGTH_SHORT).show();
        } else {
            result = true;
        }

        return result;
    }
}

As requested Logcat below:

2020-05-28 12:56:32.695 5462-5462/com.devops.ignite E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.devops.ignite, PID: 5462
    java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.tasks.Task com.google.firebase.auth.FirebaseAuth.createUserWithEmailAndPassword(java.lang.String, java.lang.String)' on a null object reference
        at com.shayledevops.ignite.MainActivity$1.onClick(MainActivity.java:42)
        at android.view.View.performClick(View.java:7125)
        at android.view.View.performClickInternal(View.java:7102)
        at android.view.View.access$3500(View.java:801)
        at android.view.View$PerformClick.run(View.java:27336)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

Body:
You forgot to initialize firebaseAuth before calling createUserWithEmailAndPassword on it.

Something likeL

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

    firebaseAuth = FirebaseAuth.getInstance(); // this line is new

    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (validate()){
                // Upload data to the database.

                String user_email = userEmail.getText().toString().trim();
                String user_password = userPassword.getText().toString().trim();

                firebaseAuth.createUserWithEmailAndPassword(user_email, user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    ...


问:
Nodejs silent push notification is not working in iOS 13
we are able to generate silent push notifications from firebase console to ios devices ( via APNS ) when the app is in the background - we have tested these and these are consistently received over long periods of the app in background ( ios 13 as well). however when we try and send the same silent notifications via our backend server ( which is node.js) then they aren't received? any solutions/ suggestions</p>

```<code>let data = {
        key1:`Key1 Value`,
        key2:`Key2 Value`,
        notificationTime: new Date().toISOString()
    }
    const response = await admin.messaging().send({
        token,
        data,
        apns: {
          headers:{
            'apns-push-type':'background',
            'apns-priority':'5',
            'apns-topic': 'com.packageName'
        },
        payload: {
          aps: {
            'content-available': 1,
            'alert':{
                'body':""
            }
          },
        },
      }
    });
</code>```

答:
I had the same issue, and all I did is the following:

Steps

Logout from your application

Remove the application

Restart your phone (Turn it off and turn it on after ~30 seconds)

Install the app once again

Login

Send the app to background / Kill it from the processes

Send the silent push notification

It looks like restarting the phone did the trick in my case.

Body:
we are able to generate silent push notifications from firebase console to ios devices ( via APNS ) when the app is in the background - we have tested these and these are consistently received over long periods of the app in background ( ios 13 as well). however when we try and send the same silent notifications via our backend server ( which is node.js) then they aren't received? any solutions/ suggestions

let data = {
        key1:`Key1 Value`,
        key2:`Key2 Value`,
        notificationTime: new Date().toISOString()
    }
    const response = await admin.messaging().send({
        token,
        data,
        apns: {
          headers:{
            'apns-push-type':'background',
            'apns-priority':'5',
            'apns-topic': 'com.packageName'
        },
        payload: {
          aps: {
            'content-available': 1,
            'alert':{
                'body':""
            }
          },
        },
      }
    });


问:
implement word2vec, but I got error, that word car_NOUN is in the vocabulary
I wrote the code below: to implement the word2vec on it, now im testing to get embedding for w2v_model.wv['car_NOUN']   but I get error as below : "word 'car_NOUN' not in vocabulary" but im sure that word car_NOUN is in the vocabulary , what is the problem ?
can someone help me?

about code : I used Use spacy to restrict the words in the tweets to content words, i.e., nouns, verbs, and adjectives. Transform the words to lower case and add the POS with an underderscore. E.g.:love_VERB .then I wanted to implement word2vec on new list but I came up with that error

love_VERB old-fashioneds_NOUN

```<code>KeyError                                  Traceback (most recent call last)
<ipython-input-145-f6fb9c62175c> in <module>()
----> 1 w2v_model.wv['car_NOUN']

2 frames
/usr/local/lib/python3.6/dist-packages/gensim/models/keyedvectors.py in word_vec(self, word, use_norm)
    450             return result
    451         else:
--> 452             raise KeyError("word '%s' not in vocabulary" % word)
    453
    454     def get_vector(self, word):

KeyError: "word 'car_NOUN' not in vocabulary"
</code>```

```<code>! pip install wget
import wget
url = 'https://raw.githubusercontent.com/dirkhovy/NLPclass/master/data/reviews.full.tsv.zip'
wget.download(url, 'reviews.full.tsv.zip')

from zipfile import ZipFile
with ZipFile('reviews.full.tsv.zip', 'r') as zf:
    zf.extractall()

import pandas as pd
df = pd.read_csv('reviews.full.tsv', sep='\t', nrows=100000) # nrows , max amount of rows
documents = df.text.values.tolist()
print(documents[:4])

import spacy

nlp = spacy.load('en_core_web_sm') #you can use other methods
# excluded tags
included_tags = {"NOUN", "VERB", "ADJ"}
#document = [line.strip() for line in open('moby_dick.txt', encoding='utf8').readlines()]

sentences = documents[:103] #first 10 sentences
new_sentences = []
for sentence in sentences:
    new_sentence = []
    for token in nlp(sentence):
        if token.pos_  in included_tags:
            new_sentence.append(token.text.lower()+'_'+token.pos_)
    new_sentences.append(" ".join(new_sentence))

def convert(new_sentences):
    return ' '.join(new_sentences).split()

x=convert(new_sentences)

from gensim.models import Word2Vec
from gensim.models.word2vec import FAST_VERSION

# initialize model
w2v_model = Word2Vec(size=100,
                     window=15,
                     sample=0.0001,
                     iter=200,
                     negative=5,
                     min_count=100,
                     workers=-1,
                     hs=0
)

w2v_model.build_vocab(x)

w2v_model.train(x,
                total_examples=w2v_model.corpus_count,
                epochs=w2v_model.epochs)

w2v_model.wv['car_NOUN']
</code>```

答:
You had a mistake in your convert function: you are supposed to pass a list of lists to Word2Vec, as in, a list that contains the sentences in lists. I have changed that for you. Basically, you want to go from sometihng like this

```<code>['prices_NOUN',
  'change_VERB',
  'want_VERB',
  'research_VERB',
  'price_NOUN',
  'many_ADJ',
  'different_ADJ',
  'sites_NOUN',
  'found_VERB',
  'cheaper_ADJ',]
</code>```

To something like this

```<code>[['prices_NOUN',
  'change_VERB',
  'want_VERB',]
  ['research_VERB',
  'price_NOUN',
  'many_ADJ',]
  ['different_ADJ',
  'sites_NOUN',
  'found_VERB',
  'cheaper_ADJ',]]
</code>```

I have also altered the code around training the model a bit for you to make it work for me, you might want to experiment with that.

```<code>! pip install wget

from gensim.models.word2vec import FAST_VERSION
from gensim.models import Word2Vec
import spacy
import pandas as pd
from zipfile import ZipFile
import wget

url = 'https://raw.githubusercontent.com/dirkhovy/NLPclass/master/data/reviews.full.tsv.zip'
wget.download(url, 'reviews.full.tsv.zip')

with ZipFile('reviews.full.tsv.zip', 'r') as zf:
    zf.extractall()

# nrows , max amount of rows
df = pd.read_csv('reviews.full.tsv', sep='\t', nrows=100000)
documents = df.text.values.tolist()

nlp = spacy.load('en_core_web_sm')  # you can use other methods
# excluded tags
included_tags = {"NOUN", "VERB", "ADJ"}

sentences = documents[:103]  # first 10 sentences
new_sentences = []
for sentence in sentences:
    new_sentence = []
    for token in nlp(sentence):
        if token.pos_ in included_tags:
            new_sentence.append(token.text.lower()+'_'+token.pos_)
    new_sentences.append(new_sentence)

# initialize model
w2v_model = Word2Vec(new_sentences,
                     size=100,
                     window=15,
                     sample=0.0001,
                     iter=200,
                     negative=5,
                     min_count=1,  # <-- it seems your min_count was too high
                     workers=-1,
                     hs=0
                     )

w2v_model.wv['car_NOUN']
</code>```

Returns

```<code>array([ 3.4433445e-03, -4.6847924e-03, -4.6468928e-04, -4.1419661e-04,
        1.6716495e-03, -1.3368594e-03,  2.3602389e-03, -3.5505681e-03,
       -2.6509305e-04,  5.3194270e-04,  2.3251947e-03,  2.1161686e-03,
        3.8566503e-03, -1.0463649e-03, -3.4403126e-04, -2.3808836e-03,
       -1.7489052e-03, -3.6803843e-03, -5.5171514e-04, -4.3218122e-03,
        3.2187223e-03, -1.4893038e-04, -4.7250376e-03, -3.9506676e-03,
        4.9547744e-03,  6.8341813e-04, -1.7588978e-03,  2.9804371e-03,
        1.4809771e-03,  3.8084502e-03,  3.7447066e-05, -2.6706287e-03,
       -8.4727036e-04, -4.8435321e-03, -4.4348584e-03, -3.9350889e-03,
        4.1925525e-03, -2.7435150e-03,  2.5154117e-03, -4.5825918e-03,
       -3.8889556e-03,  4.0331958e-03, -5.7232054e-04,  1.7530264e-03,
        3.8368679e-03, -3.4817799e-03,  2.4366400e-03, -3.7075430e-03,
       -1.2156683e-03,  4.4666473e-03,  1.7927163e-05, -3.2169635e-03,
        1.9718746e-03, -3.0671202e-03, -8.5452310e-04, -2.9490239e-03,
       -4.1346985e-04,  8.5071824e-04,  4.4970238e-03, -2.8501134e-03,
        4.4103153e-03,  1.4589783e-03,  3.6588225e-03, -1.4809598e-03,
       -9.8118311e-05,  2.4781735e-03, -2.4647343e-03,  2.2115968e-03,
        3.1630241e-03, -1.5672935e-04,  1.6695650e-03,  3.5689210e-03,
       -2.6638571e-03,  3.4224256e-03, -1.5750986e-03,  3.6926002e-03,
        3.2584099e-03,  3.8033908e-03,  1.5272110e-04, -2.2282582e-03,
       -4.7118403e-04, -2.5838052e-03, -2.8910220e-03, -3.1307489e-03,
       -4.0518055e-03, -2.3207215e-03,  1.2772443e-03, -4.4162138e-03,
       -1.9835744e-03,  3.0219899e-03,  1.7312685e-03,  3.9408603e-03,
       -5.6407665e-04,  3.2022693e-03, -8.9243404e-04,  4.5719477e-03,
        4.7199172e-03, -4.9393933e-05,  2.2010114e-03, -3.4861618e-03],
      dtype=float32)
</code>```

Body:
I wrote the code below: to implement the word2vec on it, now im testing to get embedding for w2v_model.wv['car_NOUN']   but I get error as below : "word 'car_NOUN' not in vocabulary" but im sure that word car_NOUN is in the vocabulary , what is the problem ?
can someone help me?

about code : I used Use spacy to restrict the words in the tweets to content words, i.e., nouns, verbs, and adjectives. Transform the words to lower case and add the POS with an underderscore. E.g.:love_VERB .then I wanted to implement word2vec on new list but I came up with that error

love_VERB old-fashioneds_NOUN

KeyError                                  Traceback (most recent call last)
<ipython-input-145-f6fb9c62175c> in <module>()
----> 1 w2v_model.wv['car_NOUN']

2 frames
/usr/local/lib/python3.6/dist-packages/gensim/models/keyedvectors.py in word_vec(self, word, use_norm)
    450             return result
    451         else:
--> 452             raise KeyError("word '%s' not in vocabulary" % word)
    453
    454     def get_vector(self, word):

KeyError: "word 'car_NOUN' not in vocabulary"

! pip install wget
import wget
url = 'https://raw.githubusercontent.com/dirkhovy/NLPclass/master/data/reviews.full.tsv.zip'
wget.download(url, 'reviews.full.tsv.zip')

from zipfile import ZipFile
with ZipFile('reviews.full.tsv.zip', 'r') as zf:
    zf.extractall()

import pandas as pd
df = pd.read_csv('reviews.full.tsv', sep='\t', nrows=100000) # nrows , max amount of rows
documents = df.text.values.tolist()
print(documents[:4])

import spacy

nlp = spacy.load('en_core_web_sm') #you can use other methods
# excluded tags
included_tags = {"NOUN", "VERB", "ADJ"}
#document = [line.strip() for line in open('moby_dick.txt', encoding='utf8').readlines()]

sentences = documents[:103] #first 10 sentences
new_sentences = []
for sentence in sentences:
    new_sentence = []
    for token in nlp(sentence):
        if token.pos_  in included_tags:
            new_sentence.append(token.text.lower()+'_'+token.pos_)
    new_sentences.append(" ".join(new_sentence))

def convert(new_sentences):
    return ' '.join(new_sentences).split()

x=convert(new_sentences)

from gensim.models import Word2Vec
from gensim.models.word2vec import FAST_VERSION

# initialize model
w2v_model = Word2Vec(size=100,
                     window=15,
                     sample=0.0001,
                     iter=200,
                     negative=5,
                     min_count=100,
                     workers=-1,
                     hs=0
)

w2v_model.build_vocab(x)

w2v_model.train(x,
                total_examples=w2v_model.corpus_count,
                epochs=w2v_model.epochs)

w2v_model.wv['car_NOUN']

Body:
You had a mistake in your convert function: you are supposed to pass a list of lists to Word2Vec, as in, a list that contains the sentences in lists. I have changed that for you. Basically, you want to go from sometihng like this

['prices_NOUN',
  'change_VERB',
  'want_VERB',
  'research_VERB',
  'price_NOUN',
  'many_ADJ',
  'different_ADJ',
  'sites_NOUN',
  'found_VERB',
  'cheaper_ADJ',]

To something like this

[['prices_NOUN',
  'change_VERB',
  'want_VERB',]
  ['research_VERB',
  'price_NOUN',
  'many_ADJ',]
  ['different_ADJ',
  'sites_NOUN',
  'found_VERB',
  'cheaper_ADJ',]]

I have also altered the code around training the model a bit for you to make it work for me, you might want to experiment with that.

! pip install wget

from gensim.models.word2vec import FAST_VERSION
from gensim.models import Word2Vec
import spacy
import pandas as pd
from zipfile import ZipFile
import wget

url = 'https://raw.githubusercontent.com/dirkhovy/NLPclass/master/data/reviews.full.tsv.zip'
wget.download(url, 'reviews.full.tsv.zip')

with ZipFile('reviews.full.tsv.zip', 'r') as zf:
    zf.extractall()

# nrows , max amount of rows
df = pd.read_csv('reviews.full.tsv', sep='\t', nrows=100000)
documents = df.text.values.tolist()

nlp = spacy.load('en_core_web_sm')  # you can use other methods
# excluded tags
included_tags = {"NOUN", "VERB", "ADJ"}

sentences = documents[:103]  # first 10 sentences
new_sentences = []
for sentence in sentences:
    new_sentence = []
    for token in nlp(sentence):
        if token.pos_ in included_tags:
            new_sentence.append(token.text.lower()+'_'+token.pos_)
    new_sentences.append(new_sentence)

# initialize model
w2v_model = Word2Vec(new_sentences,
                     size=100,
                     window=15,
                     sample=0.0001,
                     iter=200,
                     negative=5,
                     min_count=1,  # <-- it seems your min_count was too high
                     workers=-1,
                     hs=0
                     )

w2v_model.wv['car_NOUN']

Returns

array([ 3.4433445e-03, -4.6847924e-03, -4.6468928e-04, -4.1419661e-04,
        1.6716495e-03, -1.3368594e-03,  2.3602389e-03, -3.5505681e-03,
       -2.6509305e-04,  5.3194270e-04,  2.3251947e-03,  2.1161686e-03,
        3.8566503e-03, -1.0463649e-03, -3.4403126e-04, -2.3808836e-03,
       -1.7489052e-03, -3.6803843e-03, -5.5171514e-04, -4.3218122e-03,
        3.2187223e-03, -1.4893038e-04, -4.7250376e-03, -3.9506676e-03,
        4.9547744e-03,  6.8341813e-04, -1.7588978e-03,  2.9804371e-03,
        1.4809771e-03,  3.8084502e-03,  3.7447066e-05, -2.6706287e-03,
       -8.4727036e-04, -4.8435321e-03, -4.4348584e-03, -3.9350889e-03,
        4.1925525e-03, -2.7435150e-03,  2.5154117e-03, -4.5825918e-03,
       -3.8889556e-03,  4.0331958e-03, -5.7232054e-04,  1.7530264e-03,
        3.8368679e-03, -3.4817799e-03,  2.4366400e-03, -3.7075430e-03,
       -1.2156683e-03,  4.4666473e-03,  1.7927163e-05, -3.2169635e-03,
        1.9718746e-03, -3.0671202e-03, -8.5452310e-04, -2.9490239e-03,
       -4.1346985e-04,  8.5071824e-04,  4.4970238e-03, -2.8501134e-03,
        4.4103153e-03,  1.4589783e-03,  3.6588225e-03, -1.4809598e-03,
       -9.8118311e-05,  2.4781735e-03, -2.4647343e-03,  2.2115968e-03,
        3.1630241e-03, -1.5672935e-04,  1.6695650e-03,  3.5689210e-03,
       -2.6638571e-03,  3.4224256e-03, -1.5750986e-03,  3.6926002e-03,
        3.2584099e-03,  3.8033908e-03,  1.5272110e-04, -2.2282582e-03,
       -4.7118403e-04, -2.5838052e-03, -2.8910220e-03, -3.1307489e-03,
       -4.0518055e-03, -2.3207215e-03,  1.2772443e-03, -4.4162138e-03,
       -1.9835744e-03,  3.0219899e-03,  1.7312685e-03,  3.9408603e-03,
       -5.6407665e-04,  3.2022693e-03, -8.9243404e-04,  4.5719477e-03,
        4.7199172e-03, -4.9393933e-05,  2.2010114e-03, -3.4861618e-03],
      dtype=float32)


问:
Where to remove Python 3.6 from PATH variable in macOS Catalina?
I have installed Python 3.6.8 in macOS 10.15.4 Catalina using the installer obtained from Python.org. Later I have installed Python 3.7.7 via Homebrew and would now like to keep the  Python 3.6.0 but remove it from the $PATH environment variable. However, I am not able to find out where the $PATH variable is modified to include /Library/Frameworks/Python.framework/Versions/3.6/bin, which is the first path in the $PATH variable.

Following are the paths where I looked into, but the file either does not exist or exists but doesn't contain the Python 3.6 bin path.

~/.bashrc

~/.bash_login

~/.bash_profile

~/.cshrc

~/.profile

~/.tcshrc

~/.zprofile

/etc/paths

/etc/paths.d

/etc/profile

~/.MacOSX/environment.plist

The echo $PATH command gives me:

```<code>/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin
</code>```

Any ideas where can I modify the $PATH variable to remove /Library/Frameworks/Python.framework/Versions/3.6/bin from it?

答: I am sorry, must have overlooked it. The correct answer is that the $PATH variable is modified to include /Library/Frameworks/Python.framework/Versions/3.6/bin in the ~/.zprofile config file.

Body:
I have installed Python 3.6.8 in macOS 10.15.4 Catalina using the installer obtained from Python.org. Later I have installed Python 3.7.7 via Homebrew and would now like to keep the  Python 3.6.0 but remove it from the $PATH environment variable. However, I am not able to find out where the $PATH variable is modified to include /Library/Frameworks/Python.framework/Versions/3.6/bin, which is the first path in the $PATH variable.

Following are the paths where I looked into, but the file either does not exist or exists but doesn't contain the Python 3.6 bin path.

~/.bashrc

~/.bash_login

~/.bash_profile

~/.cshrc

~/.profile

~/.tcshrc

~/.zprofile

/etc/paths

/etc/paths.d

/etc/profile

~/.MacOSX/environment.plist

The echo $PATH command gives me:

/Library/Frameworks/Python.framework/Versions/3.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin

Any ideas where can I modify the $PATH variable to remove /Library/Frameworks/Python.framework/Versions/3.6/bin from it?


问:
use proxy model to change cell's background color of a QTableView after values are changed
I have a subclassed QAbstractTableModel

which contains None Type Values to display the rows as empty

```<code>class ViewModel(qtc.QAbstractTableModel):

    def __init__(self, input_data=None):
        super().__init__()

        self.input_data = input_data or [[None, None],[None, None]]
</code>```

I want to change the colors of the cells if the inserted values (replacing the None Type Values) are in /out a certain range

like z = 12 <= x <= 20

#  False == red, True == green

the color should only change if the items are edited or
self.model.layoutChanged.emit() gets executed

the answers to change cell's background color of a QTableView are suggesting to make changes in the data method How to change cell's background color of a QTableView [duplicate]

but this is going to color the cells right at the beginning

I have found an approach in the QT forum to insert a proxy model between the view and the model
How to simply change the background color of a cell inside a TableView

I'm trying to implement the code into Pyqt5, unsuccessful so far. Is there a PyQt5 approach which I'm unaware of?

example code

```<code>import sys
import re

from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc

class ViewModel(qtc.QAbstractTableModel):

    def __init__(self, input_data=None):
        super().__init__()

        self.input_data = input_data or [[None, None],[None, None]]

    def data(self, index, role):  # parameter index, role are needed !
        if role == qtc.Qt.DisplayRole:
            try:
                text = self.input_data[index.row()][index.column()]
            except IndexError:
                text = None

            return text

    def rowCount(self, index=qtc.QModelIndex()):
        return 0 if index.isValid() else len(self.input_data)

    def columnCount(self, index):
        return len(self.input_data[0])

    def headerData(self, section, orientation, role):
        # section is which index of the orientation
        if role == qtc.Qt.DisplayRole:
            if orientation == qtc.Qt.Vertical:
                return "row"

    def flags(self, index):
        return qtc.Qt.ItemIsEditable | qtc.Qt.ItemIsSelectable | qtc.Qt.ItemIsEnabled

    def setData(self, index, value, role=qtc.Qt.EditRole):
        if role == qtc.Qt.EditRole:
            try:
                row = index.row()
                column = index.column()

                pattern = '^[\d]+(?:,[\d]+)?$'

                if re.fullmatch(pattern, value, flags=0):
                    print("true")
                    self.input_data[row][column] = value  # float
                else:
                    print("nope")
                    pass

                return True

            except ValueError:
                print("not a number")
                return False

class MainWindow(qtw.QWidget):

    def __init__(self):
        super().__init__()

        # View
        table_view = qtw.QTableView()

        self.model = ViewModel()

        table_view.setModel(self.model)

        # size and position
        qtRectangle = self.frameGeometry()
        centerPoint = qtw.QDesktopWidget().availableGeometry().center()
        qtRectangle.moveCenter(centerPoint)
        self.move(qtRectangle.topLeft())
        # size
        self.resize(1000, 410)

        # layout
        qvboxlayout = qtw.QVBoxLayout()
        qvboxlayout.addWidget(table_view)

        self.setLayout(qvboxlayout)
        self.show()

if __name__ == '__main__':
    app = qtw.QApplication(sys.argv)
    w = MainWindow()
    sys.exit(app.exec_())

</code>```

答:
If you want to use a proxy to change the color then only the data() method should be overridden:

```<code>class ColorProxy(qtc.QIdentityProxyModel):
    def data(self, index, role=qtc.Qt.DisplayRole):
        if role == qtc.Qt.BackgroundRole:
            data = index.data()
            try:
                value = float(data)
            except (ValueError, TypeError) as e:
                print("error:", e)
            else:
                return qtg.QColor("green") if 12 <= value <= 20 else qtg.QColor("red")
        return super().data(index, role)
</code>```

```<code># ...
self.model = ViewModel()

proxy = ColorProxy()
proxy.setSourceModel(self.model)

table_view.setModel(proxy)
# ...
</code>```

Another solution is to use a delegate

```<code>class ColorDelegate(qtw.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super().initStyleOption(option, index)
        data = index.data()
        try:
            value = float(data)
        except (ValueError, TypeError) as e:
            print("error:", e)
        else:
            color = qtg.QColor("green") if 12 <= value <= 20 else qtg.QColor("red")
            option.backgroundBrush = color
</code>```

```<code># ...
table_view = qtw.QTableView()

self.model = ViewModel()

delegate = ColorDelegate(table_view)
table_view.setItemDelegate(delegate)

table_view.setModel(self.model)
# ...
</code>```

Body:
I have a subclassed QAbstractTableModel

which contains None Type Values to display the rows as empty

class ViewModel(qtc.QAbstractTableModel):

    def __init__(self, input_data=None):
        super().__init__()

        self.input_data = input_data or [[None, None],[None, None]]

I want to change the colors of the cells if the inserted values (replacing the None Type Values) are in /out a certain range

like z = 12 <= x <= 20

#  False == red, True == green

the color should only change if the items are edited or
self.model.layoutChanged.emit() gets executed

the answers to change cell's background color of a QTableView are suggesting to make changes in the data method How to change cell's background color of a QTableView [duplicate]

but this is going to color the cells right at the beginning

I have found an approach in the QT forum to insert a proxy model between the view and the model
How to simply change the background color of a cell inside a TableView

I'm trying to implement the code into Pyqt5, unsuccessful so far. Is there a PyQt5 approach which I'm unaware of?

example code

import sys
import re

from PyQt5 import QtWidgets as qtw
from PyQt5 import QtCore as qtc

class ViewModel(qtc.QAbstractTableModel):

    def __init__(self, input_data=None):
        super().__init__()

        self.input_data = input_data or [[None, None],[None, None]]

    def data(self, index, role):  # parameter index, role are needed !
        if role == qtc.Qt.DisplayRole:
            try:
                text = self.input_data[index.row()][index.column()]
            except IndexError:
                text = None

            return text

    def rowCount(self, index=qtc.QModelIndex()):
        return 0 if index.isValid() else len(self.input_data)

    def columnCount(self, index):
        return len(self.input_data[0])

    def headerData(self, section, orientation, role):
        # section is which index of the orientation
        if role == qtc.Qt.DisplayRole:
            if orientation == qtc.Qt.Vertical:
                return "row"

    def flags(self, index):
        return qtc.Qt.ItemIsEditable | qtc.Qt.ItemIsSelectable | qtc.Qt.ItemIsEnabled

    def setData(self, index, value, role=qtc.Qt.EditRole):
        if role == qtc.Qt.EditRole:
            try:
                row = index.row()
                column = index.column()

                pattern = '^[\d]+(?:,[\d]+)?$'

                if re.fullmatch(pattern, value, flags=0):
                    print("true")
                    self.input_data[row][column] = value  # float
                else:
                    print("nope")
                    pass

                return True

            except ValueError:
                print("not a number")
                return False

class MainWindow(qtw.QWidget):

    def __init__(self):
        super().__init__()

        # View
        table_view = qtw.QTableView()

        self.model = ViewModel()

        table_view.setModel(self.model)

        # size and position
        qtRectangle = self.frameGeometry()
        centerPoint = qtw.QDesktopWidget().availableGeometry().center()
        qtRectangle.moveCenter(centerPoint)
        self.move(qtRectangle.topLeft())
        # size
        self.resize(1000, 410)

        # layout
        qvboxlayout = qtw.QVBoxLayout()
        qvboxlayout.addWidget(table_view)

        self.setLayout(qvboxlayout)
        self.show()

if __name__ == '__main__':
    app = qtw.QApplication(sys.argv)
    w = MainWindow()
    sys.exit(app.exec_())

Body:
If you want to use a proxy to change the color then only the data() method should be overridden:

class ColorProxy(qtc.QIdentityProxyModel):
    def data(self, index, role=qtc.Qt.DisplayRole):
        if role == qtc.Qt.BackgroundRole:
            data = index.data()
            try:
                value = float(data)
            except (ValueError, TypeError) as e:
                print("error:", e)
            else:
                return qtg.QColor("green") if 12 <= value <= 20 else qtg.QColor("red")
        return super().data(index, role)

# ...
self.model = ViewModel()

proxy = ColorProxy()
proxy.setSourceModel(self.model)

table_view.setModel(proxy)
# ...

Another solution is to use a delegate

class ColorDelegate(qtw.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super().initStyleOption(option, index)
        data = index.data()
        try:
            value = float(data)
        except (ValueError, TypeError) as e:
            print("error:", e)
        else:
            color = qtg.QColor("green") if 12 <= value <= 20 else qtg.QColor("red")
            option.backgroundBrush = color

# ...
table_view = qtw.QTableView()

self.model = ViewModel()

delegate = ColorDelegate(table_view)
table_view.setItemDelegate(delegate)

table_view.setModel(self.model)
# ...


问:
How to call a TYPO3 custom viewhelper from a typoscript (.ts) file and receive a response from viewhelper?
I tried to call a custom viewhelper in TYPO3 9.5.9 from a typoscript file. But it is not working.
An example for viewhelper is given below:

```<code><?php
namespace MyVendor\BlogExample\ViewHelpers;

use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

class GravatarViewHelper extends AbstractViewHelper
{
   use CompileWithRenderStatic;

   public static function renderStatic(
       array $arguments,
       \Closure $renderChildrenClosure,
       RenderingContextInterface $renderingContext
   ) {
       return 'World';
   }
}
</code>```

How can I call this custom viewhelper from a typoscript (.ts) file and get a response ?

答:
Why should you do this? (please describe your use case)

Viewhelpers are for usage in FLUID templates, there you have the correct and matching context.

If you want to call a PHP function inside of typoscript directly you have the option of an userfunc (manual). But you need to provide the necssary context.

Body:
I tried to call a custom viewhelper in TYPO3 9.5.9 from a typoscript file. But it is not working.
An example for viewhelper is given below:

<?php
namespace MyVendor\BlogExample\ViewHelpers;

use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

class GravatarViewHelper extends AbstractViewHelper
{
   use CompileWithRenderStatic;

   public static function renderStatic(
       array $arguments,
       \Closure $renderChildrenClosure,
       RenderingContextInterface $renderingContext
   ) {
       return 'World';
   }
}

How can I call this custom viewhelper from a typoscript (.ts) file and get a response ?


问:
Problem in camera activities in ios4
hi so far i have used  UIImagePickerController  for camera activities in IOS3. But in IOS4 the  ImagePickerController is  not working properly. When i tried to capture  image it shows either a  white image or else the app gets crashed often.

So i started using the AVCapture device for my camera  activities. In  this too i started facing new problems. When i capture  the image in  landscape the image preview shows the image to be portrait  and vice  versa. And some times it shows memory level warning.

Both  the UIImagePickerController and the AVCapture are making  problems. I  want to know how to solve these problems. Else is there any  other way  to handle camera activities in IOS4.

Please help me friends.....

答:
If you just want to enable the user to take photos, UIImagePickerController is the way to go. AVFoundation is quite low level and requires you to handle a lot of things yourself (e.g. compensating for the device orientation).

I've used UIImagePickerController extensively on iOS 4 and it works just fine for me. I suspect the white image/crashing problems are due to something else in your code. If you post a few code snippets we can try to figure out what's going on.

ContentLicense: CC BY-SA 3.0

Title: Problem in camera activities in ios4


问:
How to take screen shot for failed test cases using selenium webdriver in Java?
Can any one please help taking screen shots and saving on specific folder on Mac while running selenium webdriver automation scripts using java??

Note: I used static in my code so i cannot use below code

```<code>File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\screenshot.jpg"));
</code>```

Thanks in advance !!

答:
Below is something that works for me, I am using junit4 with selenium. Also, it used the name of the scenario for the screenshot which is very helpful.

```<code>@After
public void closeBrowser(Scenario scenario){
    if(scenario.isFailed()){
        try{
            TakesScreenshot screenshot = (TakesScreenshot)browser;
            File source = screenshot.getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(source, new File("logs/screenshots/" + scenario.getName() + ".png"));
            System.out.println("Screenshot taken");
        } catch (Exception e){
            System.out.println("Exception while taking screenshot " + e.getMessage());
        }
    }
    browser.quit();
}
</code>```

Hope this helps :)

Body:
Can any one please help taking screen shots and saving on specific folder on Mac while running selenium webdriver automation scripts using java??

Note: I used static in my code so i cannot use below code

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\screenshot.jpg"));

Thanks in advance !!

Body:
Below is something that works for me, I am using junit4 with selenium. Also, it used the name of the scenario for the screenshot which is very helpful.

@After
public void closeBrowser(Scenario scenario){
    if(scenario.isFailed()){
        try{
            TakesScreenshot screenshot = (TakesScreenshot)browser;
            File source = screenshot.getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(source, new File("logs/screenshots/" + scenario.getName() + ".png"));
            System.out.println("Screenshot taken");
        } catch (Exception e){
            System.out.println("Exception while taking screenshot " + e.getMessage());
        }
    }
    browser.quit();
}

Hope this helps :)


问:
TwitteR analysis on tweet trends
I am doing a twitter analysis on a few selected users on R. I used the twitteR package to get user data, and their tweets.

However there is a limitation of 3200 tweets on each user, but I would like to do an analysis on the number of tweets, retweets and replies by a particular user over time (probably since opening their user account). Is there any way of getting these numbers?

答: The Twitter API timeline for individual users is 3200 Tweets. The way to get more than that would be to use the full-archive search API, which is commercial. That does also provide a specific “count” endpoint that would enable you to discover how many times a specific user account Tweeted within a time period. I don’t think twitteR is developed any more, and rTweet is a more-commonly-used package now - I believe that it may have support for the premium full-archive search features, but you would want to check that.

Title: TwitteR analysis on tweet trends


问:
How can I modify an struct in another .c?
I'm trying to add some data to my struct in another .c, but I'm getting segfault.

This is an example of my main.c.
I used "REGISTER *reg" to use the struct from the other file.

```<code>#include "otherfile.c"

int main(){
   char mom[30];
   char baby[30];
   int age;

   REGISTER *reg;

   scanf("%s", mom);
   scanf("%s", baby);
   scanf("%d", &age);

   set_mothersName(reg,mom);
   set_childsName(reg,baby);
   set_age(reg,age);

return 0;
}
</code>```

In the other file, I try this:

```<code>typedef struct register{
   char mothersName[30];
   char childsName[30];
   int age;
}REGISTER;

void set_mothersName(REGISTER *reg, char* name){
   strcpy(reg->mothersName,name);
}
void set_childsName(REGISTER *reg, char*name){
   strcpy(reg->childsName,name);
}
void set_age(REGISTER* reg, int age){
   reg->age = age;
}
</code>```

I think I'm using pointers wrong, but I can't know where and why.

答:
As the others answers stated, you have an issue with a uninitialized pointer. It also just so happens that register is a C keyword, so you might want to change your lowercase register to something like s_register to avoid confusions and probably compiling errors.
Since you seem to be learning about pointers I will go a bit more in depth in my explanation.

When declaring a REGISTER *reg; you declare a pointer, of size 8 which will contain an address to a space you have manually assigned. By default pointers are not initialized so you basically have a pointer to a random place in memory.

When declaring a REGISTER reg;, you are declaring a variable of size 64 (size of your structure) on the stack with its space assigned like you would declare a char (size 1). When using the & symbol, you access to the address of this structure, the pointer to this allocated space.

I rewrote your code adding a .h file to declare your functions because I was getting compiling errors trying  yours, the compiler found multiple declarations for your functions.

Here is the code :

file.c :

```<code>    #include "declar.h"
    #include <stdio.h>

    int main()
    {
       char mom[30];
       char baby[30];
       int age;

       REGISTER reg;

       scanf("%s", mom);
       scanf("%s", baby);
       scanf("%d", &age);

       set_mothersName(&reg, mom);
       set_childsName(&reg, baby);
       set_age(&reg, age);

       return 0;
    }
</code>```

otherfile.c :

```<code>    #include "declar.h"
    #include <string.h>
    #include <stdio.h>

    void set_mothersName(REGISTER *reg, char *name)
    {
       strcpy(reg->mothersName, name);
    }
    void set_childsName(REGISTER *reg, char *name)
    {
       strcpy(reg->childsName, name);
    }
    void set_age(REGISTER *reg, int age)
    {
       reg->age = age;
    }
</code>```

declar.h :

```<code>    #ifndef DECLAR_H_
    # define DECLAR_H_

    typedef struct reg
    {
       char mothersName[30];
       char childsName[30];
       int age;
    } REGISTER;

    void set_mothersName(REGISTER *reg, char *name);
    void set_childsName(REGISTER *reg, char *name);
    void set_age(REGISTER *reg, int age);

    #endif
</code>```

Let me know if this works out for you, also be careful with a use of scanf in real word applications, it is very easy to break by simply overflowing the buffer.
Hopefully this helped you :)

Body:
I'm trying to add some data to my struct in another .c, but I'm getting segfault.

This is an example of my main.c.
I used "REGISTER *reg" to use the struct from the other file.

#include "otherfile.c"

int main(){
   char mom[30];
   char baby[30];
   int age;

   REGISTER *reg;

   scanf("%s", mom);
   scanf("%s", baby);
   scanf("%d", &age);

   set_mothersName(reg,mom);
   set_childsName(reg,baby);
   set_age(reg,age);

return 0;
}

In the other file, I try this:

typedef struct register{
   char mothersName[30];
   char childsName[30];
   int age;
}REGISTER;

void set_mothersName(REGISTER *reg, char* name){
   strcpy(reg->mothersName,name);
}
void set_childsName(REGISTER *reg, char*name){
   strcpy(reg->childsName,name);
}
void set_age(REGISTER* reg, int age){
   reg->age = age;
}

I think I'm using pointers wrong, but I can't know where and why.

Body:
As the others answers stated, you have an issue with a uninitialized pointer. It also just so happens that register is a C keyword, so you might want to change your lowercase register to something like s_register to avoid confusions and probably compiling errors.
Since you seem to be learning about pointers I will go a bit more in depth in my explanation.

When declaring a REGISTER *reg; you declare a pointer, of size 8 which will contain an address to a space you have manually assigned. By default pointers are not initialized so you basically have a pointer to a random place in memory.

When declaring a REGISTER reg;, you are declaring a variable of size 64 (size of your structure) on the stack with its space assigned like you would declare a char (size 1). When using the & symbol, you access to the address of this structure, the pointer to this allocated space.

I rewrote your code adding a .h file to declare your functions because I was getting compiling errors trying  yours, the compiler found multiple declarations for your functions.

Here is the code :

file.c :

    #include "declar.h"
    #include <stdio.h>

    int main()
    {
       char mom[30];
       char baby[30];
       int age;

       REGISTER reg;

       scanf("%s", mom);
       scanf("%s", baby);
       scanf("%d", &age);

       set_mothersName(&reg, mom);
       set_childsName(&reg, baby);
       set_age(&reg, age);

       return 0;
    }

otherfile.c :

    #include "declar.h"
    #include <string.h>
    #include <stdio.h>

    void set_mothersName(REGISTER *reg, char *name)
    {
       strcpy(reg->mothersName, name);
    }
    void set_childsName(REGISTER *reg, char *name)
    {
       strcpy(reg->childsName, name);
    }
    void set_age(REGISTER *reg, int age)
    {
       reg->age = age;
    }

declar.h :

    #ifndef DECLAR_H_
    # define DECLAR_H_

    typedef struct reg
    {
       char mothersName[30];
       char childsName[30];
       int age;
    } REGISTER;

    void set_mothersName(REGISTER *reg, char *name);
    void set_childsName(REGISTER *reg, char *name);
    void set_age(REGISTER *reg, int age);

    #endif

Let me know if this works out for you, also be careful with a use of scanf in real word applications, it is very easy to break by simply overflowing the buffer.
Hopefully this helped you :)


问:
Reducing the time complexity of the program
I am doing this practice problem where given a string s of lowercase letters, and a position p, I have to print all the occurrences of the letter at position p which occur before the position p.

Eg: If the string is "abaac" and p=3(1 based index) then output is 1 because 'a' occurs one time before the position p.

 There are q queries each giving me a position p. Is there any way to make this code more efficient?
I'm using hashing which is pretty efficient I think? Is there any algorithm that I am not aware of?

```<code>#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin>>n;
    string s;
    cin>>s;
    int q;
    cin>>q;
    while(q--)
    {
        int p;
        cin>>p;
        int freq[26] = {0};
        for(int i = 0; i<(p-1); i++)
            freq[s[i]-'a']++;
        cout<<freq[s[p-1]-'a']<<"\n";
    }

}

</code>```

答:
HINT ONLY

The trick here is pre-calculate answers just after you read string. You can do it quite fast.
So in exchange of memory complexity you will gain on time complexity.
This can be done in linear time to string size.

This way you will be able to provide an answer in following queries in constant time.

OFFTOPIC

This problem should have this code to gain on IO speed:

int main()
{
    std::sync_with_stdio(false);
    std::cin.tie(nullptr);
```

Body:
I am doing this practice problem where given a string s of lowercase letters, and a position p, I have to print all the occurrences of the letter at position p which occur before the position p.

Eg: If the string is "abaac" and p=3(1 based index) then output is 1 because 'a' occurs one time before the position p.

 There are q queries each giving me a position p. Is there any way to make this code more efficient?
I'm using hashing which is pretty efficient I think? Is there any algorithm that I am not aware of?

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin>>n;
    string s;
    cin>>s;
    int q;
    cin>>q;
    while(q--)
    {
        int p;
        cin>>p;
        int freq[26] = {0};
        for(int i = 0; i<(p-1); i++)
            freq[s[i]-'a']++;
        cout<<freq[s[p-1]-'a']<<"\n";
    }

}


问:
Knowing when NSPopoverTouchBarItem will show its collapsed view
I have an NSPopoverTouchBarItem in my Touch Bar, created in Interface Builder.

The popover has a custom NSView inside it, and want to load data in it only when the view is activated, but I can't find any way to recognize when the contained NSTouchBar or NSView becomes visible.

According to docs, NSTouchBarDelegate does not have any delegate methods for the view appearing, either.

Which class should I subclass, or should I be monitoring viewWillDraw on my custom NSView and set up some hacky scheme?

答:
The docs were not too clear, but subclassing NSPopoverTouchBarItem gives you -(void)showPopover:(id)sender and -(void)dismissPopover:(id)sender.

You can then define a delegate method to tell the parent class that this popover did show.

-(void)showPopover:(id)sender {
    [super showPopover:sender];
    [self.delegate touchPopoverDidShow];
}
```


问:
How to sharpen more div border using CSS?
I'm trying to create a div in moon shape, like this:

What I got to make was this:

.half-circle {
    width: 100%;
    height: 50px;

    background-color: gold;
    border-bottom-left-radius: 50%;
    border-bottom-right-radius: 50%;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="half-circle"></div></code>```

Is possible fine tune more with CSS?

答:
With some rotation you can do it:

.half-circle {
  width: 100%;
  height: 250px;
  position: relative;
  z-index:0;
  overflow: hidden;
}

.half-circle::before {
  content: "";
  position: absolute;
  z-index:-1;
  width: 2000px;  /* this need to be as big as possible to cover a big area */
  height: 2000px; /* this need to be the same as width */
  left: 50%;
  top: 50%;
  /* adjust the -65% and the 75deg to control the height
     don't touch the other
  */
  transform: translate(-50%, -65%) rotateX(75deg) rotate(45deg);
  background-color: gold;
  border-radius:0 0 10% 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="half-circle"></div></code>```

Body:
I'm trying to create a div in moon shape, like this:

What I got to make was this:

.half-circle {
    width: 100%;
    height: 50px;

    background-color: gold;
    border-bottom-left-radius: 50%;
    border-bottom-right-radius: 50%;

}

Is possible fine tune more with CSS?

Body:
With some rotation you can do it:

.half-circle {
  width: 100%;
  height: 250px;
  position: relative;
  z-index:0;
  overflow: hidden;
}

.half-circle::before {
  content: "";
  position: absolute;
  z-index:-1;
  width: 2000px;  /* this need to be as big as possible to cover a big area */
  height: 2000px; /* this need to be the same as width */
  left: 50%;
  top: 50%;
  /* adjust the -65% and the 75deg to control the height
     don't touch the other
  */
  transform: translate(-50%, -65%) rotateX(75deg) rotate(45deg);
  background-color: gold;
  border-radius:0 0 10% 0;
}

<div class="half-circle"></div>


问:
React Native hooks - correct use of useEffect()?
I'm new to hooks and ran across this setup on SO and wanted to confirm that this is the correct pattern. I was getting the RN "unmounted component" leak warning message before and this seemed to solve it. I'm trying to mimic in some way compnentDidMount. This is part of a phone number verify sign up flow and onMount I want to just check for navigation and then fire off a side effect, set mounted true and then unmount correctly.

```<code>const SMSVerifyEnterPinScreen = ({ route, navigation }) => {

  const [didMount, setDidMount] = useState(false)
  const { phoneNumber } = route.params

  useEffect(() => {
    if(navigation) {
      signInWithPhoneNumber(phoneNumber)
      setDidMount(true)
    }
    return () => setDidMount(false)
  }, [])

  if (!didMount) { return null }

  async function signInWithPhoneNumber(phoneNumber) {
    const confirmation = await auth().signInWithPhoneNumber('+1'+phoneNumber)
    ...
  }

  return (
    ...
  )
}

</code>```

RN 0.62.2 with react-nav 5 - thanks!

答:
Since signInWithPhoneNumber is a async function and will setState you will see warning it the component is unmounted before the response is available

In order to handle such scenarios you can keep a variable to keep track whether its mounted or not and then only set state is the mounted variable is true

However you do not need to return null if component has unmounted since that doesn't accomplish anything. The component is removed from view and will anyways not render anything.

Also you do not need to maintain this value in state, instead use a ref

```<code>const SMSVerifyEnterPinScreen = ({ route, navigation }) => {

  const isMounted = useRef(true)
  const { phoneNumber } = route.params

  useEffect(() => {
    if(navigation) {
      signInWithPhoneNumber(phoneNumber)
    }
    return () => {isMounted.current = false;}
  }, [])

  async function signInWithPhoneNumber(phoneNumber) {
    const confirmation = await auth().signInWithPhoneNumber('+1'+phoneNumber)
    ...
  }

  return (
    ...
  )
}
</code>```

Body:
I'm new to hooks and ran across this setup on SO and wanted to confirm that this is the correct pattern. I was getting the RN "unmounted component" leak warning message before and this seemed to solve it. I'm trying to mimic in some way compnentDidMount. This is part of a phone number verify sign up flow and onMount I want to just check for navigation and then fire off a side effect, set mounted true and then unmount correctly.

const SMSVerifyEnterPinScreen = ({ route, navigation }) => {

  const [didMount, setDidMount] = useState(false)
  const { phoneNumber } = route.params

  useEffect(() => {
    if(navigation) {
      signInWithPhoneNumber(phoneNumber)
      setDidMount(true)
    }
    return () => setDidMount(false)
  }, [])

  if (!didMount) { return null }

  async function signInWithPhoneNumber(phoneNumber) {
    const confirmation = await auth().signInWithPhoneNumber('+1'+phoneNumber)
    ...
  }

  return (
    ...
  )
}

RN 0.62.2 with react-nav 5 - thanks!

Body:
Since signInWithPhoneNumber is a async function and will setState you will see warning it the component is unmounted before the response is available

In order to handle such scenarios you can keep a variable to keep track whether its mounted or not and then only set state is the mounted variable is true

However you do not need to return null if component has unmounted since that doesn't accomplish anything. The component is removed from view and will anyways not render anything.

Also you do not need to maintain this value in state, instead use a ref

const SMSVerifyEnterPinScreen = ({ route, navigation }) => {

  const isMounted = useRef(true)
  const { phoneNumber } = route.params

  useEffect(() => {
    if(navigation) {
      signInWithPhoneNumber(phoneNumber)
    }
    return () => {isMounted.current = false;}
  }, [])

  async function signInWithPhoneNumber(phoneNumber) {
    const confirmation = await auth().signInWithPhoneNumber('+1'+phoneNumber)
    ...
  }

  return (
    ...
  )
}


问:
Python - Regex (Re.Escape, Re.Findall); How To: Find sub-strings + a number of characters beyond the sub-strings within a string?
This might be an simple question.  I'm learning how to use Regex and I am having trouble performing a specific task on a string.

For example:

example_string = "; One, one; Two, two; Three, three; Four, four"

desired_output = ["One, o", "Two, t", "Three, t", "Four, f"] #list output is OK

With the following, i can get ["One" , "Two" , "Three"]:

```<code>def findStringsInMiddle(a, b, text):
    return re.findall(re.escape(a)+"(.*?)"+re.escape(b),text)

desired_output = findStringsInMiddle('; ' , ',' , example_string)
</code>```

But I am having trouble figuring out how to configure this properly to grab the comma+space+any_type_of_character that I also want.

Any advice?

Thanks!

答:
```<code>import re

example_string = "; One, one; Two, two; Three, three; Four, four"

pattern = re.compile(r";\s"  # The search string must start with a semoicolon and then a space character
                     r"([A-Z][a-z]+,\s.?)"  # Here is the capturing group, containing first a capital letter,
                     # some lowercase letters
                     # and finally a comma, space and zero or one characters
                     )
print(re.findall(pattern,
                 example_string
                 )
      )

</code>```

Output:

```<code>['One, o', 'Two, t', 'Three, t', 'Four, f']
</code>```

Body:
This might be an simple question.  I'm learning how to use Regex and I am having trouble performing a specific task on a string.

For example:

example_string = "; One, one; Two, two; Three, three; Four, four"

desired_output = ["One, o", "Two, t", "Three, t", "Four, f"] #list output is OK

With the following, i can get ["One" , "Two" , "Three"]:

def findStringsInMiddle(a, b, text):
    return re.findall(re.escape(a)+"(.*?)"+re.escape(b),text)

desired_output = findStringsInMiddle('; ' , ',' , example_string)

But I am having trouble figuring out how to configure this properly to grab the comma+space+any_type_of_character that I also want.

Any advice?

Thanks!

Body:
import re

example_string = "; One, one; Two, two; Three, three; Four, four"

pattern = re.compile(r";\s"  # The search string must start with a semoicolon and then a space character
                     r"([A-Z][a-z]+,\s.?)"  # Here is the capturing group, containing first a capital letter,
                     # some lowercase letters
                     # and finally a comma, space and zero or one characters
                     )
print(re.findall(pattern,
                 example_string
                 )
      )

Output:

['One, o', 'Two, t', 'Three, t', 'Four, f']


问:
Fast Multiprocessing for small processes in Python
I am facing the following problem:
Within a larger python class I would like to execute a part of it in multiple processes to speed up my programm. As you see in my minimum example I have this function f(x), I call 10 times. Doing this by a single process takes around 1 second. With multiprocessing I would like to come as close to 100 ms as possible. Therefore, I already tried the Pool.map and Pool.imap_unordered method. As you see, they are much faster but dont give me the desired results.

Can you help me?

```<code>import time
from multiprocessing import Pool

class TestClass(object):

    def __init__(self):
        # Single Process
        self.result_list = []
        self.single_process()
        print(self.result_list)

        # Multiprocess ordered
        self.result_list = []
        self.multiprocessing_ordered()
        print(self.result_list)

        # Multiprocess unordered
        self.result_list = []
        self.multiprocessing_unordered()
        print(self.result_list)

    def f(self, x):
        time.sleep(0.1)
        self.result_list.append(x**2)

    def single_process(self):
        # Single process
        start_time = time.time()
        for x in range(10):
            self.f(x)
        print("Time with a single process: {0:.1f}".format((time.time() - start_time)*1e3))

    def multiprocessing_ordered(self):
        start_time = time.time()
        pool = Pool(10)
        pool.map(self.f, list(range(10)))
        pool.close()
        print("Time with multiprocessing (ordered): {0:.1f}".format((time.time() - start_time)*1e3))

    def multiprocessing_unordered(self):
        start_time = time.time()
        pool = Pool(10)
        pool.imap_unordered(self.f, list(range(10)))
        pool.close()
        print("Time with multiprocessing (unordered): {0:.1f}".format((time.time() - start_time)*1e3))

if __name__ == '__main__':

    test_object = TestClass()
</code>```

Result:

```<code>Time with a single process: 1013.7 ms
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Time with multiprocessing (ordered): 280.3 ms
[]
Time with multiprocessing (unordered): 100.7 ms
[]
</code>```

答:
Processes live in an own memory space and thus the self.result_list is not shared between your parent and your child processes.

You know have multiple options:

Use pipes or queues or any other te in order to communicate between your subprocesses and you main process.

Return a result by your function and retrieve it in the main process like this:

import time
from multiprocessing import Pool

class TestClass(object):

    def __init__(self):
        # Single Process
        self.result_list = []
        self.single_process()
        print(self.result_list)

        # Multiprocess
        self.result_list = []
        self.multiprocessing()
        print(self.result_list)

    def f(self, x):
        time.sleep(0.1)
        return x**2

    def single_process(self):
        # Single process
        start_time = time.time()
        result = []
        for x in range(10):
             self.result_list.append(self.f(x))
        print("Time with a single process: {0:.1f}".format((time.time() - start_time)*1e3))

    def multiprocessing(self):
        pool = Pool(10)

        # Start calculation
        start_time = time.time()
        multiple_results = [pool.apply_async(self.f, (i,)) for i in range(10)]

        # Receive answer
        self.result_list = [res.get(timeout=1) for res in multiple_results]

        # Evaluate result
        print("Time with multiprocessing: {0:.1f}".format((time.time() - start_time)*1e3))

        pool.close()

if __name__ == '__main__':

    test_object = TestClass()
```

<p>Result:</p>

```Time with a single process: 1002.0
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Time with multiprocessing: 102.8
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
```

<ol start="3">
<li>Try the threading module or ThreadPool. Threading shares the same memory space and thus the results can be shared by simply appending it to the list. With ThreadPool:</li>
</ol>

<pre class="lang-py prettyprint-override"><code>import time
from multiprocessing.pool import ThreadPool

class TestClass(object):

    def __init__(self):
        # Single Process
        self.result_list = []
        self.single_process()
        print(self.result_list)

        # Multiprocess ordered
        self.result_list = []
        self.multiprocessing_ordered()
        print(self.result_list)

        # Multiprocess unordered
        self.result_list = []
        self.multiprocessing_unordered()
        print(self.result_list)

    def f(self, x):
        time.sleep(0.1)
        self.result_list.append(x**2)

    def single_process(self):
        # Single process
        start_time = time.time()
        for x in range(10):
            self.f(x)
        print("Time with a single process: {0:.1f}".format((time.time() - start_time)*1e3))

    def multiprocessing_ordered(self):
        start_time = time.time()
        pool = ThreadPool(10)
        pool.map(self.f, list(range(10)))
        pool.close()
        print("Time with multiprocessing (ordered): {0:.1f}".format((time.time() - start_time)*1e3))

    def multiprocessing_unordered(self):
        start_time = time.time()
        pool = ThreadPool(10)
        [_ for _ in pool.imap_unordered(self.f, list(range(10)))]
        pool.close()
        print("Time with multiprocessing (unordered): {0:.1f}".format((time.time() - start_time)*1e3))

if __name__ == '__main__':

    test_object = TestClass()
</code>```

Result with ThreadPool:

```<code>Time with a single process: 1002.0
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Time with multiprocessing (ordered): 116.1
[0, 4, 1, 25, 36, 9, 16, 49, 81, 64]
Time with multiprocessing (unordered): 109.4
[0, 1, 4, 16, 25, 36, 9, 49, 81, 64]
</code>```

Body:
I am facing the following problem:
Within a larger python class I would like to execute a part of it in multiple processes to speed up my programm. As you see in my minimum example I have this function f(x), I call 10 times. Doing this by a single process takes around 1 second. With multiprocessing I would like to come as close to 100 ms as possible. Therefore, I already tried the Pool.map and Pool.imap_unordered method. As you see, they are much faster but dont give me the desired results.

Can you help me?

import time
from multiprocessing import Pool

class TestClass(object):

    def __init__(self):
        # Single Process
        self.result_list = []
        self.single_process()
        print(self.result_list)

        # Multiprocess ordered
        self.result_list = []
        self.multiprocessing_ordered()
        print(self.result_list)

        # Multiprocess unordered
        self.result_list = []
        self.multiprocessing_unordered()
        print(self.result_list)

    def f(self, x):
        time.sleep(0.1)
        self.result_list.append(x**2)

    def single_process(self):
        # Single process
        start_time = time.time()
        for x in range(10):
            self.f(x)
        print("Time with a single process: {0:.1f}".format((time.time() - start_time)*1e3))

    def multiprocessing_ordered(self):
        start_time = time.time()
        pool = Pool(10)
        pool.map(self.f, list(range(10)))
        pool.close()
        print("Time with multiprocessing (ordered): {0:.1f}".format((time.time() - start_time)*1e3))

    def multiprocessing_unordered(self):
        start_time = time.time()
        pool = Pool(10)
        pool.imap_unordered(self.f, list(range(10)))
        pool.close()
        print("Time with multiprocessing (unordered): {0:.1f}".format((time.time() - start_time)*1e3))

if __name__ == '__main__':

    test_object = TestClass()

Result:

Time with a single process: 1013.7 ms
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Time with multiprocessing (ordered): 280.3 ms
[]
Time with multiprocessing (unordered): 100.7 ms
[]

Body:
Processes live in an own memory space and thus the self.result_list is not shared between your parent and your child processes.

You know have multiple options:

Use pipes or queues or any other te in order to communicate between your subprocesses and you main process.

Return a result by your function and retrieve it in the main process like this:

import time
from multiprocessing import Pool

class TestClass(object):

    def __init__(self):
        # Single Process
        self.result_list = []
        self.single_process()
        print(self.result_list)

        # Multiprocess
        self.result_list = []
        self.multiprocessing()
        print(self.result_list)

    def f(self, x):
        time.sleep(0.1)
        return x**2

    def single_process(self):
        # Single process
        start_time = time.time()
        result = []
        for x in range(10):
             self.result_list.append(self.f(x))
        print("Time with a single process: {0:.1f}".format((time.time() - start_time)*1e3))

    def multiprocessing(self):
        pool = Pool(10)

        # Start calculation
        start_time = time.time()
        multiple_results = [pool.apply_async(self.f, (i,)) for i in range(10)]

        # Receive answer
        self.result_list = [res.get(timeout=1) for res in multiple_results]

        # Evaluate result
        print("Time with multiprocessing: {0:.1f}".format((time.time() - start_time)*1e3))

        pool.close()

if __name__ == '__main__':

    test_object = TestClass()

Result:

Time with a single process: 1002.0
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Time with multiprocessing: 102.8
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Try the threading module or ThreadPool. Threading shares the same memory space and thus the results can be shared by simply appending it to the list. With ThreadPool:

import time
from multiprocessing.pool import ThreadPool

class TestClass(object):

    def __init__(self):
        # Single Process
        self.result_list = []
        self.single_process()
        print(self.result_list)

        # Multiprocess ordered
        self.result_list = []
        self.multiprocessing_ordered()
        print(self.result_list)

        # Multiprocess unordered
        self.result_list = []
        self.multiprocessing_unordered()
        print(self.result_list)

    def f(self, x):
        time.sleep(0.1)
        self.result_list.append(x**2)

    def single_process(self):
        # Single process
        start_time = time.time()
        for x in range(10):
            self.f(x)
        print("Time with a single process: {0:.1f}".format((time.time() - start_time)*1e3))

    def multiprocessing_ordered(self):
        start_time = time.time()
        pool = ThreadPool(10)
        pool.map(self.f, list(range(10)))
        pool.close()
        print("Time with multiprocessing (ordered): {0:.1f}".format((time.time() - start_time)*1e3))

    def multiprocessing_unordered(self):
        start_time = time.time()
        pool = ThreadPool(10)
        [_ for _ in pool.imap_unordered(self.f, list(range(10)))]
        pool.close()
        print("Time with multiprocessing (unordered): {0:.1f}".format((time.time() - start_time)*1e3))

if __name__ == '__main__':

    test_object = TestClass()

Result with ThreadPool:

Time with a single process: 1002.0
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Time with multiprocessing (ordered): 116.1
[0, 4, 1, 25, 36, 9, 16, 49, 81, 64]
Time with multiprocessing (unordered): 109.4
[0, 1, 4, 16, 25, 36, 9, 49, 81, 64]