问:
How to change color of excel cells with pandas (python)
I'm trying to compare two excel files and then output the non equal values into a new excel file.

Currently in the excel3 file it will display (value in excel1) --> (value in excel2) but I also want to add a red background to the cell as well so it is easily visible.

I've tried looking around online and can't figure it out. I'm pretty new to python as well.

```<code>#Needed packages
import pandas as pd
import numpy as np

#Changes the col number into its corresponding excel col letter
def col_num(n):
    n = n + 1
    string = ""
    while n > 0:
        n, remainder = divmod(n - 1, 26)
        string = chr(65 + remainder) + string
    return string

#Puts the characters from the col_num method into a string (Could be improved)
def char_array(cols):
    i = 0
    ex_cols = ""
    while i < len(cols):
        if i == len(cols) - 1:
            ex_cols += (col_num(cols[i]))
        else:
            ex_cols += (col_num(cols[i])) + " "
        i += 1
    return ex_cols

print("\nExcel Comparer v1.2\n")

#Retrieve excel files for comparison
while True:
    file = input("First Excel file for comparison: ")
    try:
        df1 = pd.read_excel(file + ".xlsx")
        break
    except FileNotFoundError:
        print("File not Found, please make sure this program is in the same directory as both excel files.")
while True:
    file = input("Second Excel file for comparison: ")
    try:
        df2 = pd.read_excel(file + ".xlsx")
        break
    except FileNotFoundError:
        print("File not Found, please make sure this program is in the same directory as both excel files.")
print("\n\nFiles compared succesfully!\n\n")

#determines whether the files are exactly equal
print("\nAre the Documents exactly the same:", df1.equals(df2))

#shows each cell as being either equal(True) or not equal(False)
values_compared = df1.values == df2.values
print("\nEach cell on whether or not they're equivalent:\n", values_compared)

#Get all cells where the values are not equal(False)
rows, cols = np.where(values_compared == False)
print("\nThe indexes of each non-equal value:")
print("Col: [", char_array(cols), "]")
print("Row: ", (rows + 2))

#df1 will now show the differences between the two files
for item in zip(rows, cols):
    df1.iloc[item[0], item[1]] = '{} --> {}'.format(df1.iloc[item[0], item[1]], df2.iloc[item[0], item[1]])

#Creates a new excel file and writes the differences shown
df1.to_excel('./excel3.xlsx', index = False, header = True)

print("\nexcel3.xlsx has been written to this directory with the discrepancies.")
</code>```

答:
Pandas isn't going to do that.  You'll need another library.  xlsxwriter can do what you've asked.  Here's the documentation.

https://xlsxwriter.readthedocs.io/working_with_pandas.html

Body:
I'm trying to compare two excel files and then output the non equal values into a new excel file.

Currently in the excel3 file it will display (value in excel1) --> (value in excel2) but I also want to add a red background to the cell as well so it is easily visible.

I've tried looking around online and can't figure it out. I'm pretty new to python as well.

#Needed packages
import pandas as pd
import numpy as np

#Changes the col number into its corresponding excel col letter
def col_num(n):
    n = n + 1
    string = ""
    while n > 0:
        n, remainder = divmod(n - 1, 26)
        string = chr(65 + remainder) + string
    return string

#Puts the characters from the col_num method into a string (Could be improved)
def char_array(cols):
    i = 0
    ex_cols = ""
    while i < len(cols):
        if i == len(cols) - 1:
            ex_cols += (col_num(cols[i]))
        else:
            ex_cols += (col_num(cols[i])) + " "
        i += 1
    return ex_cols

print("\nExcel Comparer v1.2\n")

#Retrieve excel files for comparison
while True:
    file = input("First Excel file for comparison: ")
    try:
        df1 = pd.read_excel(file + ".xlsx")
        break
    except FileNotFoundError:
        print("File not Found, please make sure this program is in the same directory as both excel files.")
while True:
    file = input("Second Excel file for comparison: ")
    try:
        df2 = pd.read_excel(file + ".xlsx")
        break
    except FileNotFoundError:
        print("File not Found, please make sure this program is in the same directory as both excel files.")
print("\n\nFiles compared succesfully!\n\n")

#determines whether the files are exactly equal
print("\nAre the Documents exactly the same:", df1.equals(df2))

#shows each cell as being either equal(True) or not equal(False)
values_compared = df1.values == df2.values
print("\nEach cell on whether or not they're equivalent:\n", values_compared)

#Get all cells where the values are not equal(False)
rows, cols = np.where(values_compared == False)
print("\nThe indexes of each non-equal value:")
print("Col: [", char_array(cols), "]")
print("Row: ", (rows + 2))

#df1 will now show the differences between the two files
for item in zip(rows, cols):
    df1.iloc[item[0], item[1]] = '{} --> {}'.format(df1.iloc[item[0], item[1]], df2.iloc[item[0], item[1]])

#Creates a new excel file and writes the differences shown
df1.to_excel('./excel3.xlsx', index = False, header = True)

print("\nexcel3.xlsx has been written to this directory with the discrepancies.")


来源: stackexchange

问:
why does this negative lookahead not work?
Both of the following produce the string gotcha. why?

```<code>perl -e 'print "gotcha\n" if "corecaptured" =~ /(?!corecaptured)/;'

perl -e 'print "gotcha\n" if "corecaptured" =~ /(?=corecaptured)/;'
</code>```

I expect the first not to print anything as the negative lookahead should produce a false result but I'm obviously missing something.

when I stick the regex into a debugger I get unexpected results:
https://regex101.com/r/eM4tF1/4

答:
Your regexes are not anchored. The first condition really says "is there a position in the string "corecaptured" that is not followed by the text corecaptured?".

The answer to that is yes, because at offset 1 the following string is "orecaptured", which does not start with c. That's why the regex match returns true.

You probably meant /^(?!corecaptured)/, which checks whether the target string does not start with corecaptured.

As for your regex101 link, that contains a very different regex: a(?!b)c is equivalent to ac because (?!b)c means "match c at a position where the next character is not b" (or in other words, "match a c that is not also a b").

If you change it to what's in your code, you'll see that the result is a single successful match (of length 0) at offset 1:

```<code>corecaptured
 ^
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Both of the following produce the string gotcha. why?

perl -e 'print "gotcha\n" if "corecaptured" =~ /(?!corecaptured)/;'

perl -e 'print "gotcha\n" if "corecaptured" =~ /(?=corecaptured)/;'

I expect the first not to print anything as the negative lookahead should produce a false result but I'm obviously missing something.

when I stick the regex into a debugger I get unexpected results:
https://regex101.com/r/eM4tF1/4

Body:
Your regexes are not anchored. The first condition really says "is there a position in the string "corecaptured" that is not followed by the text corecaptured?".

The answer to that is yes, because at offset 1 the following string is "orecaptured", which does not start with c. That's why the regex match returns true.

You probably meant /^(?!corecaptured)/, which checks whether the target string does not start with corecaptured.

As for your regex101 link, that contains a very different regex: a(?!b)c is equivalent to ac because (?!b)c means "match c at a position where the next character is not b" (or in other words, "match a c that is not also a b").

If you change it to what's in your code, you'll see that the result is a single successful match (of length 0) at offset 1:

corecaptured
 ^


问:
Drupal 6 - Content profile fields within page-user.tpl.php
Going a bit mad here... :)

I'm just trying to add CCK fields from a Content Profile content type into page-user.tpl.php (I'm creating a highly-themed user profile page).

There seem to be two methods, both of which have a unique disadvantage that I can't seem to overcome:

'$content profile' method.

```<code>$var = $content_profile->get_variables('profile');

print $var['field_last_name'][0]['safe'];
</code>```

This is great, except I can't seem to pass the currently viewed user into $content_profile, and it therefore always shows the logged in user.

'$content profile load' method.

```<code>$account_id = arg(1);
$account = user_load($account_id);
$user_id = $account->uid;

$var = content_profile_load('profile', $user_id);

print $var->field_first_name[0]['value'];
</code>```

Fine, but now I can't access the full rendered fields, only the plain values (i.e. if the field has paragraphs they won't show up).

How can I have both things at once? In other words how can I show fields relating to the currently viewed user that are also rendered (the 'safe' format in 1)?

I've Googled and Googled and I just end up going round in circles. :(

Cheers,
James

答:
When you're creating a user profile page there is a built in mechanism for it.  just create a user template file, user_profile.tpl.php.

When you use the built in mechanism you automatically get access to the $account object of the user you are browsing, including all user profile cck fields.  You have the fields you are looking for without having to programmatically load the user.

I have a field called profile_bio and am able to spit out any mark up that is in without ever having to ask for the $account.

```<code><?php if ($account->content[Profile][profile_bio]['#value']) print "<h3>Bio</h3>".$account->content[Profile][profile_bio]['#value']; ?>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Going a bit mad here... :)

I'm just trying to add CCK fields from a Content Profile content type into page-user.tpl.php (I'm creating a highly-themed user profile page).

There seem to be two methods, both of which have a unique disadvantage that I can't seem to overcome:

'$content profile' method.

$var = $content_profile->get_variables('profile');

print $var['field_last_name'][0]['safe'];

This is great, except I can't seem to pass the currently viewed user into $content_profile, and it therefore always shows the logged in user.

'$content profile load' method.

$account_id = arg(1);
$account = user_load($account_id);
$user_id = $account->uid;

$var = content_profile_load('profile', $user_id);

print $var->field_first_name[0]['value'];

Fine, but now I can't access the full rendered fields, only the plain values (i.e. if the field has paragraphs they won't show up).

How can I have both things at once? In other words how can I show fields relating to the currently viewed user that are also rendered (the 'safe' format in 1)?

I've Googled and Googled and I just end up going round in circles. :(

Cheers,
James

Body:
When you're creating a user profile page there is a built in mechanism for it.  just create a user template file, user_profile.tpl.php.

When you use the built in mechanism you automatically get access to the $account object of the user you are browsing, including all user profile cck fields.  You have the fields you are looking for without having to programmatically load the user.

I have a field called profile_bio and am able to spit out any mark up that is in without ever having to ask for the $account.

<?php if ($account->content[Profile][profile_bio]['#value']) print "<h3>Bio</h3>".$account->content[Profile][profile_bio]['#value']; ?>


问:
How to "Pass configuration data to your plug-in" and what's the purpose of the same ? Any real time scenario with example?
What's the use of passing configuration data to plugin and how to do this ?

https://learn.microsoft.com/en-us/powerapps/developer/common-data-service/write-plug-in

Pass configuration data to your plug-in
When you register a plug-in you have the ability to pass configuration data to it. Configuration data allows you to define how a specific instance of a registered plug-in should behave. This information is passed as string data to parameters in the constructor of your class. There are two parameters: unsecure and secure. Use the first unsecure parameter for data that you don't mind if people can see. Use the second secure parameter for sensitive data.

The following code shows the three possible signatures for a plug-in class named SamplePlugin.

```<code>public SamplePlugin()
public SamplePlugin(string unsecure)
public SamplePlugin(string unsecure, string secure)
</code>```

答:
Adding to Arun's answer.  The data that is passed in, is set view the PluginRegistrationTool.  You can download it from NuGet, but I think it's even easier to download it from Xrm.Tools as a zip and access it form there.

I also suggest defining only a single constructor with default null values:

```<code>public SamplePlugin(string unsecure = null, string secure = null) {}
</code>```

And if you want to go crazy, check out my Visual Studio Accelerator plugin for the XrmToolBox to add the correct SDK references, and optionally some example plugins with unit tests in less than 2 minutes.

Body:
What's the use of passing configuration data to plugin and how to do this ?

https://learn.microsoft.com/en-us/powerapps/developer/common-data-service/write-plug-in

Pass configuration data to your plug-in
When you register a plug-in you have the ability to pass configuration data to it. Configuration data allows you to define how a specific instance of a registered plug-in should behave. This information is passed as string data to parameters in the constructor of your class. There are two parameters: unsecure and secure. Use the first unsecure parameter for data that you don't mind if people can see. Use the second secure parameter for sensitive data.

The following code shows the three possible signatures for a plug-in class named SamplePlugin.

public SamplePlugin()
public SamplePlugin(string unsecure)
public SamplePlugin(string unsecure, string secure)

Body:
Adding to Arun's answer.  The data that is passed in, is set view the PluginRegistrationTool.  You can download it from NuGet, but I think it's even easier to download it from Xrm.Tools as a zip and access it form there.

I also suggest defining only a single constructor with default null values:

public SamplePlugin(string unsecure = null, string secure = null) {}

And if you want to go crazy, check out my Visual Studio Accelerator plugin for the XrmToolBox to add the correct SDK references, and optionally some example plugins with unit tests in less than 2 minutes.


问:
Why ng build just doesn’t work in the Angular app?
Created a new project, did not change anything. I started ng build, took the dist folder (only it) and ran it on the local server. In the end, nothing. What's wrong?</p>

答:
I didn't understand your point. When you use the build command, you are compiling to production, I mean, you are transpiling from typescript to javascript vanilla, in less words, you are preparing your angular application to speak the same browser language.

Sorry, but I answer you as I understand your problem.


问:
How to center icon by horizontal parent block?
I have the following block:

```<code><div class="class-journal-mobile-navigation-move left">
<i class="material-icons"> arrow_back_ios</i>
</div>

.class-journal-mobile-navigation-move {
    border-radius: 50%;
    border: 1px solid #3e4eb8;
    width: 50px;
    height: 50px;
    display: table;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

.class-journal-mobile-navigation-move i {
    font-size: 24px;
    color: #3e4eb8;
    display: table-cell;
    text-align: center;
}
</code>```

I need to center i element by center in parent block, now it look as:

After applying changes it looks now as:

答:
Add the following lines:</p>

```<code>.class-journal-mobile-navigation-move {
   display: flex;
   align-items:center;
   justify-content:center;
}
</code>```

Body:
I have the following block:

 arrow_back_ios

.class-journal-mobile-navigation-move {
    border-radius: 50%;
    border: 1px solid #3e4eb8;
    width: 50px;
    height: 50px;
    display: table;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

.class-journal-mobile-navigation-move i {
    font-size: 24px;
    color: #3e4eb8;
    display: table-cell;
    text-align: center;
}

I need to center i element by center in parent block, now it look as:

After applying changes it looks now as:

Body:
Add the following lines:

.class-journal-mobile-navigation-move {
   display: flex;
   align-items:center;
   justify-content:center;
}


问:
Child setState does not work when calling Parent method
I am new to React so sorry if this is a bad question. I am having trouble with changing the state of a child component then calling a method that changes the state of the parent component. Right now when I trigger the method that is supposed to change states the parent state changes as it should but the child state does not change at all.

When I remove the state change on the Parent component the child component changes as it should.

Here is the parent component (edited to remove code not related to the problem)

```<code>class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loginModalName: "Log in"
        }
        this.bindedUpdateModalName = this.updateModalName.bind(this)
    }

    updateModalName(name) {
        console.log(name);
        this.setState({
            loginModalName: name
        });
    };

    render() {
        return (
            <Child loginSwitch = {this.bindedUpdateModalName}/>
        );
    }
}
</code>```

and here is the child component

```<code>class Child extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoggingIn: true
        }
    }

    toggleLoggingIn = () => {
        this.setState({
            isLoggingIn: !this.state.isLoggingIn
        });
        console.log(this.state.isLoggingIn);
        this.props.loginSwitch(this.state.isLoggingIn ? "Log in" : "Register");
    };

    render() {
        return (
            <Button onClick={this.toggleLoggingIn} type="link" style={{paddingLeft: 0}}>register now!</Button>
        );
    }
</code>```

There are no error messages, but my logs show

```<code>true
Log In
</code>```

every time I click the button

答:
As John mentioned setState is async. However, setState takes a second parameter that is a callback function to call after is has updated the state.

From the docs:

The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.

Try this:

```<code>toggleLoggingIn = () => {
    const isLogin = !this.state.isLoggingIn
    this.setState(
        {
            isLoggingIn: !this.state.isLoggingIn
        },

        // Callback to run after state has been updated
        () => {
            console.log(this.state.isLoggingIn);
            this.props.loginSwitch(this.state.isLoggingIn ? "Log in" : "Register");
        }
    );
};
</code>```

Body:
I am new to React so sorry if this is a bad question. I am having trouble with changing the state of a child component then calling a method that changes the state of the parent component. Right now when I trigger the method that is supposed to change states the parent state changes as it should but the child state does not change at all.

When I remove the state change on the Parent component the child component changes as it should.

Here is the parent component (edited to remove code not related to the problem)

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loginModalName: "Log in"
        }
        this.bindedUpdateModalName = this.updateModalName.bind(this)
    }

    updateModalName(name) {
        console.log(name);
        this.setState({
            loginModalName: name
        });
    };

    render() {
        return (
            <Child loginSwitch = {this.bindedUpdateModalName}/>
        );
    }
}

and here is the child component

class Child extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoggingIn: true
        }
    }

    toggleLoggingIn = () => {
        this.setState({
            isLoggingIn: !this.state.isLoggingIn
        });
        console.log(this.state.isLoggingIn);
        this.props.loginSwitch(this.state.isLoggingIn ? "Log in" : "Register");
    };

    render() {
        return (
            <Button onClick={this.toggleLoggingIn} type="link" style={{paddingLeft: 0}}>register now!</Button>
        );
    }

There are no error messages, but my logs show

true
Log In

every time I click the button

Body:
As John mentioned setState is async. However, setState takes a second parameter that is a callback function to call after is has updated the state.

From the docs:

The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.

Try this:

toggleLoggingIn = () => {
    const isLogin = !this.state.isLoggingIn
    this.setState(
        {
            isLoggingIn: !this.state.isLoggingIn
        },

        // Callback to run after state has been updated
        () => {
            console.log(this.state.isLoggingIn);
            this.props.loginSwitch(this.state.isLoggingIn ? "Log in" : "Register");
        }
    );
};


问:
NPM does not update package properly
In my React Native (version 0.59.5) application, I have installed and linked the latest version of React Native Gesture Handler(version 1.2.2). Whenever I run the application on my simulator, I get the following message immediately after successfully building:

TypeError: param is not an Object. (evaluating "__isNative' in param')

This error is located at:
  inPanGestureHandler (at StackViewLayout.js:300)
  in StackViewLayout (at withOrientation.js:30)
  in withOrientation (at StackView.js:79)
  in RCTView (at View.js:45)
  in View (at Transitioner.js:215)
  in Transitioner (at StackView.js22)
  in StackView (created by Navigator)
  in Navigator (at createKeyboardAwareNavigator.js:12)
  in KeyboardAwareNavigator (created by SceneView)
  in SceneView (at createTabNavigator.js:39)
  in RCTView (at View.js:45)
  in View (at ResourceSavingScene.js:26)
  in ResourceSavingScene (at createBottomTabNavigator.js:113)
  in RCTView (at View.js:45)
  in View (at screens.native.js:83)
  in ScreenContainer (at createBottomTabNavigator.js:103)
  in RCTView (at View.js:45)
  in View (at createBottomTabNavigator.js:102)
  in TabNavigationView (at createTabNavigator.js:197)
```

<p>However, when I reinstall the library without closing or restarting the simulator, using the following command:</p>

```npm install --save react-native-gesture-handler@latest
```

Immediately after I live reload (refresh the app), the error is gone and I can properly use my application.

What might have gone wrong? Why do I always have to reinstall the library for the error to get fixed?

答: Solved by removing the following subspecs from my Podfile.

Title: NPM does not update package properly

Body:
In my React Native (version 0.59.5) application, I have installed and linked the latest version of React Native Gesture Handler(version 1.2.2). Whenever I run the application on my simulator, I get the following message immediately after successfully building:

TypeError: param is not an Object. (evaluating "__isNative' in param')

This error is located at:
  inPanGestureHandler (at StackViewLayout.js:300)
  in StackViewLayout (at withOrientation.js:30)
  in withOrientation (at StackView.js:79)
  in RCTView (at View.js:45)
  in View (at Transitioner.js:215)
  in Transitioner (at StackView.js22)
  in StackView (created by Navigator)
  in Navigator (at createKeyboardAwareNavigator.js:12)
  in KeyboardAwareNavigator (created by SceneView)
  in SceneView (at createTabNavigator.js:39)
  in RCTView (at View.js:45)
  in View (at ResourceSavingScene.js:26)
  in ResourceSavingScene (at createBottomTabNavigator.js:113)
  in RCTView (at View.js:45)
  in View (at screens.native.js:83)
  in ScreenContainer (at createBottomTabNavigator.js:103)
  in RCTView (at View.js:45)
  in View (at createBottomTabNavigator.js:102)
  in TabNavigationView (at createTabNavigator.js:197)

However, when I reinstall the library without closing or restarting the simulator, using the following command:

npm install --save react-native-gesture-handler@latest

Immediately after I live reload (refresh the app), the error is gone and I can properly use my application.

What might have gone wrong? Why do I always have to reinstall the library for the error to get fixed?


问:
Why is my code not working on more than one thread?
I have been trying to multi-thread my code, it still works, but only uses 15% of my cpu (i have 8 threads, so thats 1 thread).

I have tried many scripts to multi-thread from stack overflow and youtube, but none worked.

```<code>import threading

n=2

def crazy():
    global n
    while True:
        n = n*2
        print(n)

threads = []
for i in range(4):
    t = threading.Thread(target=crazy)
    threads.append(t)
    t.start()
</code>```

The ouput is as expected, but only running on one thread.

答:
This is running multiple python threads, however, python threads are at the application level and not the kernel. These application threads take turns running on the same core, but they are indeed context switching. For example take the output of this code. It switches between threads to print the numbers:

```<code>import threading

n=0
def crazy(i):
    global n
    for i in range(4):
        n = n + 1
        print(f"Thread {i}: {n}")

threads = []
for i in range(4):
    t = threading.Thread(target=crazy, args=(i,))
    threads.append(t)
    t.start()
</code>```

Outputs:

```<code>Thread 0: 1
Thread 1: 2
Thread 2: 3
Thread 3: 4
Thread 0: 5
Thread 1: 6
Thread 2: 7
Thread 3: 8
Thread 0: 9
Thread 1: 10
Thread 2: 11
Thread 3: 12
Thread 0: 13
Thread 1: 14
Thread 2: 15
Thread 3: 16
</code>```

Body:
I have been trying to multi-thread my code, it still works, but only uses 15% of my cpu (i have 8 threads, so thats 1 thread).

I have tried many scripts to multi-thread from stack overflow and youtube, but none worked.

import threading

n=2

def crazy():
    global n
    while True:
        n = n*2
        print(n)

threads = []
for i in range(4):
    t = threading.Thread(target=crazy)
    threads.append(t)
    t.start()

The ouput is as expected, but only running on one thread.

Body:
This is running multiple python threads, however, python threads are at the application level and not the kernel. These application threads take turns running on the same core, but they are indeed context switching. For example take the output of this code. It switches between threads to print the numbers:

import threading

n=0
def crazy(i):
    global n
    for i in range(4):
        n = n + 1
        print(f"Thread {i}: {n}")

threads = []
for i in range(4):
    t = threading.Thread(target=crazy, args=(i,))
    threads.append(t)
    t.start()

Outputs:

Thread 0: 1
Thread 1: 2
Thread 2: 3
Thread 3: 4
Thread 0: 5
Thread 1: 6
Thread 2: 7
Thread 3: 8
Thread 0: 9
Thread 1: 10
Thread 2: 11
Thread 3: 12
Thread 0: 13
Thread 1: 14
Thread 2: 15
Thread 3: 16


问:
C pointer problem!
Why does the following C code does not ouput 10

```<code>#include<stdio.h>
#include<stdlib.h>
void get_length(char s[]);
int main( )
{
char buff[128];
printf("\nEnter buffer data: ");
scanf("%s",buff);
get_length(buff);
}

void get_length(char *s){
    int count;
for(count = 0 ; *s != '\0' ; s++)
    count++;
printf("count = %d\n",count);
}
</code>```

The input is I am Rohit

The output is

count = 432

Can anyone please explain that.

答:
You appear to have a 5 instead of a % in your scanf format string. (Perhaps your keyboard's shift key needs cleaning.)

That means that scanf isn't actually reading anything into your buffer. Your code doesn't check the return value from scanf (it should!) and therefore never notices that it failed. So you're then trying to calculate the length of ... a buffer full of uninitialized junk. It could give you 432, or 0, or anything else at all.

[EDITED to add:] ... Oh. And even if you fix that, it still won't work because scanf will stop reading when it sees a whitespace character, including a newline, and therefore the \n your get_length function is looking for will not be in the buffer.

Incidentally, do you know about the strlen function in the C standard library?

Title: C pointer problem!

Body:
Why does the following C code does not ouput 10

#include<stdio.h>
#include<stdlib.h>
void get_length(char s[]);
int main( )
{
char buff[128];
printf("\nEnter buffer data: ");
scanf("%s",buff);
get_length(buff);
}

void get_length(char *s){
    int count;
for(count = 0 ; *s != '\0' ; s++)
    count++;
printf("count = %d\n",count);
}

The input is I am Rohit

The output is

count = 432

Can anyone please explain that.


问:
C++ how to check a condition before using initialiser list?
I am writing a piece of code that is structured this way:

```<code>//field.h
class Field {
    std::vector<std::vector<double>> data;

    public:
    Field(int, int);
};
Field::Field (int dim0, int dim1) :: data(dim0, std::vector<double>(dim1, 0)) { }
</code>```

Then I am using this Field in another class like:

```<code>//approx.h
class Field;
class Approx {
    Field SWAP;

    public:
    Approx(int, int);
};
Approx::Approx (int size, int dim) { }
/*I want to initialise SWAP like this:
     if (size > dim) SWAP(size, dim)
     else SWAP(dim, size)
*/
</code>```

I do not know how to do this. I presume it is impossible without initialiser lists? Can I even ask inside initialiser list these questions?

If there is another way to do so, I'd be grateful for any type of solution.

答:
Shouldn't using std::min and max do the trick ?</p>

```<code>class Field;
class Approx {
Field SWAP;

public:
Approx(int, int);
};
Approx::Approx (int size, int dim): SWAP(std::max(size,dim), std::min(size,dim))
{ }
</code>```

Body:
I am writing a piece of code that is structured this way:

//field.h
class Field {
    std::vector<std::vector<double>> data;

    public:
    Field(int, int);
};
Field::Field (int dim0, int dim1) :: data(dim0, std::vector<double>(dim1, 0)) { }

Then I am using this Field in another class like:

//approx.h
class Field;
class Approx {
    Field SWAP;

    public:
    Approx(int, int);
};
Approx::Approx (int size, int dim) { }
/*I want to initialise SWAP like this:
     if (size > dim) SWAP(size, dim)
     else SWAP(dim, size)
*/

I do not know how to do this. I presume it is impossible without initialiser lists? Can I even ask inside initialiser list these questions?

If there is another way to do so, I'd be grateful for any type of solution.

Body:
Shouldn't using std::min and max do the trick ?

class Field;
class Approx {
Field SWAP;

public:
Approx(int, int);
};
Approx::Approx (int size, int dim): SWAP(std::max(size,dim), std::min(size,dim))
{ }


答:
You can use flexbox:

instead of display: table; for class-journal-mobile-navigation-move,

h1, p {
  font-family: Lato;
}

.class-journal-mobile-navigation-move {
      border-radius: 50%;
      border: 1px solid #3e4eb8;
      width: 50px;
      height: 50px;
      /* display: table; */
      cursor: pointer;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;

      display: flex;
      align-items: center;
      justify-content: center;
  }

  .class-journal-mobile-navigation-move i {
      font-size: 24px;
      color: #3e4eb8;
      /* display: table-cell; */
      text-align: center;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="class-journal-mobile-navigation-move left">
  <i class="material-icons"><</i>
  </div></code>```

Title: How to center icon by horizontal parent block?

Body:
You can use flexbox:

instead of display: table; for class-journal-mobile-navigation-move,

h1, p {
  font-family: Lato;
}

.class-journal-mobile-navigation-move {
      border-radius: 50%;
      border: 1px solid #3e4eb8;
      width: 50px;
      height: 50px;
      /* display: table; */
      cursor: pointer;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;

      display: flex;
      align-items: center;
      justify-content: center;
  }

  .class-journal-mobile-navigation-move i {
      font-size: 24px;
      color: #3e4eb8;
      /* display: table-cell; */
      text-align: center;
  }

  <div class="class-journal-mobile-navigation-move left">
  <i class="material-icons"><</i>
  </div>


问:
How to convert object into string in javascript?
I have a function that should take as an argument of the object and return a string

The code I wrote.

```<code>function check(obj) {
  return obj.toString();
}
</code>```

答:
let toString = ({name, age, language}) => `name: ${name}, age: ${age}, language: ${language}`;

const david = { name: 'David', age: 22, language: 'PHP' };

console.log(toString(david));```
</div>
</div>
</p>

<p>If you'd like to be more generic:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let toString = obj => Object.entries(obj).map(([k, v]) => `${k}: ${v}`).join(', ');

const david = { name: 'David', age: 22, language: 'PHP', favoriteFood: 'blue' };

console.log(toString(david));</code>```

Body:
I have a function that should take as an argument of the object and return a string

The code I wrote.

function check(obj) {
  return obj.toString();
}

Body:
let toString = ({name, age, language}) => `name: ${name}, age: ${age}, language: ${language}`;

const david = { name: 'David', age: 22, language: 'PHP' };

console.log(toString(david));

If you'd like to be more generic:

let toString = obj => Object.entries(obj).map(([k, v]) => `${k}: ${v}`).join(', ');

const david = { name: 'David', age: 22, language: 'PHP', favoriteFood: 'blue' };

console.log(toString(david));


问:
Checking result of EXPECT_* macros in GTest or run code when ASSERT_* failed
I have written C++ tests with GTest which basically work like this

```<code>MyData data1 = runTest(inputData);
MyData data2 = loadRegressionData();

compareMyData(data1,data2);
</code>```

with

```<code>void compareMyData(MyData const& data1, MyData const& data2)
{
  ASSERT_EQ(data1.count, data2.count);
  //pseudo:
  foreach element in data1/data2:
    EXPECT_EQ(data1.items[i], data2.items[i]);
}
</code>```

Now I would like to save the data1 contents to a file IFF the test fails and I don't see
an elegant solution yet.

First approach: Make compareMyData return the comparison result. This can't work with the ASSERT_EQ which is fatal. Writing if (!EXPECT_EQ(...)) doesn't compile so the only way I found is

```<code>bool compareMyData(MyData const& data1, MyData const& data2)
{
  EXPECT_EQ(data1.count, data2.count);
  if (data1.count != data2.count)
    return false;
  //pseudo:
  foreach element in data1/data2:
  {
    EXPECT_EQ(data1.items[i], data2.items[i]);
    if (data1.items[i]!= data2.items[i])
      return false;
  }
}
</code>```

Not very elegant :-(

Second idea: Run code when the test failed

I know I can implement ::testing::EmptyTestEventListener and get notified if a test fails, but that doesn't give me the data I want to write to file and it is "far away" from the place I'd like it to have. So my question here is: Is there a way to run code at the end of a test if it failed (e.g. catching an exception?).

To ask more general: how would you solve this?

答:
The way around:

```<code>bool HasError = false;
FAIL() << (HasError = true);
if (HasError){
 // do something
}
</code>```

Instead of FAIL() could be ASSERT_.. EXPECT_... and so on. (in output you'll see "true" it's a fee for shortcut).

Body:
I have written C++ tests with GTest which basically work like this

MyData data1 = runTest(inputData);
MyData data2 = loadRegressionData();

compareMyData(data1,data2);

with

void compareMyData(MyData const& data1, MyData const& data2)
{
  ASSERT_EQ(data1.count, data2.count);
  //pseudo:
  foreach element in data1/data2:
    EXPECT_EQ(data1.items[i], data2.items[i]);
}

Now I would like to save the data1 contents to a file IFF the test fails and I don't see
an elegant solution yet.

First approach: Make compareMyData return the comparison result. This can't work with the ASSERT_EQ which is fatal. Writing if (!EXPECT_EQ(...)) doesn't compile so the only way I found is

bool compareMyData(MyData const& data1, MyData const& data2)
{
  EXPECT_EQ(data1.count, data2.count);
  if (data1.count != data2.count)
    return false;
  //pseudo:
  foreach element in data1/data2:
  {
    EXPECT_EQ(data1.items[i], data2.items[i]);
    if (data1.items[i]!= data2.items[i])
      return false;
  }
}

Not very elegant :-(

Second idea: Run code when the test failed

I know I can implement ::testing::EmptyTestEventListener and get notified if a test fails, but that doesn't give me the data I want to write to file and it is "far away" from the place I'd like it to have. So my question here is: Is there a way to run code at the end of a test if it failed (e.g. catching an exception?).

To ask more general: how would you solve this?

Body:
The way around:

bool HasError = false;
FAIL() << (HasError = true);
if (HasError){
 // do something
}

Instead of FAIL() could be ASSERT_.. EXPECT_... and so on. (in output you'll see "true" it's a fee for shortcut).


问:
Can SQL Server run over SCO SantaCruz Operations SO (Linux)?
I wanna know if Microsoft SQL Server can run over the SO of Santa Cruz Operations SCO, Linux based SO, I already looked into the documentation available in it's web page but isn't specified, does anyone here knows if it's posible, due the fact than since the 2017 version MSSQL can run over linux, I just need to know if SCO is up to date for the support.

If you have already done the install, can you give some insights?

Thanks guys.

答:
Official platforms where you can install SQLServer: sqlserver platforms

In this case you can use Docker (
Develop once and run anywhere)


问:
Jasmine throwing error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL
I am trying to automate instagram following. I go to a profile and click on the followers link. It opens a modal type div and there are all the followers.
It first finds all the follow buttons present in the DOM and clickson them. After that it scrolls down and finds more follow buttons in the DOM and clicks on them. But after scrolling 2-3 times the automation stops and gives this error.

!Scrollable Div Image: https://imgur.com/6s3nGJs

Attaching the code below for collecting the follow buttons and clicking on them:

```<code>element(by.xpath("//div[@role='dialog']")).element(by.tagName("ul")).all(by.buttonText("Follow")).then(links => {
            console.log("Links Length" + links.length);
            if (links.length == 0) {
                this.ScrollDown();
            }
            else {
                for (let i = 0; i < links.length; i++) {
                    if (i >= links.length - 2) {
                        console.log("Scrolling Down");
                        browser.actions().sendKeys(protractor.Key.PAGE_DOWN).perform().then(function(){
                            console.log("Scrolled");
                            browser.sleep(3000);
                        });
                        break;
                    }
                    else {
                        browser.actions().mouseMove(links[i]).click().perform().then(function () {
                            console.log("Clicked on link " + (i + 1));
                            browser.sleep(3000);
                        });
                    }
                }
                this.followProfiles();
            }
        });
</code>```

ScrollDown:

```<code>console.log("Scrolling Down");
        browser.wait(browser.actions().sendKeys(protractor.Key.PAGE_DOWN).perform().then(function () {
            console.log("Scrolled down");
        }), 90000);
        browser.sleep(5000);
        this.followProfiles();
</code>```

答:
This is because Your test is taking more time than the default timeout set for jasmine.
To increase this you can add below in your protractor config file
jasmineNodeOpts: {
    defaultTimeoutInterval: 480000 //which isbequal to 6 min // you can increase it if your test take more time than this
  }</p>

Body:
I am trying to automate instagram following. I go to a profile and click on the followers link. It opens a modal type div and there are all the followers.
It first finds all the follow buttons present in the DOM and clickson them. After that it scrolls down and finds more follow buttons in the DOM and clicks on them. But after scrolling 2-3 times the automation stops and gives this error.

!Scrollable Div Image: https://imgur.com/6s3nGJs

Attaching the code below for collecting the follow buttons and clicking on them:

element(by.xpath("//div[@role='dialog']")).element(by.tagName("ul")).all(by.buttonText("Follow")).then(links => {
            console.log("Links Length" + links.length);
            if (links.length == 0) {
                this.ScrollDown();
            }
            else {
                for (let i = 0; i < links.length; i++) {
                    if (i >= links.length - 2) {
                        console.log("Scrolling Down");
                        browser.actions().sendKeys(protractor.Key.PAGE_DOWN).perform().then(function(){
                            console.log("Scrolled");
                            browser.sleep(3000);
                        });
                        break;
                    }
                    else {
                        browser.actions().mouseMove(links[i]).click().perform().then(function () {
                            console.log("Clicked on link " + (i + 1));
                            browser.sleep(3000);
                        });
                    }
                }
                this.followProfiles();
            }
        });

ScrollDown:

console.log("Scrolling Down");
        browser.wait(browser.actions().sendKeys(protractor.Key.PAGE_DOWN).perform().then(function () {
            console.log("Scrolled down");
        }), 90000);
        browser.sleep(5000);
        this.followProfiles();


问:
Can't decode a JSON file from web in VB.NET
I have some code below, which gets a response from a website fine, my code works until it gets to the decoding bit, but returns no objects.
This is my first attempt at JSON and web related data.

It works fine until:
Dim dict As Object
which returns nothing, I've tried several alternatives from the web, but am stumpt.

here is the URL of the website for the JSON:
https://www.metcheck.com/OTHER/json_data.asp?zipcode=wv12+4qz&locationID=60883&lat=52.6&lon=-2

Here is he URL that will show the JSON File:
http://ws1.metcheck.com/ENGINE/v9_0/json.asp?lat=52.6&lon=-2&lid=60883&Fc=No

```<code>Imports System.IO
Imports System.Net
Imports System.Web.Script.Serialization

Public Class Weather
    Private Sub Weather_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim uriString As String = "http://ws1.metcheck.com/ENGINE/v9_0/json.asp?lat=52.6&lon=-2&lid=60883&Fc=No"
    Dim uri As New Uri(uriString)

    Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
    request.Method = "GET"

    Dim response As HttpWebResponse = request.GetResponse()

    Dim read As New StreamReader(response.GetResponseStream())
    Dim raw As String = read.ReadToEnd

    Dim dict As Object = New JavaScriptSerializer().Deserialize(Of List(Of Object))(raw)

    For Each item As Object In dict
        TextBox1.Text = item("temperature").ToString & vbCrLf
        TextBox1.Text = item("dewpoint").ToString & vbCrLf
        TextBox1.Text = item("rain").ToString & vbCrLf
    Next

End Sub
End Class
</code>```

答:
I've not worked with JavaScriptSerializer before, but this might be because you're trying deserialize to a List(of object) instead of a more specific type. If you add series of classes matching the structure of the JSON:

```<code>Public Class Rootobject
    Public Property metcheckData As Metcheckdata
    Public Property feedCreation As Date
    Public Property feedCreator As String
    Public Property feedModel As String
    Public Property feedModelRun As String
    Public Property feedModelRunInitialTime As Date
    Public Property feedResolution As String
End Class

Public Class Metcheckdata
    Public Property forecastLocation As Forecastlocation
End Class

Public Class Forecastlocation
    Public Property forecast As List(Of Forecast)
    Public Property continent As String
    Public Property country As String
    Public Property location As String
    Public Property latitude As Single
    Public Property longitude As Single
    Public Property timezone As Integer
End Class

Public Class Forecast
    Public Property temperature As String
    Public Property dewpoint As String
    Public Property rain As String
    Public Property freezinglevel As String
    Public Property uvIndex As String
    Public Property totalcloud As String
    Public Property lowcloud As String
    Public Property medcloud As String
    Public Property highcloud As String
    Public Property humidity As String
    Public Property windspeed As String
    Public Property meansealevelpressure As String
    Public Property windgustspeed As String
    Public Property winddirection As String
    Public Property windletter As String
    Public Property icon As String
    Public Property iconName As String
    Public Property chanceofrain As String
    Public Property chanceofsnow As String
    Public Property dayOfWeek As String
    Public Property weekday As String
    Public Property sunrise As String
    Public Property sunset As String
    Public Property dayOrNight As String
    Public Property utcTime As Date
End Class
</code>```

And then try to deserialise as follows:

```<code>Dim dict As Object = New JavaScriptSerializer().Deserialize(Of Rootobject)(raw)
</code>```

Does that work as expected?

Body:
I have some code below, which gets a response from a website fine, my code works until it gets to the decoding bit, but returns no objects.
This is my first attempt at JSON and web related data.

It works fine until:
Dim dict As Object
which returns nothing, I've tried several alternatives from the web, but am stumpt.

here is the URL of the website for the JSON:
https://www.metcheck.com/OTHER/json_data.asp?zipcode=wv12+4qz&locationID=60883&lat=52.6&lon=-2

Here is he URL that will show the JSON File:
http://ws1.metcheck.com/ENGINE/v9_0/json.asp?lat=52.6&lon=-2&lid=60883&Fc=No

Imports System.IO
Imports System.Net
Imports System.Web.Script.Serialization

Public Class Weather
    Private Sub Weather_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim uriString As String = "http://ws1.metcheck.com/ENGINE/v9_0/json.asp?lat=52.6&lon=-2&lid=60883&Fc=No"
    Dim uri As New Uri(uriString)

    Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
    request.Method = "GET"

    Dim response As HttpWebResponse = request.GetResponse()

    Dim read As New StreamReader(response.GetResponseStream())
    Dim raw As String = read.ReadToEnd

    Dim dict As Object = New JavaScriptSerializer().Deserialize(Of List(Of Object))(raw)

    For Each item As Object In dict
        TextBox1.Text = item("temperature").ToString & vbCrLf
        TextBox1.Text = item("dewpoint").ToString & vbCrLf
        TextBox1.Text = item("rain").ToString & vbCrLf
    Next

End Sub
End Class

Body:
I've not worked with JavaScriptSerializer before, but this might be because you're trying deserialize to a List(of object) instead of a more specific type. If you add series of classes matching the structure of the JSON:

Public Class Rootobject
    Public Property metcheckData As Metcheckdata
    Public Property feedCreation As Date
    Public Property feedCreator As String
    Public Property feedModel As String
    Public Property feedModelRun As String
    Public Property feedModelRunInitialTime As Date
    Public Property feedResolution As String
End Class

Public Class Metcheckdata
    Public Property forecastLocation As Forecastlocation
End Class

Public Class Forecastlocation
    Public Property forecast As List(Of Forecast)
    Public Property continent As String
    Public Property country As String
    Public Property location As String
    Public Property latitude As Single
    Public Property longitude As Single
    Public Property timezone As Integer
End Class

Public Class Forecast
    Public Property temperature As String
    Public Property dewpoint As String
    Public Property rain As String
    Public Property freezinglevel As String
    Public Property uvIndex As String
    Public Property totalcloud As String
    Public Property lowcloud As String
    Public Property medcloud As String
    Public Property highcloud As String
    Public Property humidity As String
    Public Property windspeed As String
    Public Property meansealevelpressure As String
    Public Property windgustspeed As String
    Public Property winddirection As String
    Public Property windletter As String
    Public Property icon As String
    Public Property iconName As String
    Public Property chanceofrain As String
    Public Property chanceofsnow As String
    Public Property dayOfWeek As String
    Public Property weekday As String
    Public Property sunrise As String
    Public Property sunset As String
    Public Property dayOrNight As String
    Public Property utcTime As Date
End Class

And then try to deserialise as follows:

Dim dict As Object = New JavaScriptSerializer().Deserialize(Of Rootobject)(raw)

Does that work as expected?


问:
How to call a function from another class to main class
I created another class (calculations) and created a function in it which checks if a number is even or odd. I want to call this function in my program class so it can check if variable (result) is even or odd.

I tried to call the method like: CheckEvenOrOdd(result).

```<code>class Program
{
    static void Main(string[] args)
    {
        int number1;
        int number2;
        int result;

        Console.Write("Enter a number: ");
        number1 = int.Parse(Console.ReadLine());

        Console.Write("Enter a second number: ");
        number2 = int.Parse(Console.ReadLine());

        result = number2 * number2;

        Console.WriteLine($"The total is: {result} ");
        Console.WriteLine("AND");

       // i tried this here but it doesn't work: CheckEvenOrOdd(result)

    }

}

class Calculations
{
    public static void CheckEvenOrOdd(int numb)
    {
        if (numb % 2 == 0)
        {
            Console.WriteLine("The number is even");

        }
        else
        {
            Console.WriteLine("The number is odd ");
        }

    }

}
</code>```

答:
Because your method is in a different class, you're going to have to make it static and then call it by class name first then method name. If it's not static you're going to have to instantiate a new instance of that class before being able to access any of its methods.

(btw you're multiplying number2 by number2, changed it for you as well in the codes provided below hehe)

Static:

```<code>class Program
{
    static void Main(string[] args)
    {
        int number1;
        int number2;
        int result;

        Console.Write("Enter a number: ");
        number1 = int.Parse(Console.ReadLine());

        Console.Write("Enter a second number: ");
        number2 = int.Parse(Console.ReadLine());

        result = number1 * number2;

        Console.WriteLine($"The total is: {result} ");
        Console.WriteLine("AND");

        Calculations.CheckEvenOrOdd(result);
        Console.ReadLine();
     }
}

public static class Calculations
{
    public static void CheckEvenOrOdd(int numb)
    {
        if (numb % 2 == 0)
        {
            Console.WriteLine("The number is even");
        }
        else
        {
            Console.WriteLine("The number is odd ");
        }
    }
}
</code>```

Not Static:

```<code>class Program
{
    static void Main(string[] args)
    {
        int number1;
        int number2;
        int result;

        Console.Write("Enter a number: ");
        number1 = int.Parse(Console.ReadLine());

        Console.Write("Enter a second number: ");
        number2 = int.Parse(Console.ReadLine());

        result = number1 * number2;

        Console.WriteLine($"The total is: {result} ");
        Console.WriteLine("AND");

        Calculations calc = new Calculations();
        calc.CheckEvenOrOdd(result);
        Console.ReadLine();
     }
}

public class Calculations
{
    public void CheckEvenOrOdd(int numb)
    {
        if (numb % 2 == 0)
        {
            Console.WriteLine("The number is even");
        }
        else
        {
            Console.WriteLine("The number is odd ");
        }
    }
}
</code>```

Body:
I created another class (calculations) and created a function in it which checks if a number is even or odd. I want to call this function in my program class so it can check if variable (result) is even or odd.

I tried to call the method like: CheckEvenOrOdd(result).

class Program
{
    static void Main(string[] args)
    {
        int number1;
        int number2;
        int result;

        Console.Write("Enter a number: ");
        number1 = int.Parse(Console.ReadLine());

        Console.Write("Enter a second number: ");
        number2 = int.Parse(Console.ReadLine());

        result = number2 * number2;

        Console.WriteLine($"The total is: {result} ");
        Console.WriteLine("AND");

       // i tried this here but it doesn't work: CheckEvenOrOdd(result)

    }

}

class Calculations
{
    public static void CheckEvenOrOdd(int numb)
    {
        if (numb % 2 == 0)
        {
            Console.WriteLine("The number is even");

        }
        else
        {
            Console.WriteLine("The number is odd ");
        }

    }

}

Body:
Because your method is in a different class, you're going to have to make it static and then call it by class name first then method name. If it's not static you're going to have to instantiate a new instance of that class before being able to access any of its methods.

(btw you're multiplying number2 by number2, changed it for you as well in the codes provided below hehe)

Static:

class Program
{
    static void Main(string[] args)
    {
        int number1;
        int number2;
        int result;

        Console.Write("Enter a number: ");
        number1 = int.Parse(Console.ReadLine());

        Console.Write("Enter a second number: ");
        number2 = int.Parse(Console.ReadLine());

        result = number1 * number2;

        Console.WriteLine($"The total is: {result} ");
        Console.WriteLine("AND");

        Calculations.CheckEvenOrOdd(result);
        Console.ReadLine();
     }
}

public static class Calculations
{
    public static void CheckEvenOrOdd(int numb)
    {
        if (numb % 2 == 0)
        {
            Console.WriteLine("The number is even");
        }
        else
        {
            Console.WriteLine("The number is odd ");
        }
    }
}

Not Static:

class Program
{
    static void Main(string[] args)
    {
        int number1;
        int number2;
        int result;

        Console.Write("Enter a number: ");
        number1 = int.Parse(Console.ReadLine());

        Console.Write("Enter a second number: ");
        number2 = int.Parse(Console.ReadLine());

        result = number1 * number2;

        Console.WriteLine($"The total is: {result} ");
        Console.WriteLine("AND");

        Calculations calc = new Calculations();
        calc.CheckEvenOrOdd(result);
        Console.ReadLine();
     }
}

public class Calculations
{
    public void CheckEvenOrOdd(int numb)
    {
        if (numb % 2 == 0)
        {
            Console.WriteLine("The number is even");
        }
        else
        {
            Console.WriteLine("The number is odd ");
        }
    }
}


答:
There are a couple ways to solve this.  First, you could just use std::min and std::max to get the right values like

```<code>Approx::Approx (int size, int dim) : SWAP(std::max(dim, size), std::min(dim, size)) {}
</code>```

Secondly, you could write a lambda and immediately invoke it like

```<code>Approx::Approx (int size, int dim) : SWAP([](auto size, auto dim){ if (size > dim) return Field(size, dim); else return Field(dim, size); }(size, dim)) {}
</code>```

If you don't like having the code in the initialization list then you can out it into a private static function and call the function instead.

Title: C++ how to check a condition before using initialiser list?

Body:
There are a couple ways to solve this.  First, you could just use std::min and std::max to get the right values like

Approx::Approx (int size, int dim) : SWAP(std::max(dim, size), std::min(dim, size)) {}

Secondly, you could write a lambda and immediately invoke it like

Approx::Approx (int size, int dim) : SWAP([](auto size, auto dim){ if (size > dim) return Field(size, dim); else return Field(dim, size); }(size, dim)) {}

If you don't like having the code in the initialization list then you can out it into a private static function and call the function instead.


问:
How to include a literal '#' in a Tatsu grammar?
I can't get Tatsu to parse a grammar that includes a literal '#'.

Here is a minimal example:

```<code>G = r'''
atom = /[0-9]+/
     | '#' atom
     ;
'''

p = tatsu.compile(G)
p.parse('#345', trace=True)
</code>```

The parse throws a FailedParse exception. The trace seems to show that the parser is not matching the '#' literal:

```<code><atom ~1:1
#345
!'' /[0-9]+/
!'#'
!atom ~1:1
#345
</code>```

If I change the grammar to use a symbol other than '#', it works fine.  For example this works:

```<code>G1 = r'''
atom = /[0-9]+/
     | '@' atom
     ;
'''

tatsu.parse(G1, '@345')     --> ['@', '345']
</code>```

Unfortunately, I can't change the format of the input data.

答:
This is likely a bug in the version of TatSu you are using.

If you need to stick to that version, please try including @@eol_comments :: // or a similar pattern in the grammar.

This works for me:

[ins] In [1]: import tatsu

[ins] In [2]: G = r'''
         ...: atom = /[0-9]+/
         ...:      | '#' atom
         ...:      ;
         ...: '''
         ...:
         ...: p = tatsu.compile(G)
         ...: p.parse('#345', trace=True)
↙atom ~1:1
#345
≢'' /[0-9]+/
#345
≡'#'
345
↙atom↙atom ~1:2
345
≡'345' /[0-9]+/
≡atom↙atom
≡atom
Out[2]: ('#', '345')

```

AFTERNOTE: Yes, the above output is from the master version of TatSu (sequences return tuple), but I just checked against v4.4.0, and it's equivalent.

Body:
I can't get Tatsu to parse a grammar that includes a literal '#'.

Here is a minimal example:

G = r'''
atom = /[0-9]+/
     | '#' atom
     ;
'''

p = tatsu.compile(G)
p.parse('#345', trace=True)

The parse throws a FailedParse exception. The trace seems to show that the parser is not matching the '#' literal:

<atom ~1:1
#345
!'' /[0-9]+/
!'#'
!atom ~1:1
#345

If I change the grammar to use a symbol other than '#', it works fine.  For example this works:

G1 = r'''
atom = /[0-9]+/
     | '@' atom
     ;
'''

tatsu.parse(G1, '@345')     --> ['@', '345']

Unfortunately, I can't change the format of the input data.

Body:
This is likely a bug in the version of TatSu you are using.

If you need to stick to that version, please try including @@eol_comments :: // or a similar pattern in the grammar.

This works for me:

[ins] In [1]: import tatsu

[ins] In [2]: G = r'''
         ...: atom = /[0-9]+/
         ...:      | '#' atom
         ...:      ;
         ...: '''
         ...:
         ...: p = tatsu.compile(G)
         ...: p.parse('#345', trace=True)
↙atom ~1:1
#345
≢'' /[0-9]+/
#345
≡'#'
345
↙atom↙atom ~1:2
345
≡'345' /[0-9]+/
≡atom↙atom
≡atom
Out[2]: ('#', '345')

AFTERNOTE: Yes, the above output is from the master version of TatSu (sequences return tuple), but I just checked against v4.4.0, and it's equivalent.


问:
Dropdown list elements contains substring/pattern : Disable element
I got a dropdown list and options, as described below.

If I try to click/select on "POICaption-XX423366 [DONOT ALLOW SELECT FOR THIS]" I am able to restrict this value for selection.

```<code>    <select multiple="multiple" size=20 id="caption_collection">

    <optgroup label="MAKE A CHOICE">
    <option>SHOW ALL ENABLED CAPTIONS</option>
    <option>SHOW ALL DISABLED CAPTIONS</option>
    <option>SHOW ALL LISTED CAPTIONS</option>
    </optgroup>
    <optgroup label="ELSE SELECT ONE OR MULTIPLE">
             <option>ALWCaption-A100104  [ALLOW SELECT HERE]</option>
           <option>ZSDCaption-Z100104  [ALLOW SELECT HERE]</option>
           <option>XCDCaption-S100104  [ALLOW SELECT HERE]</option>
           <option>DCVCaption-Q100104  [ALLOW SELECT HERE]</option>
           <option>ERTCaption-D100104  [ALLOW SELECT HERE]</option>
           <option>BNMCaption-XX223366 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>XWECaption-XX243356 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>QWECaption-XX323356 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>DFGCaption-XX228866 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>TYUCaption-XX220066 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>POICaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>GHJCaption-D100104  [ALLOW SELECT HERE]</option>
           <option>LKICaption-D100104  [ALLOW SELECT HERE]</option>
           <option>UYTCaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
           </optgroup>

    </select>
    <br><br>
    <div>
      <textarea id="selected" rows="4" cols="56" readonly></textarea>
    </div>
</code>```

```<code>const needle = '[DO NOT ALLOW SELECT FOR THIS]';
// using jQuery:
$('select option').prop('disabled', function() {
return this.text.includes(needle);
});

$("#caption_collection").change(function() {
$('#selected').html(' ');
$("#caption_collection option:selected").each(function() {
var $this = $(this);
if ($this.length) {
  var selText = $this.text();
   console.log(selText);
  $('#selected').append(selText + ', ');
  //$('#selected').text('Only Captions allowed are:').append(selText + ', ');
}
});

});
</code>```

UPDATE:
Updated with working code, but need more guidance.

PROBLEM:
Got 3 options under optgroup ""MAKE A CHOICE" as below

```<code>SHOW ALL ENABLED CAPTIONS
SHOW ALL DISABLED CAPTIONS
SHOW ALL LISTED CAPTIONS
</code>```

What i want is clicking on each get me the value as shown below

```<code>SHOW ALL ENABLED CAPTIONS
     A100104  ,Z100104  ,S100104  ,Q100104  ,D100104  ,D100104  ,D100104

SHOW ALL DISABLED CAPTIONS
     XX223366  ,XX243356  ,XX323356  ,XX228866  ,XX220066  ,XX423366  ,XX423366

SHOW ALL LISTED CAPTIONS
    XX223366  ,XX243356  ,XX323356  ,XX228866  ,XX220066  ,XX423366  ,XX423366, A100104  ,Z100104  ,S100104  ,Q100104  ,D100104  ,D100104  ,D100104
</code>```

AND under optgroup label="ELSE SELECT ONE OR MULTIPLE"
need to display one or more value as :

```<code>A100104  ,Z100104  ,S100104
A100104
</code>```

Though I can extract

```<code>var stre = "LKICaption-A100104 [LKI   hfjdlfdlfjl]"
var str2 = stre.split('-');
var strval = str2[str2.length - 1];
alert(strval) // A100104 [LKI   hfjdlfdlfjl] but I need only A100104

alert(strval.split(' ')[0]) // Worked this way o/p is A100104
</code>```

答:
You have the right idea. Change the disablefor string to the below, since that is the substring we're looking for:

```<code>var disablefor= "[DO NOT ALLOW SELECT FOR THIS]";
</code>```

Use the includes method to check for a substring:

```<code>if($thisOption.val().includes(disablefor)) {
    $thisOption.attr("disabled", "disabled");
}
</code>```

Body:
I got a dropdown list and options, as described below.

If I try to click/select on "POICaption-XX423366 [DONOT ALLOW SELECT FOR THIS]" I am able to restrict this value for selection.

    <select multiple="multiple" size=20 id="caption_collection">

    <optgroup label="MAKE A CHOICE">
    <option>SHOW ALL ENABLED CAPTIONS</option>
    <option>SHOW ALL DISABLED CAPTIONS</option>
    <option>SHOW ALL LISTED CAPTIONS</option>
    </optgroup>
    <optgroup label="ELSE SELECT ONE OR MULTIPLE">
             <option>ALWCaption-A100104  [ALLOW SELECT HERE]</option>
           <option>ZSDCaption-Z100104  [ALLOW SELECT HERE]</option>
           <option>XCDCaption-S100104  [ALLOW SELECT HERE]</option>
           <option>DCVCaption-Q100104  [ALLOW SELECT HERE]</option>
           <option>ERTCaption-D100104  [ALLOW SELECT HERE]</option>
           <option>BNMCaption-XX223366 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>XWECaption-XX243356 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>QWECaption-XX323356 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>DFGCaption-XX228866 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>TYUCaption-XX220066 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>POICaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
           <option>GHJCaption-D100104  [ALLOW SELECT HERE]</option>
           <option>LKICaption-D100104  [ALLOW SELECT HERE]</option>
           <option>UYTCaption-XX423366 [DO NOT ALLOW SELECT FOR THIS]</option>
           </optgroup>

    </select>

      <textarea id="selected" rows="4" cols="56" readonly></textarea>

const needle = '[DO NOT ALLOW SELECT FOR THIS]';
// using jQuery:
$('select option').prop('disabled', function() {
return this.text.includes(needle);
});

$("#caption_collection").change(function() {
$('#selected').html(' ');
$("#caption_collection option:selected").each(function() {
var $this = $(this);
if ($this.length) {
  var selText = $this.text();
   console.log(selText);
  $('#selected').append(selText + ', ');
  //$('#selected').text('Only Captions allowed are:').append(selText + ', ');
}
});

});

UPDATE:
Updated with working code, but need more guidance.

PROBLEM:
Got 3 options under optgroup ""MAKE A CHOICE" as below

SHOW ALL ENABLED CAPTIONS
SHOW ALL DISABLED CAPTIONS
SHOW ALL LISTED CAPTIONS

What i want is clicking on each get me the value as shown below

SHOW ALL ENABLED CAPTIONS
     A100104  ,Z100104  ,S100104  ,Q100104  ,D100104  ,D100104  ,D100104

SHOW ALL DISABLED CAPTIONS
     XX223366  ,XX243356  ,XX323356  ,XX228866  ,XX220066  ,XX423366  ,XX423366

SHOW ALL LISTED CAPTIONS
    XX223366  ,XX243356  ,XX323356  ,XX228866  ,XX220066  ,XX423366  ,XX423366, A100104  ,Z100104  ,S100104  ,Q100104  ,D100104  ,D100104  ,D100104

AND under optgroup label="ELSE SELECT ONE OR MULTIPLE"
need to display one or more value as :

A100104  ,Z100104  ,S100104
A100104

Though I can extract

var stre = "LKICaption-A100104 [LKI   hfjdlfdlfjl]"
var str2 = stre.split('-');
var strval = str2[str2.length - 1];
alert(strval) // A100104 [LKI   hfjdlfdlfjl] but I need only A100104

alert(strval.split(' ')[0]) // Worked this way o/p is A100104

Body:
You have the right idea. Change the disablefor string to the below, since that is the substring we're looking for:

var disablefor= "[DO NOT ALLOW SELECT FOR THIS]";

Use the includes method to check for a substring:

if($thisOption.val().includes(disablefor)) {
    $thisOption.attr("disabled", "disabled");
}


问:
Access Electron Api from React
I’m building up a new react app on electron , I want to access electron api from react Component to close the app with a button.

i tried to import electron but it give me module not found

```<code>import React, { Component } from 'react';
import './Frame.scss';

class Frame extends Component {
  render() {
    return(
      <div className="kr-app-frame">
        <div className="kr-app-frame-buttons-block">
            <button id="close" className="kr-app-frame-button">X</button>
        </div>
      </div>
    )
  }
}

export default Frame;
</code>```

答:
instead of :

```<code>const { remote } = require('electron');
</code>```

use this :

```<code>const { remote } = window.require('electron');
</code>```

Title: Access Electron Api from React

Body:
I’m building up a new react app on electron , I want to access electron api from react Component to close the app with a button.

i tried to import electron but it give me module not found

import React, { Component } from 'react';
import './Frame.scss';

class Frame extends Component {
  render() {
    return(

            <button id="close" className="kr-app-frame-button">X</button>

    )
  }
}

export default Frame;

Body:
instead of :

const { remote } = require('electron');

use this :

const { remote } = window.require('electron');


问:
Tawk.to Not working inside an IONIC App but working on deployed browser
I am trying to integrate Tawk.to in my ionic app but the widget is not showing at all in my app. But, when i do ionic serve and run it on browser the widget shows correctly.
Is it because ionic app is not allowing an iframe to load? </p>

```<code> <script type="text/javascript">
 var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
 (function(){
  var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
   s1.async=true;
   s1.src='https://embed.tawk.to/.../default';
   s1.charset='UTF-8';
   s1.setAttribute('crossorigin','*');
   s0.parentNode.insertBefore(s1,s0);

  })();
  </script>
  <!--End of Tawk.to Script-->
   </div>
</code>```

答:
put in your config.xml
...</p>

```<code>   ...
   <access origin="*" />
   <allow-intent href="*" />
   <allow-navigation href="*" />
   ...
   <plugin name="cordova-plugin-ionic-webview" spec="^1.1.16" />
</code>```

Body:
put in your config.xml
...

   ...
   <access origin="*" />
   <allow-intent href="*" />
   <allow-navigation href="*" />
   ...
   <plugin name="cordova-plugin-ionic-webview" spec="^1.1.16" />


问:
Socket chunk/buffer size
I’m using select on a socket connection in Python with a chunk size of 1024 to send two wav files. The server is listening to two sockets which are both sending chunks of 1024 (checked with print statement). The chunk data is then put into an empty numpy array for further processing however, when I check the size of the numpy array, the value is only 512 for each array, leading to a combined 1024 chunk on the receiving end and resulting in distorted audio. I’ve tried adjusting chunk size, as well as using

```<code>data = s.recv(1024)
data += s.recv(1024)
</code>```

Which results in both sizes being 1024, however the audio ends up being sped up. Can provide code upon request. Any help is much appreciated!

答:
TCP is a byte streaming protocol.  You are guaranteed to get the bytes in the same order sent, but not in the same chunk sizes as sent.  Use (or design) a higher level protocol (HTTP, etc.) to ensure you receive all the bytes sent.

For example, the first bytes sent could be the null-terminated file name followed by the file size as a null-terminated string, followed by the file contents.  The on accepting the connection, the receiver buffers s.recv(1024) calls and extracts the file name and file size terminated by nulls, then continues reading until the buffer contains at least "file size" bytes.

Another option is to just transmit the file and close the connection, the receiver buffers everything received until recv() returns zero bytes, indicating the connection was closed.

The first option allows for sending multiple files without closing the connection.

Title: Socket chunk/buffer size

Body:
I’m using select on a socket connection in Python with a chunk size of 1024 to send two wav files. The server is listening to two sockets which are both sending chunks of 1024 (checked with print statement). The chunk data is then put into an empty numpy array for further processing however, when I check the size of the numpy array, the value is only 512 for each array, leading to a combined 1024 chunk on the receiving end and resulting in distorted audio. I’ve tried adjusting chunk size, as well as using

data = s.recv(1024)
data += s.recv(1024)

Which results in both sizes being 1024, however the audio ends up being sped up. Can provide code upon request. Any help is much appreciated!


问:
Python importing from a higher directory in same project
I am having a issue importing a python file from another directory. Below is my project layout.

```<code>project/
   include/
     networking/
       ssl.py
     process.py
</code>```

Inside my ssl.py file I am trying to access a function inside process.py

I have tried

```<code>from include.process import procfunction
</code>```

This returns a error

```<code>cannot import name 'procfunction' from 'include.process'
</code>```

答:
When you run a python file and have import statements, it is looking at your current directory of that file. In order to move out 1 directory use '..'

Example - Inside your ssl.py:

```<code>from ..process import procfunction
</code>```

Body:
I am having a issue importing a python file from another directory. Below is my project layout.

project/
   include/
     networking/
       ssl.py
     process.py

Inside my ssl.py file I am trying to access a function inside process.py

I have tried

from include.process import procfunction

This returns a error

cannot import name 'procfunction' from 'include.process'

Body:
When you run a python file and have import statements, it is looking at your current directory of that file. In order to move out 1 directory use '..'

Example - Inside your ssl.py:

from ..process import procfunction


问:
Accesing an array item for a class binding in a v-for loop
When using Vue's dynamic class binding to use a ternary operator to bind a class based on the currentValue and the id of the items in my looped array, Vue seems to ignore the class completely.

Both the 'first' and 'last' class bindings work, but when using the item.id, the class is never assigned. However the function is fired because the event is successfully emitted and the currentValue var updated.

ContentSwitcher.vue

```<code><template>
  <div class="content-switcher-wrapper">
    <section class="content-items">
      <a v-for="(item, index) in options"
         class="content-item"
         :class="[ index === 0 ? 'first' : '',
                   index === options.length -1 ? 'last' : '',
                   item.id === currentValue ? 'selected' : '',]"
         @click="updateSelected(item.id)">
        {{ item.text }}
      </a>
    </section>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';

@Component
export default class ContentSwitcher extends Vue {
  @Prop()
  public options!: any;

  public currentValue!: string;

  public created(): void {
    this.currentValue = this.options[0].id;
  }

  public updateSelected(value: string): void {
    this.currentValue = value;
    this.$emit('contentSwitcherUpdated', value);
  }
}
</script>
</code>```

Usage

```<code><content-switcher :options="tabSwitcherOptions"></content-switcher>
</code>```

Options passed

```<code>  private tabSwitcherOptions: any = [
    {
      id: 'week',
      text: 'Week',
    },
    {
      id: 'month',
      text: 'Maand',
    },
  ];
</code>```

When clicking on "Month", the event is emmited, however the classed 'selected' is never added to the tag.

答:
The problem with your component is that your data property in the typescript class is undefined upon initialization. So currentValue is not reactive.

From the official Vue documentation

To take consistency between the decorator behavior of Babel and TypeScript, vue-class-component does not make a property reactive if it has undefined as initial value. You should use null as initial value or use data hook to initialize undefined property instead.

You need to initialize your data properties using a hook:

```<code>@Component
export default class ContentSwitcher extends Vue {
  @Prop()
  public options!: any;

  public currentValue!: string;

  // Here!
  data () {
    return {
      currentValue: undefined
    }
  }

  public created(): void {
    this.currentValue = this.options[0].id;
  }

  public updateSelected(value: string): void {
    this.currentValue = value;
    this.$emit('contentSwitcherUpdated', value);
  }
}
</code>```

Here's the working example on codesandox

Also, your code works fine when I test it in Javascript.

Vue.config.productionTip = false;

Vue.component('content-switcher', {
  template: `

  Selected: {{ currentValue }}

      {{ item.text }}

  `,
  props: {
    options: Array
  },
  data: () => ({
    currentValue: undefined,
  }),
  created() {
    this.currentValue = this.options[0].id;
  },
  methods: {
    updateSelected(value) {
      this.currentValue = value;
    }
  }
});

new Vue({
   el: '#app',
   template: `

     <content-switcher :options="tabSwitcherOptions" />

   `,
   data: () => ({
      tabSwitcherOptions: [
        {
          id: 'week',
          text: 'Week',
        },
        {
          id: 'day',
          text: 'Day',
        },
        {
          id: 'month',
          text: 'Maand',
        },
      ]
   })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.first { color: red; }
.last { color: green; }
.selected { font-size: 2em; }</code>```

```

Body:
When using Vue's dynamic class binding to use a ternary operator to bind a class based on the currentValue and the id of the items in my looped array, Vue seems to ignore the class completely.

Both the 'first' and 'last' class bindings work, but when using the item.id, the class is never assigned. However the function is fired because the event is successfully emitted and the currentValue var updated.

ContentSwitcher.vue

<template>

        {{ item.text }}

</template>

Usage

<content-switcher :options="tabSwitcherOptions"></content-switcher>

Options passed

  private tabSwitcherOptions: any = [
    {
      id: 'week',
      text: 'Week',
    },
    {
      id: 'month',
      text: 'Maand',
    },
  ];

When clicking on "Month", the event is emmited, however the classed 'selected' is never added to the tag.

Body:
The problem with your component is that your data property in the typescript class is undefined upon initialization. So currentValue is not reactive.

From the official Vue documentation

To take consistency between the decorator behavior of Babel and TypeScript, vue-class-component does not make a property reactive if it has undefined as initial value. You should use null as initial value or use data hook to initialize undefined property instead.

You need to initialize your data properties using a hook:

@Component
export default class ContentSwitcher extends Vue {
  @Prop()
  public options!: any;

  public currentValue!: string;

  // Here!
  data () {
    return {
      currentValue: undefined
    }
  }

  public created(): void {
    this.currentValue = this.options[0].id;
  }

  public updateSelected(value: string): void {
    this.currentValue = value;
    this.$emit('contentSwitcherUpdated', value);
  }
}

Here's the working example on codesandox

Also, your code works fine when I test it in Javascript.

Vue.config.productionTip = false;

Vue.component('content-switcher', {
  template: `
<div class="content-switcher-wrapper">
  Selected: {{ currentValue }}
  </br>
  <section class="content-items">
    <a v-for="(item, index) in options"
       class="content-item"
       :class="[ index === 0 ? 'first' : '',
                 index === options.length -1 ? 'last' : '',
                 item.id === currentValue ? 'selected' : '',]"
       @click="updateSelected(item.id)">
      {{ item.text }}
    </a>
  </section>
</div>
  `,
  props: {
    options: Array
  },
  data: () => ({
    currentValue: undefined,
  }),
  created() {
    this.currentValue = this.options[0].id;
  },
  methods: {
    updateSelected(value) {
      this.currentValue = value;
    }
  }
});

new Vue({
   el: '#app',
   template: `
    <div>
     <content-switcher :options="tabSwitcherOptions" />
   </div>
   `,
   data: () => ({
      tabSwitcherOptions: [
        {
          id: 'week',
          text: 'Week',
        },
        {
          id: 'day',
          text: 'Day',
        },
        {
          id: 'month',
          text: 'Maand',
        },
      ]
   })
})

.first { color: red; }
.last { color: green; }
.selected { font-size: 2em; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>


问:
Limit text length to n lines using CSS
Is it possible to limit a text length to "n" lines using CSS (or cut it when overflows vertically).

text-overflow: ellipsis; only works for 1 line text.

original text:

Ultrices natoque mus mattis, aliquam, cras in pellentesque

  tincidunt elit purus lectus, vel ut aliquet, elementum nunc

  nunc rhoncus placerat urna! Sit est sed! Ut penatibus turpis

  mus tincidunt! Dapibus sed aenean, magna sagittis, lorem velit

wanted output (2 lines):

Ultrices natoque mus mattis, aliquam, cras in pellentesque

  tincidunt elit purus lectus, vel ut aliquet, elementum...

答:
If you want to focus on each letter you can do like that, I refer to this question

function truncate(source, size) {
  return source.length > size ? source.slice(0, size - 1) + "…" : source;
}

var text = truncate('Truncate text to fit in 3 lines', 14);
console.log(text);```
</div>
</div>
</p>

<p>If you want to focus on each <code>word</code> you can do like that + space</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const truncate = (title, limit = 14) => {  // 14 IS DEFAULT ARGUMENT
    const newTitle = [];
    if (title.length > limit) {
        title.split(' ').reduce((acc, cur) => {
            if (acc + cur.length <= limit) {
                newTitle.push(cur);
            }
            return acc + cur.length;
        }, 0);

        return newTitle.join(' ') + '...'
    }
    return title;
}

var text = truncate('Truncate text to fit in 3 lines', 14);
console.log(text);</code>```

If you want to focus on each word you can do like that + without space

const truncate = (title, limit = 14) => {  // 14 IS DEFAULT ARGUMENT
    const newTitle = [];
    if (title.length > limit) {
        Array.prototype.slice.call(title).reduce((acc, cur) => {
            if (acc + cur.length <= limit) {
                newTitle.push(cur);
            }
            return acc + cur.length;
        }, 0);

        return newTitle.join('') + '...'
    }
    return title;
}

var text = truncate('Truncate text to fit in 3 lines', 14);
console.log(text);```

ContentLicense: CC BY-SA 2.5

Title: Limit text length to n lines using CSS

Body:
If you want to focus on each letter you can do like that, I refer to this question

function truncate(source, size) {
  return source.length > size ? source.slice(0, size - 1) + "…" : source;
}

var text = truncate('Truncate text to fit in 3 lines', 14);
console.log(text);

If you want to focus on each word you can do like that + space

const truncate = (title, limit = 14) => {  // 14 IS DEFAULT ARGUMENT
    const newTitle = [];
    if (title.length > limit) {
        title.split(' ').reduce((acc, cur) => {
            if (acc + cur.length <= limit) {
                newTitle.push(cur);
            }
            return acc + cur.length;
        }, 0);

        return newTitle.join(' ') + '...'
    }
    return title;
}

var text = truncate('Truncate text to fit in 3 lines', 14);
console.log(text);

If you want to focus on each word you can do like that + without space

const truncate = (title, limit = 14) => {  // 14 IS DEFAULT ARGUMENT
    const newTitle = [];
    if (title.length > limit) {
        Array.prototype.slice.call(title).reduce((acc, cur) => {
            if (acc + cur.length <= limit) {
                newTitle.push(cur);
            }
            return acc + cur.length;
        }, 0);

        return newTitle.join('') + '...'
    }
    return title;
}

var text = truncate('Truncate text to fit in 3 lines', 14);
console.log(text);


问:
How to use tag filtering in Atlas
New to the Atlas project (and also to Java), I am trying some things out. I am looking for the preferred way to combine the instructions given here and here to apply tag filtering on an Atlas.

Would the below be a good approach or is there a better alternative?

String definition = "highway->residential";
final TaggableFilter filter = TaggableFilter.forDefinition(definition);
final Optional<Atlas> predicateAtlas = atlas.subAtlas(filter::test, AtlasCutType.SOFT_CUT);
```

答:
Your code would work and produce an other Atlas that contains all elements with highway=residential. It is important to note that Atlas has to follow feature integrity (i.e. an Edge cannot exist without its end Nodes) which mean some features without the tag you specified here might still be pulled in (connected Nodes, or parent Relations for example).

Another way to only get the features that are tagged highway=residential would be to not force them to be fed back to an Atlas, but just printed, or handled with a custom function of your choice:

```<code>String definition = "highway->residential";
final TaggableFilter filter = TaggableFilter.forDefinition(definition);
atlas.entities(filter).forEach(entity -> ...);
</code>```

Title: How to use tag filtering in Atlas

Body:
Your code would work and produce an other Atlas that contains all elements with highway=residential. It is important to note that Atlas has to follow feature integrity (i.e. an Edge cannot exist without its end Nodes) which mean some features without the tag you specified here might still be pulled in (connected Nodes, or parent Relations for example).

Another way to only get the features that are tagged highway=residential would be to not force them to be fed back to an Atlas, but just printed, or handled with a custom function of your choice:

String definition = "highway->residential";
final TaggableFilter filter = TaggableFilter.forDefinition(definition);
atlas.entities(filter).forEach(entity -> ...);


问:
Find target architecture for Linux system using command line
I am working with a proprietary unit used for industrial applications that has it's own development process. This unit runs a version of Linux but is shipped without a C++ compiler. I am attempting to create a compiler for this unit from source code using a different Ubuntu 18.04 system. I am following this guide: https://preshing.com/20141119/how-to-build-a-gcc-cross-compiler/

I need to know how to find the target architecture for the following command:
    ../binutils-2.24/configure --prefix=/opt/cross --target=aarch64-linux --disable-multilib

The example in the guide is aarch64-linux but I'm not sure how to figure out what I need to use for the particular unit I'm creating the compiler for. I have access to the command line on the unit although some commands may be missing.

What is the target and how do I figure out what my unit is using?

答:
would uname contain the info you need ?

https://renenyffenegger.ch/notes/Linux/shell/commands/uname


问:
Playing an audio file
I'm looking for a basic example for playing an .mp3 or .wav file in the browser. Ideally, also for playing multiple files at overlapping times.

Most libraries I found are concerned with sound synthesis and their examples focus on that topic.

答:
I ended up using cljs-bach, a wrapper around the Web Audio API. It's easier than to use than HTML5 Audio, since it enables the playback of multiple audio buffers at the same time without the need to create multiple DOM nodes.

Here's the kind of example I was looking for:

(ns foo.bar (:require [cljs-bach.synthesis :as b]))

(defonce audio-context (b/audio-context))

(defn playback-mp3
  [url]
  (let [mp3 (b/connect-> (b/sample url)  ; read file using js ajax, including caching
                         (b/gain 0.5)    ; you can chain optional effects here
                         b/destination)  ; loudspeakers
        ]
    (b/run-with mp3
                audio-context
                (b/current-time audio-context)
                3.0  ; play for 3 seconds
     )))

; (playback-mp3 "/music/qux.mp3")
```

Title: Playing an audio file


问:
Why does Python add newline characters to some list elements?
I'm reading files from a text file called WeaponShack.list

These are the contents of 'weapon shack.list':

```<code>Grenade
Ak-47
Shotgun
Makarov
Minigun
Bat
Katana
Chainsaw
Flamethrower
</code>```

There are no whitespaces. These items are copy-pasted as is.

I try to strip down some newline characters but the "\n" character just keeps showing up at some elements when I print the list. I don't understand why.

I tried using .strip('\n') but the "\n" characters still pop up at the end of
some elements.

```<code>print("Taking weapons from Weapon shack")
weapons = []
with open("WeaponShack.list",'r') as ws:
    weapons = ws.readlines()
    for weapon in weapons:
        weapons.remove(weapon)
        weapon = weapon.strip('\n')
        weapons.append(weapon)
ws.close()
print(weapons)
</code>```

The expected output is:

Taking weapons from Weapon shack
  ['Ak-47', 'Makarov', 'Bat', 'Chainsaw', 'Grenade', 'Minigun', 'Flamethrower', 'Katana', 'Shotgun']

But the actual output is:

Taking weapons from Weapon shack
  ['Ak-47\n', 'Makarov\n', 'Bat\n', 'Chainsaw\n', 'Grenade', 'Minigun', 'Flamethrower', 'Katana', 'Shotgun']

Does anyone know why this is happening?

EDIT
My focus is why the "\n" character appears. Not how to traverse lists.
Also trying the suggestion: adding a new list:

```<code>print("Taking weapons from Weapon shack")
weapons = []
newWeaponList = []
with open("WeaponShack.list",'r') as ws:
    weapons = ws.readlines()
    for weapon in weapons:
        weapons.remove(weapon)
        weapon = weapon.strip('\n')
        newWeaponList.append(weapon)
ws.close()
print(newWeaponList)
</code>```

produces this output:

Taking weapons from Weapon shack
  ['Grenade', 'Shotgun', 'Minigun', 'Katana', 'Flamethrower']

Weird because it doesn't show all the elements.

答:
@rdas Thank you for your help.

"
Removing things from a list while iterating over it messes with the relative order of the elements in the list. Since you only iterate over the list once, some elements might get skipped. So the \n is not appearing - it's just never removed from some of the elements."

I removed the weapons.remove(weapon) line and it fixed it!

Cheers!

Body:
I'm reading files from a text file called WeaponShack.list

These are the contents of 'weapon shack.list':

Grenade
Ak-47
Shotgun
Makarov
Minigun
Bat
Katana
Chainsaw
Flamethrower

There are no whitespaces. These items are copy-pasted as is.

I try to strip down some newline characters but the "\n" character just keeps showing up at some elements when I print the list. I don't understand why.

I tried using .strip('\n') but the "\n" characters still pop up at the end of
some elements.

print("Taking weapons from Weapon shack")
weapons = []
with open("WeaponShack.list",'r') as ws:
    weapons = ws.readlines()
    for weapon in weapons:
        weapons.remove(weapon)
        weapon = weapon.strip('\n')
        weapons.append(weapon)
ws.close()
print(weapons)

The expected output is:

Taking weapons from Weapon shack
  ['Ak-47', 'Makarov', 'Bat', 'Chainsaw', 'Grenade', 'Minigun', 'Flamethrower', 'Katana', 'Shotgun']

But the actual output is:

Taking weapons from Weapon shack
  ['Ak-47\n', 'Makarov\n', 'Bat\n', 'Chainsaw\n', 'Grenade', 'Minigun', 'Flamethrower', 'Katana', 'Shotgun']

Does anyone know why this is happening?

EDIT
My focus is why the "\n" character appears. Not how to traverse lists.
Also trying the suggestion: adding a new list:

print("Taking weapons from Weapon shack")
weapons = []
newWeaponList = []
with open("WeaponShack.list",'r') as ws:
    weapons = ws.readlines()
    for weapon in weapons:
        weapons.remove(weapon)
        weapon = weapon.strip('\n')
        newWeaponList.append(weapon)
ws.close()
print(newWeaponList)

produces this output:

Taking weapons from Weapon shack
  ['Grenade', 'Shotgun', 'Minigun', 'Katana', 'Flamethrower']

Weird because it doesn't show all the elements.


问:
How do I create a new DataFrame filled with minimum and maximum values?
I have the following dataset...

https://drive.google.com/open?id=1PpI6PlO8ox2vKfM4aGmEUexCPPWa59S_

How do I create a new DataFrame where the first column is the unique neighbourhood names and the next two columns are filled with the minimum and maximum price for each neighbourhood?

答:
you can group by the hosts and get max and min value like below:

```<code>>>> data = pd.read_csv('dumbbell_data.csv')
>>> pd.DataFrame([[value.maxPrice.max(), value.minPrice.min(), key] for key, value in data.groupby('neighbourhood_hosts')], columns=data.columns)
   maxPrice  minPrice neighbourhood_hosts
0        45        45          Bloomsbury
1       247       117           Canonbury
2       112        72             Chelsea
3       160        29        LB of Barnet
4        80        72       LB of Hackney
5       321        58     Shepherd's Bush
6        72        55          Shoreditch
7       115        72             Wapping
8       120        58           Wimbledon
</code>```

A more Pythonic way is to use agg function:

```<code>>>> data.sort_values(by='neighbourhood_hosts').groupby('neighbourhood_hosts').agg({'maxPrice': max, 'minPrice':min})
                     maxPrice  minPrice
neighbourhood_hosts
Bloomsbury                 45        45
Canonbury                 247       117
Chelsea                   112        72
LB of Barnet              160        29
LB of Hackney              80        72
Shepherd's Bush           321        58
Shoreditch                 72        55
Wapping                   115        72
Wimbledon                 120        58
</code>```

Body:
you can group by the hosts and get max and min value like below:

>>> data = pd.read_csv('dumbbell_data.csv')
>>> pd.DataFrame([[value.maxPrice.max(), value.minPrice.min(), key] for key, value in data.groupby('neighbourhood_hosts')], columns=data.columns)
   maxPrice  minPrice neighbourhood_hosts
0        45        45          Bloomsbury
1       247       117           Canonbury
2       112        72             Chelsea
3       160        29        LB of Barnet
4        80        72       LB of Hackney
5       321        58     Shepherd's Bush
6        72        55          Shoreditch
7       115        72             Wapping
8       120        58           Wimbledon

A more Pythonic way is to use agg function:

>>> data.sort_values(by='neighbourhood_hosts').groupby('neighbourhood_hosts').agg({'maxPrice': max, 'minPrice':min})
                     maxPrice  minPrice
neighbourhood_hosts
Bloomsbury                 45        45
Canonbury                 247       117
Chelsea                   112        72
LB of Barnet              160        29
LB of Hackney              80        72
Shepherd's Bush           321        58
Shoreditch                 72        55
Wapping                   115        72
Wimbledon                 120        58