问:
Turn off debug menu on React Native Android apk Release
I'm on RN 0.26 building an apk like so

```<code> cd android && ./gradlew assembleRelease
</code>```

and with all the keystore things in place I get a generated app-release.apk however the app is still in debug mode when I install it on a device. I get errors and rage menu.

I tried hard coding the app/react.grade to

```<code>def devEnabled = false
</code>```

no luck. This didn't used to happen but I used to be on RN 0.13.

答:
Try executing this before you generate release apk</p>

```<code>react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/
</code>```

Body:
I'm on RN 0.26 building an apk like so

 cd android && ./gradlew assembleRelease

and with all the keystore things in place I get a generated app-release.apk however the app is still in debug mode when I install it on a device. I get errors and rage menu.

I tried hard coding the app/react.grade to

def devEnabled = false

no luck. This didn't used to happen but I used to be on RN 0.13.

Body:
Try executing this before you generate release apk

react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/


来源: stackexchange

问:
How to run octave scripts on MacOS?
Using instruction from the website:

http://wiki.octave.org/Octave_for_MacOS_X

I installed octave on MacOS X 10.9.5.
The installed apps are in:

/Applications/Octave-cli.app

/Applications/Octave-gui.app

Now, i have a octave script called example.m

```<code>%file: example.m
print('hello')
</code>```

How can i run this file from the terminal?

```<code>NOTE:

    open /Applications/Octave-cli.app  # this works fine
    open /Applications/Octave-gui.app  # this freezes the octave program
</code>```

Then i can write and run octave commands interactively.

What i want is:

```<code>octave myexample.m
</code>```

should give results, as like python myscript.py gives.

UPDATE:

I uninstalled:

 /Applications/Octave-cli.app and /Applications/Octave-gui.app

Then, i downloaded two apps

    download Octave 4.0.2 with graphical user interface (OS X 10.9+),

    download Octave 4.0.2 with command line interface (OS X 10.9+)

from the website:

http://wiki.octave.org/Octave_for_MacOS_X

Then, i got Octave.app where i can write and run octave scripts in that graphical interface.

But, i also want to run from command line:

```<code>octave myexample.m
</code>```

some related links are following:

How to invoke octave script in unix shell

答:
After installing the GUI 4.0.3 on macOS, you can use this path to CLI:

```<code>/Applications/Octave.app/Contents/Resources/usr/bin/octave-cli
</code>```

This is an alias to:

```<code>/Applications/Octave.app/Contents/Resources/usr/Cellar/octave/4.0.3/bin/octave-cli-4.0.3
</code>```

But running the first is probably up version safe.

ContentLicense: CC BY-SA 3.0

Title: How to run octave scripts on MacOS?

Body:
Using instruction from the website:

http://wiki.octave.org/Octave_for_MacOS_X

I installed octave on MacOS X 10.9.5.
The installed apps are in:

/Applications/Octave-cli.app

/Applications/Octave-gui.app

Now, i have a octave script called example.m

%file: example.m
print('hello')

How can i run this file from the terminal?

NOTE:

    open /Applications/Octave-cli.app  # this works fine
    open /Applications/Octave-gui.app  # this freezes the octave program

Then i can write and run octave commands interactively.

What i want is:

octave myexample.m

should give results, as like python myscript.py gives.

UPDATE:

I uninstalled:

 /Applications/Octave-cli.app and /Applications/Octave-gui.app

Then, i downloaded two apps

    download Octave 4.0.2 with graphical user interface (OS X 10.9+),

    download Octave 4.0.2 with command line interface (OS X 10.9+)

from the website:

http://wiki.octave.org/Octave_for_MacOS_X

Then, i got Octave.app where i can write and run octave scripts in that graphical interface.

But, i also want to run from command line:

octave myexample.m

some related links are following:

How to invoke octave script in unix shell

Body:
After installing the GUI 4.0.3 on macOS, you can use this path to CLI:

/Applications/Octave.app/Contents/Resources/usr/bin/octave-cli

This is an alias to:

/Applications/Octave.app/Contents/Resources/usr/Cellar/octave/4.0.3/bin/octave-cli-4.0.3

But running the first is probably up version safe.


问:
Watson Knowledge Studio integration with Watson Discovery
I am trying to execute the following curl command that should allow me to obtain the .json file that I need to update and PUT in order to integrate WKS and WDS:  curl -u username@ibm.com:password "https://gateway.watsonplatform.net/discovery/api/v1/environments/"env id"/configurations/"config id"?version=2016-12-01" > my_config.json

The curl command works, however, I get a 401 error in the .json file that I am "not authorized".

{ "code" : 401 , "error" : "Not Authorized" , "description" : "2017-07-06T12:07:46-04:00, Error ERCDPLTFRM-INVLDCHR occurred when accessing https://gateway.watsonplatform.net/discovery/api/v1/environments/"env id"/configurations/"config id"?version=2016-12-01, Tran-Id: gateway-dp01-472751002 - " }

I am an IBM employee.  Could this be due to our IBM SSO blue mix requirement?  All help is appreciated as I need this in order to move forward building my code.

答:
The problem here is the username and password are not your Bluemix login credentials. When you create a service instance in Bluemix, Bluemix generates credentials for that specific service instance.

In the Bluemix console, https://console.bluemix.net, navigate to your Discovery instance, then, on the left side of the browser window, click on Service credentials, then toward the right, click on View credentials. The username and password shown there are what you need to use for curl or any other API access to this specific Discovery service instance. If you create a second service instance, Discovery or something else, it will have its own service credentials that you'll need to use for that service instance.


问:
function in C returns always the same arbitrary number
So i´m trying to get the power of any two numbers,

```<code>int expo(int base, int expon){
    int z = 1;
    printf("%i",&z);  // Here i get 635678
    if (expon == 0){
        printf("A");  // this gets printed if expon== 0
        return 1;
    }
    else{
        for (int x=0; x < expon; x++){
            z *= base;
            printf("%i",&z); // here i get 6356780
        }
        return z;
    }

}
</code>```

The thing that amazes me the most is the first 635678, i just told the computer that z = 1 !, the second one is that when it prints A, it doesnt even return 1. It always return 6356776. ( i just declare an int value as being the result of the function and print the int, maybe i even do that bad). I dont care about this particular function, i just want to know what i am telling to the computer, because it is obviously not what i think.
Thanks and sorry because there is a good chance that this question should not be here.

答:
```<code>printf("%i",&z);
</code>```

Here, you're printing the address of z and not its value. What you want is instead:

```<code>int expo(int base, int expon){
int z = 1;
printf("%d",z);
if (expon == 0){
    printf("A");  // this gets printed if expon== 0
    return 1;
}
else{
    for (int x=0; x < expon; x++){
        z *= base;
        printf("%d",z);
    }
    return z;
  }
}
</code>```

Just drop the & reference operator in front of z.

Body:
So i´m trying to get the power of any two numbers,

int expo(int base, int expon){
    int z = 1;
    printf("%i",&z);  // Here i get 635678
    if (expon == 0){
        printf("A");  // this gets printed if expon== 0
        return 1;
    }
    else{
        for (int x=0; x < expon; x++){
            z *= base;
            printf("%i",&z); // here i get 6356780
        }
        return z;
    }

}

The thing that amazes me the most is the first 635678, i just told the computer that z = 1 !, the second one is that when it prints A, it doesnt even return 1. It always return 6356776. ( i just declare an int value as being the result of the function and print the int, maybe i even do that bad). I dont care about this particular function, i just want to know what i am telling to the computer, because it is obviously not what i think.
Thanks and sorry because there is a good chance that this question should not be here.

Body:
printf("%i",&z);

Here, you're printing the address of z and not its value. What you want is instead:

int expo(int base, int expon){
int z = 1;
printf("%d",z);
if (expon == 0){
    printf("A");  // this gets printed if expon== 0
    return 1;
}
else{
    for (int x=0; x < expon; x++){
        z *= base;
        printf("%d",z);
    }
    return z;
  }
}

Just drop the & reference operator in front of z.


问:
A good web hosting service that allows more then 1GB MySQL databases
I was looking for a good mysql and php hosting service that allows more then 1GB MySQL databases for a cheap price and great service. can some one give some suggestions</p>

答: I highly recommend totalchoicehosting.com. I've had multi-gig databases on their shared hosting before, but I'm guessing you want dedicated. Either way, I have used them for 6 years, and they are quite reliable and cheap.</p>

ContentLicense: CC BY-SA 2.5


问:
Controlling model creation in Django and DRF
Consider the following Django model and DRF-based API:

```<code>class Disk(models.Model):
    size = models.IntegerField(...)
    free_space = models.IntegerField(...)

# ---- Serializers ---- #
class DiskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Disk
        fields = ('free_space', 'size')
        read_only_fields = ('size', )

class CreateDiskSerializer(models.Model):
    class Meta:
        model = Disk
        fields = ('size', )  # note, size only!

# ---- View ---- #
class DisksView(viewsets.ModelViewSet):
    ...

    def get_serializer(self):
        if self.request.method == 'POST':
            return CreateDiskSerializer
        else:
            return DiskSerializer
</code>```

I am trying to implement the idea of initializing the value of free_space field from size on model creation.

The naive approach would be overriding Disk.save() but that is something I would use at the very last resort. Another approach would be creating a custom model manager which overrides .create(), e.g.:

```<code>class DiskManager(models.Manager):
    def create(self, **kwargs):
        if 'free_space' not in kwargs:
            try:
                kwargs['free_space'] = kwargs['size']
            except KeyError:
                pass
        return super().create(**kwargs)
</code>```

Does it look acceptable to you? Is there a better solution?

答:
I would recommend overriding the create method of CreateDiskSerializer to look something like:

```<code>def create(self, validated_data):
    validated_data['free_space'] = validated_data['size']
    return super(CreateDiskSerializer, self).create(validated_data)
</code>```

Body:
Consider the following Django model and DRF-based API:

class Disk(models.Model):
    size = models.IntegerField(...)
    free_space = models.IntegerField(...)

# ---- Serializers ---- #
class DiskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Disk
        fields = ('free_space', 'size')
        read_only_fields = ('size', )

class CreateDiskSerializer(models.Model):
    class Meta:
        model = Disk
        fields = ('size', )  # note, size only!

# ---- View ---- #
class DisksView(viewsets.ModelViewSet):
    ...

    def get_serializer(self):
        if self.request.method == 'POST':
            return CreateDiskSerializer
        else:
            return DiskSerializer

I am trying to implement the idea of initializing the value of free_space field from size on model creation.

The naive approach would be overriding Disk.save() but that is something I would use at the very last resort. Another approach would be creating a custom model manager which overrides .create(), e.g.:

class DiskManager(models.Manager):
    def create(self, **kwargs):
        if 'free_space' not in kwargs:
            try:
                kwargs['free_space'] = kwargs['size']
            except KeyError:
                pass
        return super().create(**kwargs)

Does it look acceptable to you? Is there a better solution?

Body:
I would recommend overriding the create method of CreateDiskSerializer to look something like:

def create(self, validated_data):
    validated_data['free_space'] = validated_data['size']
    return super(CreateDiskSerializer, self).create(validated_data)


问:
PHP form won't update my MySQL database
Can someone please help me fix this code I messed up? It won't update my database anymore.</p>

```<code>DEFINE('DB_USER', 'root');
DEFINE('DB_PASSWORD', '');
DEFINE('DB_HOST', 'localhost');
DEFINE('DB_NAME', 'tags');

if ($dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)) {
    if (!mysql_select_db(DB_NAME)) {
        trigger_error("Could not select the database!\n<br />MySQL Error: " . mysql_error());
        include('./includes/footer.htm');
        exit();
    }
} else { // If it couldn't connect to MySQL.
    trigger_error("Could not connect to MySQL!\n<br />MySQL Error: " . mysql_error());
    include('./includes/footer.htm');
    exit();
} // End of $dbc IF.

$tag = mysql_real_escape_string($_POST['tag']);
$query = 'UPDATE tags SET count = count+1 WHERE tag = '.$tag;
mysql_query($query, $dbc);
if (!mysql_affected_rows()) {
    $query = 'INSERT INTO tags (tag, count) VALUES('.$tag.', 1)';
    if (!mysql_query($query,$dbc)) {
        die('Error: ' . mysql_error());
    }
    echo "1 record added";
}

mysql_close($dbc);
</code>```

答:
$query = 'INSERT INTO tags VALUES('".$tag."', 1)';

For a shorter query

OwnerDisplayName: fu

Title: PHP form won't update my MySQL database

Body:
Can someone please help me fix this code I messed up? It won't update my database anymore.

DEFINE('DB_USER', 'root');
DEFINE('DB_PASSWORD', '');
DEFINE('DB_HOST', 'localhost');
DEFINE('DB_NAME', 'tags');

if ($dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)) {
    if (!mysql_select_db(DB_NAME)) {
        trigger_error("Could not select the database!\n
MySQL Error: " . mysql_error());
        include('./includes/footer.htm');
        exit();
    }
} else { // If it couldn't connect to MySQL.
    trigger_error("Could not connect to MySQL!\n
MySQL Error: " . mysql_error());
    include('./includes/footer.htm');
    exit();
} // End of $dbc IF.

$tag = mysql_real_escape_string($_POST['tag']);
$query = 'UPDATE tags SET count = count+1 WHERE tag = '.$tag;
mysql_query($query, $dbc);
if (!mysql_affected_rows()) {
    $query = 'INSERT INTO tags (tag, count) VALUES('.$tag.', 1)';
    if (!mysql_query($query,$dbc)) {
        die('Error: ' . mysql_error());
    }
    echo "1 record added";
}

mysql_close($dbc);


问:
Regex to match variations of words
I have several sentences of the format:

Visa requirements for Qatari citizens are administrative entry restrictions by the authorities of other states placed on citizens of the Qatar.

Visa requirements for British citizens are administrative entry restrictions by the authorities of other states placed on citizens of the United Kingdom.

Visa requirements for Belarusian citizens are administrative entry restrictions imposed on citizens of Belarus by the authorities of other states.

I only want to match the "citizens of [country name]" in the above sentences. As you can see, some of them end with a period "citizens of china." others continue and some have words like "the" and some countries have two or more words like "united kingdom".

How do I write a (pythonic) regex that will match the "citizens of COUNTRY_NAME" in all of the above statements and their variations?

答:
Use the regex module so that we can use Unicode categories.

We make the assumption that country names are multiple contiguous words that each start with a capital letter, and are separated by some number of spaces. If you can't make that assumption, then tweak it at your will. If you already have a country list, then just .{,40} match the country part (or some other sensible limit) and check if some country is a sub-string.

```<code>import regex as re

text = '''Visa requirements...'''
country_pat = r'citizens of (?:the )?((?:\p{Lu}\p{L}+(?:\s*))+)'
print(country_pat.findall(text))
</code>```

(?: means we don't match that part, and p{Lu} and p{L} are Unicode uppercase letters and letters, respectively.

Title: Regex to match variations of words

Body:
Use the regex module so that we can use Unicode categories.

We make the assumption that country names are multiple contiguous words that each start with a capital letter, and are separated by some number of spaces. If you can't make that assumption, then tweak it at your will. If you already have a country list, then just .{,40} match the country part (or some other sensible limit) and check if some country is a sub-string.

import regex as re

text = '''Visa requirements...'''
country_pat = r'citizens of (?:the )?((?:\p{Lu}\p{L}+(?:\s*))+)'
print(country_pat.findall(text))

(?: means we don't match that part, and p{Lu} and p{L} are Unicode uppercase letters and letters, respectively.


问:
Changing the default filename when using mPDF
I'm currently using mPDF to generate a pdf from HTML (which was generated by PHP).

All works as expected but I'd like to be able to change the default filename.  Currently, I have:

```<code>$payStub=new mPDF();
$payStub->SetTitle('My title');
$payStub->WriteHTML($pcTableRows);
$payStub->Output();
</code>```

When I save the pdf that opened in my browser it defaults to mpdf.pdf.

Is it possible to change mpdf.pdf to something of my choosing?

I tried

```<code>$payStub->Output('myFileName.pdf');
</code>```

and

```<code>$payStub->Output('myFileName.pdf', 'F');
</code>```

but those want to save it to the server, I'm trying to have it for when the user saves it locally.

答:
Modify mdpdf.php

```<code>form.setAttribute("action", "'._MPDF_URI.'includes/out.php/'.$name.'");
</code>```

for downloading with other name

Body:
I'm currently using mPDF to generate a pdf from HTML (which was generated by PHP).

All works as expected but I'd like to be able to change the default filename.  Currently, I have:

$payStub=new mPDF();
$payStub->SetTitle('My title');
$payStub->WriteHTML($pcTableRows);
$payStub->Output();

When I save the pdf that opened in my browser it defaults to mpdf.pdf.

Is it possible to change mpdf.pdf to something of my choosing?

I tried

$payStub->Output('myFileName.pdf');

and

$payStub->Output('myFileName.pdf', 'F');

but those want to save it to the server, I'm trying to have it for when the user saves it locally.

Body:
Modify mdpdf.php

form.setAttribute("action", "'._MPDF_URI.'includes/out.php/'.$name.'");

for downloading with other name


问:
Adding to an array in main via function argument
I'm not sure if I even worded the title correctly, but basically. I want to know if there is a way to add to the buff array from the hey function using the pointers in the arguments and why does it work if it does?

buf[100].
example:

```<code>int main(){
  char buf[100];
  hey("320244",buf);
  printf("%s", buf);
}
  void hey(char* s, char* result){
  /*
  some code that appends to result using pointers
  do some stuff with s and get the result back in buf without using return.
  */
}
</code>```

答:
If I have understood you correctly you mean the following

```<code>#include <string.h>

//...

void hey(char* s, char* result)
{
    strcpy( result, s );
}
</code>```

Here is a demonstrative program

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

void hey( const char* s, char* result);

int main(void)
{
    char buf[100];

    hey( "320244", buf );

    printf( "%s\n", buf );

    return 0;
}

void hey( const char* s, char* result )
{
    strcpy( result, s );
}
</code>```

Its output is

```<code>320244
</code>```

If the array buf already stores a string then you can append to it a new string. For example

```<code>#include <string.h>

//...

char buf[100] = "ABC";

strcat( buf, "320244" );
</code>```

Take into account that the function hey should be declared before its usage and according to the C Standard the function main shall be declared like

```<code>int main( void )
</code>```

Body:
I'm not sure if I even worded the title correctly, but basically. I want to know if there is a way to add to the buff array from the hey function using the pointers in the arguments and why does it work if it does?

buf[100].
example:

int main(){
  char buf[100];
  hey("320244",buf);
  printf("%s", buf);
}
  void hey(char* s, char* result){
  /*
  some code that appends to result using pointers
  do some stuff with s and get the result back in buf without using return.
  */
}

Body:
If I have understood you correctly you mean the following

#include <string.h>

//...

void hey(char* s, char* result)
{
    strcpy( result, s );
}

Here is a demonstrative program

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

void hey( const char* s, char* result);

int main(void)
{
    char buf[100];

    hey( "320244", buf );

    printf( "%s\n", buf );

    return 0;
}

void hey( const char* s, char* result )
{
    strcpy( result, s );
}

Its output is

320244

If the array buf already stores a string then you can append to it a new string. For example

#include <string.h>

//...

char buf[100] = "ABC";

strcat( buf, "320244" );

Take into account that the function hey should be declared before its usage and according to the C Standard the function main shall be declared like

int main( void )


问:
Python: Matplotlib imshow shift xlabel numbers
Is it possible to shift the x and y axis label numbers for example +2 ? For example i have this image created, but i want that the label numbers begin with 2:

My code for this was :

```<code>jacaardMatrix = 1.662887377173091485e-01    3.432835820895522305e-01    3.568320278503046006e-01
5.065963060686015651e-02    3.160270880361173984e-01    3.374888691006233121e-01
3.093987157034442520e-02    1.802120141342756221e-01    1.748178980228928259e-01

fig2=plt.figure()
plt.title("Radius and FRC Jacaard Values for Scoring System: "+str(i))
plt.xlabel('Radius')
plt.ylabel('FRC Size')
plt.imshow(jacaardMatrix)
</code>```

答:
I believe you can do

```<code>import mathplotlib.pyplot as p
plt.xticks(np.arange(-0.5, 3, 0.5), np.arange(2, 5.5, 0.5))
</code>```

See for example this. Thanks to ImportanceOfBeingErnest for their comment.

Body:
Is it possible to shift the x and y axis label numbers for example +2 ? For example i have this image created, but i want that the label numbers begin with 2:

My code for this was :

jacaardMatrix = 1.662887377173091485e-01    3.432835820895522305e-01    3.568320278503046006e-01
5.065963060686015651e-02    3.160270880361173984e-01    3.374888691006233121e-01
3.093987157034442520e-02    1.802120141342756221e-01    1.748178980228928259e-01

fig2=plt.figure()
plt.title("Radius and FRC Jacaard Values for Scoring System: "+str(i))
plt.xlabel('Radius')
plt.ylabel('FRC Size')
plt.imshow(jacaardMatrix)

Body:
I believe you can do

import mathplotlib.pyplot as p
plt.xticks(np.arange(-0.5, 3, 0.5), np.arange(2, 5.5, 0.5))

See for example this. Thanks to ImportanceOfBeingErnest for their comment.


问:
using .reduce() on an a list of objects
I have this sample data set:

```<code>let list = [
  {'first': 'morgan', 'id': 1},
  {'first': 'eric', 'id': 1},
  {'first': 'brian', 'id': 2 },
  {'first': 'derek', 'id' : 2},
  {'first': 'courtney', 'id': 3},
  {'first': 'eric', 'id': 4},
  {'first': 'jon', 'id':4},
]
</code>```

I am trying to end up with this:

```<code>[[1, [morgan, eric]], [2, [brian, derek]], [3, [courtney]], [4, [eric, jon]]
</code>```

I am using the .reduce() function to map over the list. However, I'm somewhat stuck.

I got this working:

```<code>let b = list.reduce((final_list, new_item) => {
  x = final_list.concat([[new_item.id, [new_item.first]]])
  return x
}, [])
</code>```

However, that flattens out the list into a list of lists of lists, but doesn't combine names that share a similar id.

I tried using .map() the code below does not work

I tried to map over the final_list (which is a list of [id, [names]] looking to see if the id of the new_item exists in the smaller_list and then add new_item.first to the smaller_list[1] (which should be the list of names).

Is this the right approach?

```<code>let b = list.reduce((final_list, new_item) => {
  final_list.map((smaller_list) => {
    if (smaller_list.indexOf((new_item.id)) >=0) {
      smaller_list[1].concat(new_item.first)
      // not sure what to do here...
    } else {
        // not sure what to do here either...
    }

  })
  x = final_list.concat([[item.id, [item.first]]])
  return x
}, [])
</code>```

答:
My solution was to first map over your list and combine the ones with similar ID and then loop over that result in order to change the format to the one requested.

let list = [
  {'first': 'morgan', 'id': 1},
  {'first': 'eric', 'id': 1},
  {'first': 'brian', 'id': 2 },
  {'first': 'derek', 'id' : 2},
  {'first': 'courtney', 'id': 3},
  {'first': 'eric', 'id': 4},
  {'first': 'jon', 'id':4},
]

let temp = [], result = [];

list.map(entry => {
    if(!temp[entry.id]) temp[entry.id] = [entry.first]
    else temp[entry.id].push(entry.first)
})
temp.forEach((names, id) => {
    result.push([id, names])
})

console.log(JSON.stringify(result))```

EDIT: I used an array as temp because the ID is an integer and for the convenience of being able to use a forEach loop. If the key was something else then you would use a Hash table.

Title: using .reduce() on an a list of objects

Body:
I have this sample data set:

let list = [
  {'first': 'morgan', 'id': 1},
  {'first': 'eric', 'id': 1},
  {'first': 'brian', 'id': 2 },
  {'first': 'derek', 'id' : 2},
  {'first': 'courtney', 'id': 3},
  {'first': 'eric', 'id': 4},
  {'first': 'jon', 'id':4},
]

I am trying to end up with this:

[[1, [morgan, eric]], [2, [brian, derek]], [3, [courtney]], [4, [eric, jon]]

I am using the .reduce() function to map over the list. However, I'm somewhat stuck.

I got this working:

let b = list.reduce((final_list, new_item) => {
  x = final_list.concat([[new_item.id, [new_item.first]]])
  return x
}, [])

However, that flattens out the list into a list of lists of lists, but doesn't combine names that share a similar id.

I tried using .map() the code below does not work

I tried to map over the final_list (which is a list of [id, [names]] looking to see if the id of the new_item exists in the smaller_list and then add new_item.first to the smaller_list[1] (which should be the list of names).

Is this the right approach?

let b = list.reduce((final_list, new_item) => {
  final_list.map((smaller_list) => {
    if (smaller_list.indexOf((new_item.id)) >=0) {
      smaller_list[1].concat(new_item.first)
      // not sure what to do here...
    } else {
        // not sure what to do here either...
    }

  })
  x = final_list.concat([[item.id, [item.first]]])
  return x
}, [])

Body:
My solution was to first map over your list and combine the ones with similar ID and then loop over that result in order to change the format to the one requested.

let list = [
  {'first': 'morgan', 'id': 1},
  {'first': 'eric', 'id': 1},
  {'first': 'brian', 'id': 2 },
  {'first': 'derek', 'id' : 2},
  {'first': 'courtney', 'id': 3},
  {'first': 'eric', 'id': 4},
  {'first': 'jon', 'id':4},
]

let temp = [], result = [];

list.map(entry => {
    if(!temp[entry.id]) temp[entry.id] = [entry.first]
    else temp[entry.id].push(entry.first)
})
temp.forEach((names, id) => {
    result.push([id, names])
})

console.log(JSON.stringify(result))

EDIT: I used an array as temp because the ID is an integer and for the convenience of being able to use a forEach loop. If the key was something else then you would use a Hash table.


问:
Vertical UISlider constraints
I am creating a vertical UISlider. I have created the view it is in using all code. (the rest of the storyboard elements are constrained using interface builder)

From what I have read, to create a vertical UISlider you give the UISlider a width and then rotate it. Since the height of the container that the UISlider sits in varies by screen size I do not want to give it a fixed height (width).

This is what I was thinking

```<code>    // Mark: Slider View

    let leftSlider = UISlider()
    let centerSlider = UISlider()
    let rightSlider = UISlider()

    let colorSliders = [leftSlider, centerSlider, rightSlider]

    for slider in colorSliders {

        slider.translatesAutoresizingMaskIntoConstraints = false
        sliderContainer.addSubview(slider)

        let w = sliderContainer.bounds.width
        slider.bounds.size.width = w
        slider.center = CGPoint(x: w/2, y: w/2)
        slider.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI_2))

        slider.value = 0
        slider.minimumValue = 0
        slider.maximumValue = 255

        let sliderTopConstraint = slider.topAnchor.constraint(equalTo: centerHiddenView.bottomAnchor, constant: 5)
        let sliderBottomConstraint = slider.bottomAnchor.constraint(equalTo: sliderContainer.bottomAnchor, constant: 5)

        NSLayoutConstraint.activate([sliderTopConstraint, sliderBottomConstraint])
        slider.backgroundColor = .purple
        slider.isEnabled = true
        slider.isUserInteractionEnabled = true

    }

    let sliderContainerWidth: CGFloat = sliderContainer.frame.width

    let centerSliderHorizontalConstraints = centerSlider.centerXAnchor.constraint(equalTo: sliderContainer.centerXAnchor)

    let widthConstraint = centerSlider.widthAnchor.constraint(equalToConstant: sliderContainerWidth)

    let centerSliderWidthConstraint = centerSlider.widthAnchor.constraint(equalToConstant: 90)

    NSLayoutConstraint.activate([centerSliderHorizontalConstraints, centerSliderWidthConstraint, widthConstraint])
</code>```

But when I run it I get this

which is far better than what I had earlier today. However, I would like the slider to be normal width..and well look normal just vertical

Any ideas on what I missed?
(Oh ignore that little purple offshoot to the left, that is the other 2 sliders that I added but didn't constrain yet.)

答:
(as of July 7, 2017)

```<code>self.customSlider = [[UISlider alloc] init]];
self.customView = [[UIView alloc] init];

//create the custom auto layout constraints that you wish the UIView to have

[self.view addSubview:self.customView];
[self.customView addSubview:self.customSlider];
self.slider.transform = CGAffineTransformMakeRotation(-M_PI_2);

/*Create the custom auto layout constraints for self.customSlider to have these 4 constraints:
    //1. self.customSlider CenterX = CenterX of self.customView
    //2. self.customSlider CenterY = CenterY of self.customView
    //3. self.customSlider width = self.customView height
    //4. self.customSlider height = self.customView width
*/
</code>```

Title: Vertical UISlider constraints

Body:
I am creating a vertical UISlider. I have created the view it is in using all code. (the rest of the storyboard elements are constrained using interface builder)

From what I have read, to create a vertical UISlider you give the UISlider a width and then rotate it. Since the height of the container that the UISlider sits in varies by screen size I do not want to give it a fixed height (width).

This is what I was thinking

    // Mark: Slider View

    let leftSlider = UISlider()
    let centerSlider = UISlider()
    let rightSlider = UISlider()

    let colorSliders = [leftSlider, centerSlider, rightSlider]

    for slider in colorSliders {

        slider.translatesAutoresizingMaskIntoConstraints = false
        sliderContainer.addSubview(slider)

        let w = sliderContainer.bounds.width
        slider.bounds.size.width = w
        slider.center = CGPoint(x: w/2, y: w/2)
        slider.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI_2))

        slider.value = 0
        slider.minimumValue = 0
        slider.maximumValue = 255

        let sliderTopConstraint = slider.topAnchor.constraint(equalTo: centerHiddenView.bottomAnchor, constant: 5)
        let sliderBottomConstraint = slider.bottomAnchor.constraint(equalTo: sliderContainer.bottomAnchor, constant: 5)

        NSLayoutConstraint.activate([sliderTopConstraint, sliderBottomConstraint])
        slider.backgroundColor = .purple
        slider.isEnabled = true
        slider.isUserInteractionEnabled = true

    }

    let sliderContainerWidth: CGFloat = sliderContainer.frame.width

    let centerSliderHorizontalConstraints = centerSlider.centerXAnchor.constraint(equalTo: sliderContainer.centerXAnchor)

    let widthConstraint = centerSlider.widthAnchor.constraint(equalToConstant: sliderContainerWidth)

    let centerSliderWidthConstraint = centerSlider.widthAnchor.constraint(equalToConstant: 90)

    NSLayoutConstraint.activate([centerSliderHorizontalConstraints, centerSliderWidthConstraint, widthConstraint])

But when I run it I get this

which is far better than what I had earlier today. However, I would like the slider to be normal width..and well look normal just vertical

Any ideas on what I missed?
(Oh ignore that little purple offshoot to the left, that is the other 2 sliders that I added but didn't constrain yet.)

Body:
(as of July 7, 2017)

self.customSlider = [[UISlider alloc] init]];
self.customView = [[UIView alloc] init];

//create the custom auto layout constraints that you wish the UIView to have

[self.view addSubview:self.customView];
[self.customView addSubview:self.customSlider];
self.slider.transform = CGAffineTransformMakeRotation(-M_PI_2);

/*Create the custom auto layout constraints for self.customSlider to have these 4 constraints:
    //1. self.customSlider CenterX = CenterX of self.customView
    //2. self.customSlider CenterY = CenterY of self.customView
    //3. self.customSlider width = self.customView height
    //4. self.customSlider height = self.customView width
*/


问:
Proper way to return private object in Python
I'm new to Python (and liking it so far) but have many years experience with OO languages like C++ and C# and consider myself a strong OO designer.

My understanding is that Python does not strictly enforce private object properties, but that by convention people expect that if you name a property with an underscore that they will know not to access it outside the class. OK, fair enough.

My question: if an object contains "private" object and I return it to a caller, should I make a copy so they can't mess it up? Or does Python automatically make a copy?

```<code># My Channel class has a dictionary of capabilities
class Channel(object):
    def __init__(self):
        self._capabilities = dict()
</code>```

If I do the following can the caller mess with my capabilities by messing with the returned dictionary?

```<code>@property
def capabilities(self):
    return self._capabilities
</code>```

Or should I do this and return a copy to protect myself?

```<code>@property
def capabilities(self):
    # I'm assuming that this creates a new copy of the dictionary
    return dict(self._capabilities)
</code>```

I am guessing that Python returns a reference so that the caller can indeed mess with my private dictionary (or list, or whatever) so I better make a copy first.

答:
If you're using Python 3.3 and above, there is a class in the standard library types.MappingProxyType.  Its constructor takes a dictionary and returns a read-only view.  If you return this kind of object, as opposed to a copy of the dictionary, the returned MappingProxyType would raise an exception if client code tried to alter it.

You can also make your class emulate an immutable mapping by inheriting from collections.abc.Mapping and implementing three special methods: __getitem__, __iter__, and __len__.  Then client code could access any item in _capabilities but could not modify it.  A client could even iterate over the whole set.

But Python philosophy ("we're all adults here") says that perhaps it is better to return the dictionary and trust the user's code not to mess with it.  Trying to get Python to emulate C++ is not necessarily the best approach.  As you point out, Python doesn't actually prevent the client from using variables that begin with an underscore.

Body:
I'm new to Python (and liking it so far) but have many years experience with OO languages like C++ and C# and consider myself a strong OO designer.

My understanding is that Python does not strictly enforce private object properties, but that by convention people expect that if you name a property with an underscore that they will know not to access it outside the class. OK, fair enough.

My question: if an object contains "private" object and I return it to a caller, should I make a copy so they can't mess it up? Or does Python automatically make a copy?

# My Channel class has a dictionary of capabilities
class Channel(object):
    def __init__(self):
        self._capabilities = dict()

If I do the following can the caller mess with my capabilities by messing with the returned dictionary?

@property
def capabilities(self):
    return self._capabilities

Or should I do this and return a copy to protect myself?

@property
def capabilities(self):
    # I'm assuming that this creates a new copy of the dictionary
    return dict(self._capabilities)

I am guessing that Python returns a reference so that the caller can indeed mess with my private dictionary (or list, or whatever) so I better make a copy first.


问:
Wasm access DOM
Is there any way to get read/write access to DOM and/or the WebAPIs(i.e. fullscreen API) without JavaScript?

I'm trying to build a basic application in C(C source being actually the result of transpilation from a GC language). The app I'm building will run as Desktop app(it's not meant to run in "real" browsers yet) so I can tweak the environment(i.e. the layout engine) if necessary.

答:
WebAssembly folks haven't any strong idea yet for what JS objects in WebAssembly are going to look like, it seems.

I'd look through PR #1080, which is about the Garbage Collection spec being spun off into it's own repo for now. But while that's happening they're removing the only mentions of the web platform & interop with JS objects that exist in the spec, which is described as:

It's more aspirational that concrete,

ContentLicense: CC BY-SA 4.0

Title: Wasm access DOM


答:
It's probably easiest to write a plain loop for this:</p>

```<code>let final_list = []
for (k = 0; k < list.length; k += 2) {
    let item1 = list[k]
    let item2 = list[k + 1]
    final_list.push([item1.id, [item1.first, item2.first]])
}
</code>```

Title: using .reduce() on an a list of objects

Body:
It's probably easiest to write a plain loop for this:

let final_list = []
for (k = 0; k < list.length; k += 2) {
    let item1 = list[k]
    let item2 = list[k + 1]
    final_list.push([item1.id, [item1.first, item2.first]])
}


问:
System.out.print is overlapping the questions why?
My problem is when i run the program it runs all the System.out.print right but when i run
it for the second student some of it overlaps like so:

```<code>"Enter the second student's name: Enter the student's score: "
</code>```

instead of

```<code>"Enter the second students's name: "

"Enter the student's score: "
</code>```

I also can not input data into the System.out.print method of the second student

My main code where the error is:

```<code>System.out.print("Enter the first student's name: ");
name = reader.nextLine();
student1.setName(name);
for (int i = 1; i <= 3; i++){
    System.out.print("Enter the students's score: ");
    score = reader.nextInt();
    student1.setScore(i, score);
}

System.out.print("Enter the second student's name: "); //overlaps(stays on same line)
//also wont let me enter data here
name = reader.nextLine();
student2.setName(name);
for (int i = 1; i <= 3; i++){
    System.out.print("Enter the students's score: "); //program skips to here to input
//data
    score = reader.nextInt();
    student2.setScore(i, score);
}
</code>```

the part that deals with the error from the class is as follows

```<code>public void setName(String nm){
    name = nm;
}
</code>```

答: You should call println() to print a newline character, after reading the input.

Body:
My problem is when i run the program it runs all the System.out.print right but when i run
it for the second student some of it overlaps like so:

"Enter the second student's name: Enter the student's score: "

instead of

"Enter the second students's name: "

"Enter the student's score: "

I also can not input data into the System.out.print method of the second student

My main code where the error is:

System.out.print("Enter the first student's name: ");
name = reader.nextLine();
student1.setName(name);
for (int i = 1; i <= 3; i++){
    System.out.print("Enter the students's score: ");
    score = reader.nextInt();
    student1.setScore(i, score);
}

System.out.print("Enter the second student's name: "); //overlaps(stays on same line)
//also wont let me enter data here
name = reader.nextLine();
student2.setName(name);
for (int i = 1; i <= 3; i++){
    System.out.print("Enter the students's score: "); //program skips to here to input
//data
    score = reader.nextInt();
    student2.setScore(i, score);
}

the part that deals with the error from the class is as follows

public void setName(String nm){
    name = nm;
}


问:
how to find duplicate rows in postgres?
I feel weeks ago I asked a question about counting identical rows in one dataset. This is an answer I received:

```<code>select count(*), a_dttm, b_dttm, c_dttm
from data
group by a_ddtm, b_dttm, c_dttm;
</code>```

I know that there are duplicates in this other dataset and they're messing up my count. As of right now, I know what id is used multiple times, but it doesn't necessarily mean it that those rows are duplicated.

```<code>select id, count(*) as count
from (
select *
from data
where date >= '2016-01-01' and date <= '2016-12-31'
) as a
group by id
having count(*) >= 2
order by count desc
</code>```

My question is how can I select all the rows that are completely identical in my dataset? Would I write a subquery for each column or select * ?

答:
If I were to find a solution in finding duplicate values on a script, i do a count(*) and do a group by function to count the number of duplicates. which is the answer you got previously.

To answer your question, I would suggest to add the 'date' on your group by and select as it is an indicator for "uniqueness" for the field that you need to use.

I simply would find or create a "Primary Index" to make sure that all the data used is unique.

however, if you dont want to mess your numbers, I normally use DISTINCT as an easy way remove the duplicates on that table. see reference below:
http://www.postgresqltutorial.com/postgresql-select-distinct/

Title: how to find duplicate rows in postgres?

Body:
I feel weeks ago I asked a question about counting identical rows in one dataset. This is an answer I received:

select count(*), a_dttm, b_dttm, c_dttm
from data
group by a_ddtm, b_dttm, c_dttm;

I know that there are duplicates in this other dataset and they're messing up my count. As of right now, I know what id is used multiple times, but it doesn't necessarily mean it that those rows are duplicated.

select id, count(*) as count
from (
select *
from data
where date >= '2016-01-01' and date <= '2016-12-31'
) as a
group by id
having count(*) >= 2
order by count desc

My question is how can I select all the rows that are completely identical in my dataset? Would I write a subquery for each column or select * ?


问:
TeraData on AWS: *** Warning: RDBMS CRASHED OR SESSIONS RESET. RECOVERY IN PROGRESS
I'm getting this error while trying to login to a Teradata instance running on AWS:

```<code>ec2-user@ip-xx-x-xx-xx:~> bteq

Teradata BTEQ 15.10.01.09 for LINUX. PID: 7460
Copyright 1984-2016, Teradata Corporation. ALL RIGHTS RESERVED.
Enter your logon or BTEQ command:
.logon 127.0.0.1/dbc;

.logon 127.0.0.1/dbc
Password:

*** Warning: RDBMS CRASHED OR SESSIONS RESET.  RECOVERY IN PROGRESS.
*** Warning: Exiting because of three BREAKs!

*** Exiting BTEQ...
</code>```

I've tried to manually restart the instance by running ~/etc/init.d/tpa start but got the error:

```<code>ec2-user@ip-xx-x-xx-xx:~> /etc/init.d/tpa start
Teradata Database Initiator service is starting...
Teradata Database Initiator service failed with 4 exit code
</code>```

答:
How I eventually resolved this problem was to create a new key-pair on AWS, which I then used to re-build Teradata on EC2. Why the former key-pair kept on throwing the error in the question is unknown to me.

Hope this helps someone else.

Body:
I'm getting this error while trying to login to a Teradata instance running on AWS:

ec2-user@ip-xx-x-xx-xx:~> bteq

Teradata BTEQ 15.10.01.09 for LINUX. PID: 7460
Copyright 1984-2016, Teradata Corporation. ALL RIGHTS RESERVED.
Enter your logon or BTEQ command:
.logon 127.0.0.1/dbc;

.logon 127.0.0.1/dbc
Password:

*** Warning: RDBMS CRASHED OR SESSIONS RESET.  RECOVERY IN PROGRESS.
*** Warning: Exiting because of three BREAKs!

*** Exiting BTEQ...

I've tried to manually restart the instance by running ~/etc/init.d/tpa start but got the error:

ec2-user@ip-xx-x-xx-xx:~> /etc/init.d/tpa start
Teradata Database Initiator service is starting...
Teradata Database Initiator service failed with 4 exit code


问:
Need help understanding how this grid works
Inside the for loop you have a loop for "x" and one for "y". I don't get why you need both for this to work? Why doesn't one of the loops just keep appending "squares" until the "container" is full?</p>

```<code>#JQUERY
function makeGrid() {
   for (var x = 0; x < numberSquares; x++) {
      for (var y = 0; y < numberSquares; y++) {
          $("<div class='square'></div>").appendTo('.container');
      }
   }
   $('.square').css({'width': squareSize, 'height': squareSize});
}
</code>```

答:
While this could be done in a single loop in your above example, I believe the primary reason that it was done in two loops here is for adaptability. Consider a use-case where the grid is not a perfect square. You could easily swap out numberSquares in the two loops for variables that define the width and height respectively. You also have x and y defined separately for exactly this scenario!

As a secondary reason, I'd say that using two loops provides greater clarity. If this was a single loop, you'd need to 'remember' the total number of squares yourself. For example, if you had a 13x13 grid, numSquares would need to be 169 -- much more difficult to remember than a 'width' of 13 for a perfect square, which can be re-used for both the width and height.

Hope this helps! :)

Body:
Inside the for loop you have a loop for "x" and one for "y". I don't get why you need both for this to work? Why doesn't one of the loops just keep appending "squares" until the "container" is full?

#JQUERY
function makeGrid() {
   for (var x = 0; x < numberSquares; x++) {
      for (var y = 0; y < numberSquares; y++) {
          $("

").appendTo('.container');
      }
   }
   $('.square').css({'width': squareSize, 'height': squareSize});
}


问:
My JavaScript file isn't loading in WordPress
I am trying to run a lightbox plugin in WordPress. For some reason it will not load and I have the correct file path. Normally I use the cdn version of files, but there is not a such version around and I have to load it locally. I also have some violations. I have no idea what is going on and why I am receiving the error.

functions.php

```<code>function nutrition_club_theme_script_enqueue() {

 wp_enqueue_script('jquery', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js');

    wp_enqueue_script('jquery-tools', get_template_directory_uri() .'/js/jquery.tools.min.js', array('jquery'), '', true);

    wp_enqueue_script('jquery-portfoliolightbox', get_template_directory_uri() .'/js/jquery.portfoliolightbox.js', '', '', true);

    wp_enqueue_script('jquery-magnific-popup', 'https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/jquery.magnific-popup.min.js');

    wp_enqueue_script('customjs', get_template_directory_uri() . '/js/nutrition_club_theme.js', array('jquery'), '4.8', false);

    wp_enqueue_script('owljs', 'https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.min.js');

    wp_enqueue_script('bootstrapjs', get_template_directory_uri() . '/js/bootstrap.min.js', array(), '3.3.7', true);

    wp_enqueue_script('popup-galleryjs', get_template_directory_uri() . '/js/popup-gallery.js', array(), '', true);

    wp_enqueue_script('wowjs', 'https://cdnjs.cloudflare.com/ajax/libs/wow/1.1.2/wow.min.js');

}

add_action(wp_enqueue_scripts, 'nutrition_club_theme_script_enqueue');
</code>```

custom.js

```<code>     jQuery(".service-popup").lightBox({
    imgpath: 'https://unsplash.it/1200/900?image=839',
    title: 'Your Title',
    text: 'Enter any text',
    link: ['http://www.link1.com', 'http://www.link2.com'],
    linkText: ['Site 1 Text', 'Link 2 text']
});
</code>```

Chrome error

```<code>Uncaught TypeError: jquery-3.2.1.min.js?ver=3.2.1:2
jQuery(...).lightBox is not a function
        at HTMLDocument.<anonymous> (nutrition_club_theme.js?ver=4.8:81)
        at j (jquery-3.2.1.min.js?ver=3.2.1:2)
        at k (jquery-3.2.1.min.js?ver=3.2.1:2)
    (anonymous) @ nutrition_club_theme.js?ver=4.8:81
    j @ jquery-3.2.1.min.js?ver=3.2.1:2
    k @ jquery-3.2.1.min.js?ver=3.2.1:2
</code>```

Violations

```<code>[Violation] Added non-passive event listener to a scroll-blocking 'touchstart' event. Consider marking event handler as 'passive' to make the page more responsive.
jquery-3.2.1.min.js?ver=3.2.1:2 [Violation] 'setTimeout' handler took 341ms
[Violation] Forced reflow while executing JavaScript took 197ms
[Violation] Forced reflow while executing JavaScript took 65ms
</code>```

答:
You are loading custom.js before the Lightbox script.

Try adding extra dependencies to your enqueue

```<code>wp_enqueue_script('customjs', get_template_directory_uri() . '/js/nutrition_club_theme.js', array('jquery', 'jquery-portfoliolightbox', 'jquery-magnific-popup'), '4.8', false);
</code>```

Or whatever the script adding the lightBox is. You should always make sure you set dependencies correctly to avoid this.

NOTE: you should also make sure that if there is an enqueued script ( like the lightBox one ) that requires jQuery, has it set as a dependency.

Body:
I am trying to run a lightbox plugin in WordPress. For some reason it will not load and I have the correct file path. Normally I use the cdn version of files, but there is not a such version around and I have to load it locally. I also have some violations. I have no idea what is going on and why I am receiving the error.

functions.php

function nutrition_club_theme_script_enqueue() {

 wp_enqueue_script('jquery', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js');

    wp_enqueue_script('jquery-tools', get_template_directory_uri() .'/js/jquery.tools.min.js', array('jquery'), '', true);

    wp_enqueue_script('jquery-portfoliolightbox', get_template_directory_uri() .'/js/jquery.portfoliolightbox.js', '', '', true);

    wp_enqueue_script('jquery-magnific-popup', 'https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/jquery.magnific-popup.min.js');

    wp_enqueue_script('customjs', get_template_directory_uri() . '/js/nutrition_club_theme.js', array('jquery'), '4.8', false);

    wp_enqueue_script('owljs', 'https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.min.js');

    wp_enqueue_script('bootstrapjs', get_template_directory_uri() . '/js/bootstrap.min.js', array(), '3.3.7', true);

    wp_enqueue_script('popup-galleryjs', get_template_directory_uri() . '/js/popup-gallery.js', array(), '', true);

    wp_enqueue_script('wowjs', 'https://cdnjs.cloudflare.com/ajax/libs/wow/1.1.2/wow.min.js');

}

add_action(wp_enqueue_scripts, 'nutrition_club_theme_script_enqueue');

custom.js

     jQuery(".service-popup").lightBox({
    imgpath: 'https://unsplash.it/1200/900?image=839',
    title: 'Your Title',
    text: 'Enter any text',
    link: ['http://www.link1.com', 'http://www.link2.com'],
    linkText: ['Site 1 Text', 'Link 2 text']
});

Chrome error

Uncaught TypeError: jquery-3.2.1.min.js?ver=3.2.1:2
jQuery(...).lightBox is not a function
        at HTMLDocument.<anonymous> (nutrition_club_theme.js?ver=4.8:81)
        at j (jquery-3.2.1.min.js?ver=3.2.1:2)
        at k (jquery-3.2.1.min.js?ver=3.2.1:2)
    (anonymous) @ nutrition_club_theme.js?ver=4.8:81
    j @ jquery-3.2.1.min.js?ver=3.2.1:2
    k @ jquery-3.2.1.min.js?ver=3.2.1:2

Violations

[Violation] Added non-passive event listener to a scroll-blocking 'touchstart' event. Consider marking event handler as 'passive' to make the page more responsive.
jquery-3.2.1.min.js?ver=3.2.1:2 [Violation] 'setTimeout' handler took 341ms
[Violation] Forced reflow while executing JavaScript took 197ms
[Violation] Forced reflow while executing JavaScript took 65ms

Body:
You are loading custom.js before the Lightbox script.

Try adding extra dependencies to your enqueue

wp_enqueue_script('customjs', get_template_directory_uri() . '/js/nutrition_club_theme.js', array('jquery', 'jquery-portfoliolightbox', 'jquery-magnific-popup'), '4.8', false);

Or whatever the script adding the lightBox is. You should always make sure you set dependencies correctly to avoid this.

NOTE: you should also make sure that if there is an enqueued script ( like the lightBox one ) that requires jQuery, has it set as a dependency.


问:
Validating TinyMCE HTML code using W3C
I am trying to validate a tinymce generated HTML code but it appears W3C only accept url or files as an input. Any suggestion how do I validate tinymce code?</p>

答:
If you like to implement the validation into your application, use your own validator, for example tidy.

This should be much faster  than sending data across the world, and easier too, because you dont have to parse the response of the w3c-validator.

Title: Validating TinyMCE HTML code using W3C


问:
C++ support on Visual Studio Code
I've installed Visual Studio Code and a number of plugins for C++ development (C/C++, CMake, Doxygen, LLDB Debugger) but I can't seem to make this work. I can't refactor, auto-complete has no clue where to look for options and syntax highlight could be much better.

Are there any configuration options I'm missing or is this just a glorified text editor?

答:
Visual Studio Code is a Text Editor, which is available on Windows, Linux, and OSX. It has several plugins which allow you to get some cool features, you can find a lot of documentation online.

Visual Studio (or Visual C++) is an IDE (Integrated Development Environment). It is available on Windows and on OSX (for C# only for now if I remember). It provides a lot of useful Integrated tools such has syntax highlighting, auto completion, compiler and debugger, Intellisense, etc..

I really think you are mistaking those two, tell me if I'm wrong.

Title: C++ support on Visual Studio Code


问:
Can node prevent an infinite loop?
Since node runs a single threaded model with event looping I wonder how node prevents the entire application to fail if you write a code like:

```<code>while(true){ doSomething()}
</code>```

where doSomething is a synchronous function (a blocking piece of code)

Note that it doesn't make any sense to write a function like doSomething but nothing prevents you to make a mistake

The problem here is that, since it's single threaded, it won't allow any other parts of the application to run (for instance, a web server would stop accepting new connections) because this function would never end. In a Multi threaded environment you would loose this thread alone.

Is there anything that node can do for you to prevent these kind of problems?

答:
I wonder how node prevents the entire application to fail if you write an infinite loop

nodejs does not prevent such an infinite loop.  It will just run that loop forever or until some resource is exhausted (if the loop is consuming some resource like memory).

If node can't prevent this kind of situations, is this a design fault or there's no way to prevent these kind of problems?

I don't think most people consider it a design fault - though that's purely an opinion and different people may have a different opinion.  It is a consequence of the way nodejs was designed which has many other benefits.

The only way to prevent such problems is to not write faulty code that does this.  Honestly, it's not too hard to avoid writing this type of code once you're aware that it's an issue to avoid.

The problem here is that, since it's single threaded, it won't allow any other parts of the application to run (for instance, a web server would stop accepting new connections) because this function would never end. In a Multi threaded environment you would loose this thread alone

Correct.  This is something you learn when coding in nodejs.  I've never found it a hard thing to avoid.  nodejs is an single-threaded event driven system, not a multi-threaded system.  As such, you program with events, not long running loops that poll or check conditions.  It is a rather straightforward concept to learn and use once you understand this is how nodejs works.  It is different than some other environments.  But, how to use asynchronous operations in nodejs is just something you have to learn to program in that environment.  It's not avoidable and is just part of the character of nodejs.  There is no way that nodejs could have the type of architecture it has without having to learn this to program in it.  If you want a different architecture (for whatever personal reason), then pick a different environment, not nodejs.

The single-threadedness massively simplifies many other things (far, far fewer opportunities for race conditions) and improves scalability in some circumstances (with asynchronous I/O) vs. threaded environments.  For situations where you want multiple CPUs to be applied to your problem, it is generally straightforward in node.js to either use the built-in clustering module or to fire up worker processes and feed them work.  Data is often shared among multiple processes via some sort of database (either file-based or RAM-based) that handles much of the multi-process synchronization for you.

Title: Can node prevent an infinite loop?

Body:
Since node runs a single threaded model with event looping I wonder how node prevents the entire application to fail if you write a code like:

while(true){ doSomething()}

where doSomething is a synchronous function (a blocking piece of code)

Note that it doesn't make any sense to write a function like doSomething but nothing prevents you to make a mistake

The problem here is that, since it's single threaded, it won't allow any other parts of the application to run (for instance, a web server would stop accepting new connections) because this function would never end. In a Multi threaded environment you would loose this thread alone.

Is there anything that node can do for you to prevent these kind of problems?


问:
Loading files in Prolog
I am going through a Prolog tutorial.  It is telling me I can load other prolog files by typing:

```<code>[filename].
</code>```

but every time I try this am getting

```<code>ERROR: load_files/2: Arguments are not sufficiently instantiated.
</code>```

The file is in the same directory as the one am working in.

Here is a copy of the entire query and error:

```<code>12 ?- [KB5].

ERROR: load_files/2: Arguments are not sufficiently instantiated
</code>```

What am I doing wrong?

答:
```<code>$ cat junk.pl
test(ok).

$ prolog
Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 5.8.0)
Copyright (c) 1990-2009 University of Amsterdam.
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.

For help, use ?- help(Topic). or ?- apropos(Word).

?- [junk].
% junk compiled 0.00 sec, 24 bytes
true.
</code>```

It seems to work fine for me.  Of course I'm using an atom for my file name, not a variable.  (KB5 is a variable name, not an atom.)  First try ['KB5'] and see if that helps.  Next try [kb5] and see if that helps.  Finally try an absolute minimal example like the one I provided and see if you can load that way.

Edited to add:

```<code>$ cp junk.pl JUNK.pl
$ prolog
Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 5.8.0)
Copyright (c) 1990-2009 University of Amsterdam.
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.

For help, use ?- help(Topic). or ?- apropos(Word).

?- [JUNK].
ERROR: load_files/2: Arguments are not sufficiently instantiated
?- ['JUNK'].
% JUNK compiled 0.00 sec, 1,656 bytes
true.
</code>```

It looks like the atom problem indeed.  Use ['KB5'] and your error will probably go away.

Title: Loading files in Prolog

Body:
I am going through a Prolog tutorial.  It is telling me I can load other prolog files by typing:

[filename].

but every time I try this am getting

ERROR: load_files/2: Arguments are not sufficiently instantiated.

The file is in the same directory as the one am working in.

Here is a copy of the entire query and error:

12 ?- [KB5].

ERROR: load_files/2: Arguments are not sufficiently instantiated

What am I doing wrong?

Body:
$ cat junk.pl
test(ok).

$ prolog
Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 5.8.0)
Copyright (c) 1990-2009 University of Amsterdam.
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.

For help, use ?- help(Topic). or ?- apropos(Word).

?- [junk].
% junk compiled 0.00 sec, 24 bytes
true.

It seems to work fine for me.  Of course I'm using an atom for my file name, not a variable.  (KB5 is a variable name, not an atom.)  First try ['KB5'] and see if that helps.  Next try [kb5] and see if that helps.  Finally try an absolute minimal example like the one I provided and see if you can load that way.

Edited to add:

$ cp junk.pl JUNK.pl
$ prolog
Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 5.8.0)
Copyright (c) 1990-2009 University of Amsterdam.
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to redistribute it under certain conditions.
Please visit http://www.swi-prolog.org for details.

For help, use ?- help(Topic). or ?- apropos(Word).

?- [JUNK].
ERROR: load_files/2: Arguments are not sufficiently instantiated
?- ['JUNK'].
% JUNK compiled 0.00 sec, 1,656 bytes
true.

It looks like the atom problem indeed.  Use ['KB5'] and your error will probably go away.


问:
Merge two lists and apply custom function while merging
So I have two lists which has similar properties for each item in the list. Each item is of the format -

```<code>public class ZoneOccupancy
{
    public virtual string ZoneId { get; set; }
    public virtual int CurrentOccupancy { get; set; }
}

ZoneId | CurrentOccupancy
</code>```

One list would be like -

```<code>ZoneId | CurrentOccupancy

110      2
111      1
115      3
</code>```

Another list would be like -

```<code>ZoneId | CurrentOccupancy

110      1
111      1
116      3
</code>```

After merging what I want is something like -

```<code>ZoneId | CurrentOccupancy

110      3
111      2
115      3
116      3
</code>```

So i want the duplicate items from the list to merge into one but in the process, the count to be added.

Edit:

```<code>list.Union(ParkingTagTicketQueryResult, ZoneComparer.Instance)
                         .GroupBy(z => z.ZoneId)
                         .Select(z => new ZoneOccupancy
                                        {
                                            ZoneId = z.First().ZoneId,
                                            CurrentOccupancy = z.Sum(row => row.CurrentOccupancy)

public class ZoneComparer : IEqualityComparer<ZoneOccupancy>
{
     public static readonly ZoneComparer Instance = new ZoneComparer();

     // We don't need any more instances
     private ZoneComparer() { }

     public int GetHashCode(ZoneOccupancy z)
     {
          return z.ZoneId.GetHashCode();
     }

     public bool Equals(ZoneOccupancy z1, ZoneOccupancy z2)
     {
          if (Object.ReferenceEquals(z1, z2))
          {
              return true;
          }

          if (Object.ReferenceEquals(z1, null) ||
              Object.ReferenceEquals(z2, null))
          {
              return false;
          }

          return z1.ZoneId.Equals(z2.ZoneId);
      }
</code>```

}

答:
First let's define a class to hold our data:

```<code>class Datum
{
    public string Zone { get; set; }
    public int Count { get; set; }
}
</code>```

And populate the two lists:

```<code>        var list1 = new List<Datum>();
        list1.Add(new Datum { Zone = "110", Count = 2 });
        list1.Add(new Datum { Zone = "111", Count = 1 });
        list1.Add(new Datum { Zone = "115", Count = 3 });

        var list2 = new List<Datum>();
        list1.Add(new Datum { Zone = "110", Count = 1 });
        list1.Add(new Datum { Zone = "111", Count = 1 });
        list1.Add(new Datum { Zone = "116", Count = 3 });
</code>```

To join the two lists, we need to concatenate them:

```<code>        var list3 = list1.Concat(list2);
</code>```

Then we need to group the rows by Zone:

```<code>        var list3 = list1.Concat(list2)
                         .GroupBy(a => a.Zone);
</code>```

This will return a list of IGrouping instances, which we can use to get the Zone (the unique key) and apply aggregate functions on the remaining fields. In our case we want the Sum of the counts.

```<code>        var list3 = list1.Concat(list2);
                         .GroupBy(a => a.Zone)
                         .Select(group => new Datum
                                          {
                                              Zone = group.Key,
                                              Count = group.Sum(row => row.Count)
                                          }
                                );
</code>```

When we dump list3 we'll see it contains the results you were looking for:

```<code>        foreach (var item in list3)
        {
            Console.WriteLine(string.Format("Zone: {0} Count: {1}", item.Zone, item.Count));
        }
</code>```

Zone: 110 Count: 3

Zone: 111 Count: 2

Zone: 115 Count: 3

Zone: 116 Count: 3

I did not see anything in your question that called for a "custom function" but it would be easy to add here in any of the LINQ statements.

Body:
So I have two lists which has similar properties for each item in the list. Each item is of the format -

public class ZoneOccupancy
{
    public virtual string ZoneId { get; set; }
    public virtual int CurrentOccupancy { get; set; }
}

ZoneId | CurrentOccupancy

One list would be like -

ZoneId | CurrentOccupancy

110      2
111      1
115      3

Another list would be like -

ZoneId | CurrentOccupancy

110      1
111      1
116      3

After merging what I want is something like -

ZoneId | CurrentOccupancy

110      3
111      2
115      3
116      3

So i want the duplicate items from the list to merge into one but in the process, the count to be added.

Edit:

list.Union(ParkingTagTicketQueryResult, ZoneComparer.Instance)
                         .GroupBy(z => z.ZoneId)
                         .Select(z => new ZoneOccupancy
                                        {
                                            ZoneId = z.First().ZoneId,
                                            CurrentOccupancy = z.Sum(row => row.CurrentOccupancy)

public class ZoneComparer : IEqualityComparer<ZoneOccupancy>
{
     public static readonly ZoneComparer Instance = new ZoneComparer();

     // We don't need any more instances
     private ZoneComparer() { }

     public int GetHashCode(ZoneOccupancy z)
     {
          return z.ZoneId.GetHashCode();
     }

     public bool Equals(ZoneOccupancy z1, ZoneOccupancy z2)
     {
          if (Object.ReferenceEquals(z1, z2))
          {
              return true;
          }

          if (Object.ReferenceEquals(z1, null) ||
              Object.ReferenceEquals(z2, null))
          {
              return false;
          }

          return z1.ZoneId.Equals(z2.ZoneId);
      }

}

Body:
First let's define a class to hold our data:

class Datum
{
    public string Zone { get; set; }
    public int Count { get; set; }
}

And populate the two lists:

        var list1 = new List<Datum>();
        list1.Add(new Datum { Zone = "110", Count = 2 });
        list1.Add(new Datum { Zone = "111", Count = 1 });
        list1.Add(new Datum { Zone = "115", Count = 3 });

        var list2 = new List<Datum>();
        list1.Add(new Datum { Zone = "110", Count = 1 });
        list1.Add(new Datum { Zone = "111", Count = 1 });
        list1.Add(new Datum { Zone = "116", Count = 3 });

To join the two lists, we need to concatenate them:

        var list3 = list1.Concat(list2);

Then we need to group the rows by Zone:

        var list3 = list1.Concat(list2)
                         .GroupBy(a => a.Zone);

This will return a list of IGrouping instances, which we can use to get the Zone (the unique key) and apply aggregate functions on the remaining fields. In our case we want the Sum of the counts.

        var list3 = list1.Concat(list2);
                         .GroupBy(a => a.Zone)
                         .Select(group => new Datum
                                          {
                                              Zone = group.Key,
                                              Count = group.Sum(row => row.Count)
                                          }
                                );

When we dump list3 we'll see it contains the results you were looking for:

        foreach (var item in list3)
        {
            Console.WriteLine(string.Format("Zone: {0} Count: {1}", item.Zone, item.Count));
        }

Zone: 110 Count: 3

Zone: 111 Count: 2

Zone: 115 Count: 3

Zone: 116 Count: 3

I did not see anything in your question that called for a "custom function" but it would be easy to add here in any of the LINQ statements.


问:
How I can log all nodejs messages showed on console to syslog in ubuntu?
I am new to nodejs and syslog functionality.
The message generated by nodejs such as error, or info are not getting logged in syslog.
I want to log all the message generated by nodejs and displayed on the terminal to syslog.
For this what changes I need to do in syslog.conf file?
Note: I dont want to use Winston, loggly or log4s</p>

答:
I also wanted console messages from a Node server written to syslog, without having to use a specific library within my code. The quickest way seems to be redirecting the output on the terminal:

```<code>nodejs ~/myapp.js 2>&1 | logger &
</code>```

Or if the app is launched from a more complex bash script, then entire output of the script can be redirected to syslog by adding this at the top:

```<code>#!/bin/bash
exec 1> >(logger -s -t $(basename $0)) 2>&1
# ...
</code>```

Body:
I also wanted console messages from a Node server written to syslog, without having to use a specific library within my code. The quickest way seems to be redirecting the output on the terminal:

nodejs ~/myapp.js 2>&1 | logger &

Or if the app is launched from a more complex bash script, then entire output of the script can be redirected to syslog by adding this at the top:

#!/bin/bash
exec 1> >(logger -s -t $(basename $0)) 2>&1
# ...


问:
Core Data - Relationships between Multiple Core Data Models

Platform

iOS 10, Xcode 8.3.3

Background

I have built a Notes application that takes advantage of Core Data and I'd like to use this app in my next application, which will also use Core Data. For simplicity, lets call my next application, "ListApp", and my notes application, "NotesApp". This ListApp has list items each of which can have one or more notes.

Here's what I've done so far:

Removed all unnecessary files from the NotesApp and compiled a "NotesApp Framework".

Linked the NotesApp Framework to the ListApp.

Designed the Core Data Model for ListApp. Specifically, I created an entity called "ListItem" and an entity called "Note". The ListItem has a to-many relationship with the Note (one list item can have multiple notes). The Note entity contains a "noteID" field to reference the note in the NotesApp model and, of course, the inverse relationship.

Problem

I need to form a "relationship" between an entity in the ListApp model and an entity in the NotesApp model.

I've researched configurations and that seems to be more for storing objects in the same model to different persistent stores unless there's something I'm missing. So, that doesn't help.

Then, I found that fetched properties can be used to form weak relationships between multiple stores. So, that doesn't help either.

Next, I found in the documentation that there's a method called NSManagedObjectModel.mergedModel(from:) so I'm assuming this is possible. Or maybe that's only for migration?

That's where I'm stuck.

Reason

I'd rather not redesign everything in the NotesApp model in to the ListApp model. I prefer to keep everything separate.

Questions

Is there a way to form a relationship between two entities in different models? Should I just add a function in the ListItem entity class to fetch the notes in the NotesApp model manually? Am I even going down the right path or is there a better option?

NOTE: What I mean by "relationship" is the ability to call on a property in the ListItem entity to fetch the notes and somehow "relate" specific notes to a specific ListItem.

P.S. If you know of any pitfalls, have any general advice, or know of any reading material please feel free to let me know.

Also, I've been researching this topic for a couple of hours and I can't seem to find anything about it. I'm assuming that's either because it's not possible, it's a terrible practice, or I'm not using the right keywords.

If anyone needs any more information feel free to let me know!

答:
I think you're saying your bundle will have one model that contains the List entity and another that contains the Note entity.  You can merge and tweak managed object models, as you suggested, and use the resulting managed object model which you have in code.

If you're creating your Core Data stack in code (that is, you are not using the new NSPersistentContainer), it is easy to splice in a custom managed object model.

If you are using NSPersistentContainer, you'd have to subclass it and override managedObjectModel().  I can't find any documentation saying you can't do that, but I wouldn't bet on that.

If you're document-based, overriding UIDocument's managedObjectModel should work.

To create your custom managed object model, merge your models using NSManagedObjectModel.mergedModel(from:).  Then, get the Note and List entity decriptions, get the properties of each, mutate, add your new relationships, then set them back into the model.  You would only do this on the first run; cache your custom managed model to a ivar for subsequent runs.

Hmmmm.  What I've just described, essentially tearing apart, tweaking and reassembling that managed object model, is going to be quite a few lines of code.  If this is a really just a simple "notes and lists" app, and if these are the only these two entities, it would probably be less code to ditch those .mom files and create the whole managed object model from scratch, in code.  It's not that hard.  Put on your Objective-C glasses and look at the managedObjectModel() function in main.m of Apple's old Core Data Utility sample project.


问:
addEventListener for the same event
So I have a few div tags that I have currently hidden, and I want to display them one after the other by hitting the enter key.

What I want to happen: I hit enter and the first div tag is revealed, and then I hit enter a second time to see the second div tag.

What is happening instead: I hit enter once and both div tags show up.

In this case, the first div tag I want to reveal is "intro", and the second is "body". I am running this website on jsbin, and I am using chrome, if that helps.

This is my JavaScript:

```<code>//***********************************************************

//  BODY MODULE

var bodyController = (function(){
  var enterBool;

  var reveal = function(){
    if(enterBool){
      document.getElementById("evidence").style.display = "block";
      enterBool = false;
    }
  };

  var enterListen = function(){
    document.addEventListener("keydown", function(event){
      if(event.keyCode === 13){
        document.addEventListener("keyup", function(event){
          if(event.keyCode === 13){
            enterBool = true;
            reveal();
          }
        });
      }
    });
  };

  return{
    enterBoolBody: enterBool,
    enterListenBody: function(){
      enterListen();
    }
  }
})();

//***********************************************************

//  INTRO MODULE

var introController = (function(){
  var enterBool;

  var reveal = function(){
    if(enterBool){
      document.getElementById("body").style.display = "block";
      enterBool = false;
    }
  };

  var enterListen = function(){
    document.addEventListener("keydown", function(event){
      if(event.keyCode === 13){
        document.addEventListener("keyup", function(event){
          if(event.keyCode === 13){
            enterBool = true;
            reveal();
          }
        });
      }
    });
  };

  return{
    enterBoolIntro: enterBool,
    enterListenIntro: function(){
      enterListen();
    }
  }
})();

 //***********************************************************

 //  CONTROL MODULE

 var controller = (function(introCtrl, bodyCtrl, evidenceCtrl, infoCtrl,
 conclusionCtrl){
  var eventListeners = function(){
     introCtrl.enterListenIntro();
     bodyCtrl.enterListenBody();
  };

  return{
    init: function(){
      eventListeners();
    }
  }
 })(introController, bodyController, evidenceController,
    infoController, conclusionController);

 //***********************************************************

 controller.init();
</code>```

答:
I think you might be over engineering this a bit.  All you need is an event listener to check for enter.  Then you check if the first div is shown, if not show it.  If the first div is shown check if the second div is shown and show it.

Quick note, no IE9 support for classList if that's important to you.
https://caniuse.com/#feat=classlist

(function(window, document, undefined)
{
  document.addEventListener('keyup', showDivs, false);
})(window, window.document);

function showDivs(event)
{
  event = event || window.event;
  var divsToShow = document.getElementsByClassName("Display-Div");

  for (var i = 0; i < divsToShow.length; i++) {
    if (!divsToShow[i].classList.contains("Block")) {
      divsToShow[i].classList.add("Block");
      break;
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.Hidden {
  display: none;
}

.Block {
  display: block;
}</code>```

This

Now

Works

With

Any

Div

With

Class

Display-Div
```

Title: addEventListener for the same event

Body:
So I have a few div tags that I have currently hidden, and I want to display them one after the other by hitting the enter key.

What I want to happen: I hit enter and the first div tag is revealed, and then I hit enter a second time to see the second div tag.

What is happening instead: I hit enter once and both div tags show up.

In this case, the first div tag I want to reveal is "intro", and the second is "body". I am running this website on jsbin, and I am using chrome, if that helps.

This is my JavaScript:

//***********************************************************

//  BODY MODULE

var bodyController = (function(){
  var enterBool;

  var reveal = function(){
    if(enterBool){
      document.getElementById("evidence").style.display = "block";
      enterBool = false;
    }
  };

  var enterListen = function(){
    document.addEventListener("keydown", function(event){
      if(event.keyCode === 13){
        document.addEventListener("keyup", function(event){
          if(event.keyCode === 13){
            enterBool = true;
            reveal();
          }
        });
      }
    });
  };

  return{
    enterBoolBody: enterBool,
    enterListenBody: function(){
      enterListen();
    }
  }
})();

//***********************************************************

//  INTRO MODULE

var introController = (function(){
  var enterBool;

  var reveal = function(){
    if(enterBool){
      document.getElementById("body").style.display = "block";
      enterBool = false;
    }
  };

  var enterListen = function(){
    document.addEventListener("keydown", function(event){
      if(event.keyCode === 13){
        document.addEventListener("keyup", function(event){
          if(event.keyCode === 13){
            enterBool = true;
            reveal();
          }
        });
      }
    });
  };

  return{
    enterBoolIntro: enterBool,
    enterListenIntro: function(){
      enterListen();
    }
  }
})();

 //***********************************************************

 //  CONTROL MODULE

 var controller = (function(introCtrl, bodyCtrl, evidenceCtrl, infoCtrl,
 conclusionCtrl){
  var eventListeners = function(){
     introCtrl.enterListenIntro();
     bodyCtrl.enterListenBody();
  };

  return{
    init: function(){
      eventListeners();
    }
  }
 })(introController, bodyController, evidenceController,
    infoController, conclusionController);

 //***********************************************************

 controller.init();

Body:
I think you might be over engineering this a bit.  All you need is an event listener to check for enter.  Then you check if the first div is shown, if not show it.  If the first div is shown check if the second div is shown and show it.

Quick note, no IE9 support for classList if that's important to you.
https://caniuse.com/#feat=classlist

(function(window, document, undefined)
{
  document.addEventListener('keyup', showDivs, false);
})(window, window.document);

function showDivs(event)
{
  event = event || window.event;
  var divsToShow = document.getElementsByClassName("Display-Div");

  for (var i = 0; i < divsToShow.length; i++) {
    if (!divsToShow[i].classList.contains("Block")) {
      divsToShow[i].classList.add("Block");
      break;
    }
  }
}

.Hidden {
  display: none;
}

.Block {
  display: block;
}

<div class="Hidden Display-Div">This</div>
<div class="Hidden Display-Div">Now</div>
<div class="Hidden Display-Div">Works</div>
<div class="Hidden Display-Div">With</div>
<div class="Hidden Display-Div">Any</div>
<div class="Hidden Display-Div">Div</div>
<div class="Hidden Display-Div">With</div>
<div class="Hidden Display-Div">Class</div>
<div class="Hidden Display-Div">Display-Div</div>


问:
Can the text be formatted to appear in a more appealing way while using a receipt card?
I am using a receipt card in one of my projects and I have been trying to format my subtitle text using \n, \t, \r\n, but none of these seem to give the expected output.
Is there another way to format the text?

答:
The receipt card is a predefined card template that is not designed for customization.

If you want to create custom card layouts, use Adaptive Cards.

Overview: http://adaptivecards.io/

Examples: http://adaptivecards.io/visualizer/index.html?hostApp=WebChat%20(Bot%20Framework)

Code sample for .NET SDK: https://github.com/Microsoft/BotBuilder-Samples/tree/master/CSharp/cards-AdaptiveCards

Walk-through blog article: https://blog.botframework.com/2017/06/07/Adaptive-Card-Dotnet/


答: If by "overlapping" you mean they appear on the same line then you want System.out.println, rather than System.out.print. println emits a trailing newline.

Title: System.out.print is overlapping the questions why?


问:
Zip two file contents having related timestamp column to create a list in python
I have two files containing timestamp column with 1000+ rows. Row in file f1 is related to the row in file f2. I wanted a Python script to do [f1 nth row,f2 nth row] for all corresponding rows in the best way possible. Thanks!

```<code>f1:
05:43:44
05:59:32

f2:
05:43:51
05:59:39
</code>```

e.g. [05:43:44,05:43:51], [05:59:32,05:59:39] ....

答:
You can do something like the following:</p>

```<code>f1_as_list = open(f1).readlines() # get each line as a list element
f2_as_list = open(f2).readlines()
zipped_files = zip(f1_as_list, f2_as_list) # zip the two lists together
</code>```

Body:
I have two files containing timestamp column with 1000+ rows. Row in file f1 is related to the row in file f2. I wanted a Python script to do [f1 nth row,f2 nth row] for all corresponding rows in the best way possible. Thanks!

f1:
05:43:44
05:59:32

f2:
05:43:51
05:59:39

e.g. [05:43:44,05:43:51], [05:59:32,05:59:39] ....

Body:
You can do something like the following:

f1_as_list = open(f1).readlines() # get each line as a list element
f2_as_list = open(f2).readlines()
zipped_files = zip(f1_as_list, f2_as_list) # zip the two lists together


问:
UITextField value disappearing and reappearing in other UITableViewCells upon scrolling
```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"inventoryItem";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    cell.textLabel.font = [UIFont systemFontOfSize:15];

}

UILabel *name = (UILabel *)[cell viewWithTag:1];

name.text = [NSString stringWithFormat:@"%@",inventoryItems[indexPath.row][@"Inventory_Name"]];

NSLog(@"%@", name.text);

cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;

}
</code>```

I am a beginner in Objective-C. I have a custom UITableViewCell with a name and a UITextField. The UITextField tag is 4. Everytime I scroll, the values in the UITextFields disappear and appear in different cells. I understand, that this is because of the dequeueReusableCellWithIdentifier, where cells get reused. I have researched a bit and have found that storing the UITextFields in an array and having them reloaded in cellForRowAtIndexPath might be the best way, but I am having trouble implementing that. An example would be ideal, or an easy way to get around this. Thank you.

答:
Every time your cellForRowAtIndexPath: method is called, you're setting your name UILabel.

I'm wondering/thinking that the value from inventoryItems[indexPath.row][@"Inventory_Name"] isn't what you are expecting?

Instead of doing:

```<code>NSLog(@"%@", name.text);
</code>```

Try doing:

```<code>NSLog(@"%@ SHOULD EQUAL %@", inventoryItems[indexPath.row][@"Inventory_Name"], name.text);
</code>```

And see if they always match?  I suspect you have some "<null>" values hiding in there.

Body:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"inventoryItem";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    cell.textLabel.font = [UIFont systemFontOfSize:15];

}

UILabel *name = (UILabel *)[cell viewWithTag:1];

name.text = [NSString stringWithFormat:@"%@",inventoryItems[indexPath.row][@"Inventory_Name"]];

NSLog(@"%@", name.text);

cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;

}

I am a beginner in Objective-C. I have a custom UITableViewCell with a name and a UITextField. The UITextField tag is 4. Everytime I scroll, the values in the UITextFields disappear and appear in different cells. I understand, that this is because of the dequeueReusableCellWithIdentifier, where cells get reused. I have researched a bit and have found that storing the UITextFields in an array and having them reloaded in cellForRowAtIndexPath might be the best way, but I am having trouble implementing that. An example would be ideal, or an easy way to get around this. Thank you.

Body:
Every time your cellForRowAtIndexPath: method is called, you're setting your name UILabel.

I'm wondering/thinking that the value from inventoryItems[indexPath.row][@"Inventory_Name"] isn't what you are expecting?

Instead of doing:

NSLog(@"%@", name.text);

Try doing:

NSLog(@"%@ SHOULD EQUAL %@", inventoryItems[indexPath.row][@"Inventory_Name"], name.text);

And see if they always match?  I suspect you have some "<null>" values hiding in there.


问:
What is the benefit of using redux?
I am thinking about learning reactjs recently and I hope if someone could help me to understand the circumstances to use redux, as I am confused by its complicated logic.

First, I have used angular2+ for a while, and so I am also trying to grab the idea from the what I have already know.

I have seen many examples of redux but I don't understand the benefit to use actions and dispatch.

What is the benefit of using redux store using actions and reducers instead of just use class and subject like this?

```<code>class Store{
    subject = new BehaviorSubject(0);
    get value(){
        return this.subject.getValue();
    }
    inc(){
        this.subject.next(this.subject.value+1);
    }
    dec(){
        this.subject.next(this.subject.value-1);
    }
    clear(){
        this.subject.next(0);
    }
}

class Demo extends React.Component<{}, {}>{
    store = new Store();
    componentWillMount(){
        this.store.subject.subscribe(_ => this.forceUpdate())
    }
    render(){
        const value = this.store.value;
        const { inc, dec, clear } = this.store;
        const store = this.store;
        return (
            <div>
                <span>{`current value is ${value}`}</span>
                <button onClick={inc.bind(store)}>INC</button>
                <button onClick={dec.bind(store)}>DEC</button>
                <button onClick={clear.bind(store)}>CLEAR</button>
            </div>
        );
    }
}
</code>```

答:
The benefits of dispatching actions over traditional method calling:

Logging—as all the actions can be easily logged, you always see what's going on in the app. For larger apps that's the killer feature for me.

Preprocessing—you can use redux middlewares to perform all kinds of fancy preprocessing of your actions—most typical is automating xhr requests in some way.

As actions are serializable implementing features like "undo" is much easier, while that's not necessary too often.

About the reducers—reducers happen to be the cleanest way to update immutable state. So it's not so much about the reducers as about mutable vs immutable store state, and that's quite a religious question. I would say that given enough discipline mutable state works as well as the immutable one.

About the preprocessing—basically you can have a piece of code which looks on all the actions happening in the system and doing something if an action matches some criteria.

For example:

All the actions which have the { url, params } properties will result into a request to the backend API specified by the { url } and converted into new actions which would have the { responseJson } property instead of the url & params

All the actions containing a { debounce } property will be debounced, so if you issue a dozen of such actions in a row only the last one will be actually processed.

All the actions having an { alert } property would show a small toast alert to the user.

And so on and so forth. Basically, dispatching actions force you to pass all the most important things in the app through a central place which may handle those actions in any way you can think of.

Title: What is the benefit of using redux?

Body:
I am thinking about learning reactjs recently and I hope if someone could help me to understand the circumstances to use redux, as I am confused by its complicated logic.

First, I have used angular2+ for a while, and so I am also trying to grab the idea from the what I have already know.

I have seen many examples of redux but I don't understand the benefit to use actions and dispatch.

What is the benefit of using redux store using actions and reducers instead of just use class and subject like this?

class Store{
    subject = new BehaviorSubject(0);
    get value(){
        return this.subject.getValue();
    }
    inc(){
        this.subject.next(this.subject.value+1);
    }
    dec(){
        this.subject.next(this.subject.value-1);
    }
    clear(){
        this.subject.next(0);
    }
}

class Demo extends React.Component<{}, {}>{
    store = new Store();
    componentWillMount(){
        this.store.subject.subscribe(_ => this.forceUpdate())
    }
    render(){
        const value = this.store.value;
        const { inc, dec, clear } = this.store;
        const store = this.store;
        return (

                {`current value is ${value}`}
                <button onClick={inc.bind(store)}>INC</button>
                <button onClick={dec.bind(store)}>DEC</button>
                <button onClick={clear.bind(store)}>CLEAR</button>

        );
    }
}


问:
using .reduce() on an a list of objects
I have this sample data set:

```<code>let list = [
  {'first': 'morgan', 'id': 1},
  {'first': 'eric', 'id': 1},
  {'first': 'brian', 'id': 2 },
  {'first': 'derek', 'id' : 2},
  {'first': 'courtney', 'id': 3},
  {'first': 'eric', 'id': 4},
  {'first': 'jon', 'id':4},
]
</code>```

I am trying to end up with this:

```<code>[[1, [morgan, eric]], [2, [brian, derek]], [3, [courtney]], [4, [eric, jon]]
</code>```

I am using the .reduce() function to map over the list. However, I'm somewhat stuck.

I got this working:

```<code>let b = list.reduce((final_list, new_item) => {
  x = final_list.concat([[new_item.id, [new_item.first]]])
  return x
}, [])
</code>```

However, that flattens out the list into a list of lists of lists, but doesn't combine names that share a similar id.

I tried using .map() the code below does not work

I tried to map over the final_list (which is a list of [id, [names]] looking to see if the id of the new_item exists in the smaller_list and then add new_item.first to the smaller_list[1] (which should be the list of names).

Is this the right approach?

```<code>let b = list.reduce((final_list, new_item) => {
  final_list.map((smaller_list) => {
    if (smaller_list.indexOf((new_item.id)) >=0) {
      smaller_list[1].concat(new_item.first)
      // not sure what to do here...
    } else {
        // not sure what to do here either...
    }

  })
  x = final_list.concat([[item.id, [item.first]]])
  return x
}, [])
</code>```

答:
Try first creating a map of IDs to names, then map that into your final array, eg

let list = [
  {'first': 'morgan', 'id': 1},
  {'first': 'eric', 'id': 1},
  {'first': 'brian', 'id': 2 },
  {'first': 'derek', 'id' : 2},
  {'first': 'courtney', 'id': 3},
  {'first': 'eric', 'id': 4},
  {'first': 'jon', 'id':4},
]

const idMap = list.reduce((map, item) => {
  if (Array.isArray(map[item.id])) {
    map[item.id].push(item.first)
  } else {
    map[item.id] = [item.first]
  }
  return map
}, {})

const b = Object.keys(idMap).map(id => [parseInt(id), idMap[id]])
console.info(JSON.stringify(b))```

Title: using .reduce() on an a list of objects

Body:
I have this sample data set:

let list = [
  {'first': 'morgan', 'id': 1},
  {'first': 'eric', 'id': 1},
  {'first': 'brian', 'id': 2 },
  {'first': 'derek', 'id' : 2},
  {'first': 'courtney', 'id': 3},
  {'first': 'eric', 'id': 4},
  {'first': 'jon', 'id':4},
]

I am trying to end up with this:

[[1, [morgan, eric]], [2, [brian, derek]], [3, [courtney]], [4, [eric, jon]]

I am using the .reduce() function to map over the list. However, I'm somewhat stuck.

I got this working:

let b = list.reduce((final_list, new_item) => {
  x = final_list.concat([[new_item.id, [new_item.first]]])
  return x
}, [])

However, that flattens out the list into a list of lists of lists, but doesn't combine names that share a similar id.

I tried using .map() the code below does not work

I tried to map over the final_list (which is a list of [id, [names]] looking to see if the id of the new_item exists in the smaller_list and then add new_item.first to the smaller_list[1] (which should be the list of names).

Is this the right approach?

let b = list.reduce((final_list, new_item) => {
  final_list.map((smaller_list) => {
    if (smaller_list.indexOf((new_item.id)) >=0) {
      smaller_list[1].concat(new_item.first)
      // not sure what to do here...
    } else {
        // not sure what to do here either...
    }

  })
  x = final_list.concat([[item.id, [item.first]]])
  return x
}, [])


答:
You may use zip() function. https://docs.python.org/3/library/functions.html#zip

```<code>>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
</code>```

Title: Zip two file contents having related timestamp column to create a list in python

Body:
You may use zip() function. https://docs.python.org/3/library/functions.html#zip

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]