问:
Run make file in subdirectory using shell script
I need to run make file_name command in a subdirectory using shell
script and then cd .. out of that subdirectory and run the remaining commands in the main directory.

答:
Assuming the script is initially running in "the main directory", just cd to the subdir in a subshell.  eg

```<code>#!/bin/sh

# do stuff in main directory
( cd subdir; make file_name ) # use a subshell
# now run more commands in the main directory
</code>```

You can also use pushd and popd, or try storing $(pwd), or just use cd .., but the subshell is usually the cleanest solution.

Body:
Assuming the script is initially running in "the main directory", just cd to the subdir in a subshell.  eg

#!/bin/sh

# do stuff in main directory
( cd subdir; make file_name ) # use a subshell
# now run more commands in the main directory

You can also use pushd and popd, or try storing $(pwd), or just use cd .., but the subshell is usually the cleanest solution.


来源: stackexchange

问:
Typescript: Get the type of the last parameter of a function type
Assume I have a function type, e.g.

```<code>type somefntype = (a: number, b: string, c: boolean) => void
</code>```

I need the type of that function types last parameter:

```<code>type lastparamtype = LastParameter<somefntype> // lastparamtype == boolean
</code>```

How do I define LastParameter?

答:
Here is yet a another solution which is a slight modification of jcalz answer to make it more generic using some recursive conditional types:

type Head<T extends any[]> = T extends [any, ...any[]] ? T[0] : never;
type Tail<T extends any[]> =
    ((...t: T) => any) extends ((_: any, ...tail: infer U) => any)
        ? U
        : [];
type HasTail<T extends any[]> = T extends ([] | [any]) ? false : true;

type Last<T extends any[]> = {
    0: Last<Tail<T>>
    1: Head<T>
}[
    HasTail<T> extends true ? 0 : 1
];

type LastType = Last<Parameters<somefntype>>; // boolean
```

It might be interesting to consider replacing any with unknown as well.

ContentLicense: CC BY-SA 4.0

Body:
Assume I have a function type, e.g.

type somefntype = (a: number, b: string, c: boolean) => void

I need the type of that function types last parameter:

type lastparamtype = LastParameter<somefntype> // lastparamtype == boolean

How do I define LastParameter?

Body:
Here is yet a another solution which is a slight modification of jcalz answer to make it more generic using some recursive conditional types:

type Head<T extends any[]> = T extends [any, ...any[]] ? T[0] : never;
type Tail<T extends any[]> =
    ((...t: T) => any) extends ((_: any, ...tail: infer U) => any)
        ? U
        : [];
type HasTail<T extends any[]> = T extends ([] | [any]) ? false : true;

type Last<T extends any[]> = {
    0: Last<Tail<T>>
    1: Head<T>
}[
    HasTail<T> extends true ? 0 : 1
];

type LastType = Last<Parameters<somefntype>>; // boolean

It might be interesting to consider replacing any with unknown as well.


问:
Eliminate repetitive try catch statement in async express route callbacks?
I have an api written in Node JS with Express. All of my routes follow this pattern:

```<code>router.get("/my/url", async (req, res) => {
  try{
    // await code...
  }catch(error){
    console.error(error.message);
    res.status(500).json({message: "Server Error"})
  }
});
</code>```

This try catch is the same in all of my routes. What are some ways I can negate this, having it written in one place only, so my routes are more like:

```<code>router.get("/my/url", async (req, res) => {
  // await code...
});
</code>```

答:
You should checkout this package express-async-errors

Import the package after express, and then you need to only define the error handler like this

```<code>app.use((err, req, res, next) => {
    console.error(err.message);
    res.status(500).json({message: "Server Error"})
});
</code>```

Body:
I have an api written in Node JS with Express. All of my routes follow this pattern:

router.get("/my/url", async (req, res) => {
  try{
    // await code...
  }catch(error){
    console.error(error.message);
    res.status(500).json({message: "Server Error"})
  }
});

This try catch is the same in all of my routes. What are some ways I can negate this, having it written in one place only, so my routes are more like:

router.get("/my/url", async (req, res) => {
  // await code...
});

Body:
You should checkout this package express-async-errors

Import the package after express, and then you need to only define the error handler like this

app.use((err, req, res, next) => {
    console.error(err.message);
    res.status(500).json({message: "Server Error"})
});


问:
Select an expiredate field
I have created an expiredate field which is generated automatically based on the registerdate field

I've tried a regular query just like i would use for any field (it is mentioned below)

this is the model:

```<code>class UserProfile(models.Model):
    course = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
    phonenumber = models.CharField(max_length=50)
    registerdate = models.DateTimeField()
    expiredate = timezone.now().date() + timedelta(days= 70)
    user = models.OneToOneField(User, on_delete = models.CASCADE)

def __str__(self):
    return "{}" .format(self.user)
</code>```

and this is the query i'm trying to use:

```<code>expire = UserProfile.objects.values('expiredate')
</code>```

I simply want to select the expiredate and use it on my views.py function but the query generates an error:

```<code>'Cannot resolve keyword 'expiredate' into field. Choices are: course, course_id, id, phonenumber, registerdate, user, user_id'
</code>```

答:
Solution by @katoozi force default value to be same until application restarted.

Use callable to get correct value:

```<code>def get_expiredate():
    return timezone.now().date() + timedelta(days= 70)

class UserProfile(models.Model):
    expiredate = models.DateField(default=get_expiredate)
</code>```

Take a look at How to set a Django model field's default value to a function call / callable (e.g., a date relative to the time of model object creation)

Title: Select an expiredate field

Body:
I have created an expiredate field which is generated automatically based on the registerdate field

I've tried a regular query just like i would use for any field (it is mentioned below)

this is the model:

class UserProfile(models.Model):
    course = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
    phonenumber = models.CharField(max_length=50)
    registerdate = models.DateTimeField()
    expiredate = timezone.now().date() + timedelta(days= 70)
    user = models.OneToOneField(User, on_delete = models.CASCADE)

def __str__(self):
    return "{}" .format(self.user)

and this is the query i'm trying to use:

expire = UserProfile.objects.values('expiredate')

I simply want to select the expiredate and use it on my views.py function but the query generates an error:

'Cannot resolve keyword 'expiredate' into field. Choices are: course, course_id, id, phonenumber, registerdate, user, user_id'

Body:
Solution by @katoozi force default value to be same until application restarted.

Use callable to get correct value:

def get_expiredate():
    return timezone.now().date() + timedelta(days= 70)

class UserProfile(models.Model):
    expiredate = models.DateField(default=get_expiredate)

Take a look at How to set a Django model field's default value to a function call / callable (e.g., a date relative to the time of model object creation)


问:
Efficiently using LLVM through various platforms
I'm implementing a language using LLVM (C#, .NET Core). I intend this language to have cross-platform compatibility in the sense that its final executable is compiled targeting the local machine, for example Windows 10 x64, or Linux.

To accomplish this, my current strategy is to implement a wrapper CLI utility which consumes my language's compiler library (which uses LLVM), along with packaged LLVM executable for various platforms.

So basically, my CLI tool invokes LLVM's tools automatically (llc, lli, lld-link, etc.).

However, this means that I have to package the LLVM tools compiled for every platform that I want to target (along with some libraries such as libc for Unix-like system to ensure version compatibility and consistency?).

So, if I wanted to target the following platforms:

```<code>ubuntu16, ubuntu14, armv7a, windows x86_64, debian8, ...
</code>```

I'd literally have to somehow acquire their corresponding LLVM compiled executable tools.

The language library, CLI utility, and LLVM tools are compressed ("packaged") into a simple ZIP file.

I'm inclined towards a fully-managed system, so I would like to avoid forcing the users to install the LLVM tools on their local machines.

Should I be packaging the language/compiler onto the standard packaging methods used by corresponding platforms, ex. .RPM for Fedora, etc.?

Is there an alternative, efficient (generic?) method to accomplishing this, specially without the need of having to include LLVM tools and libraries along in the package?

How do other cross-platform compilers tackle this problem, or is it only LLVM-specific?

答: You can statically link whole LLVM into your .NET application and perform all tasks these tools do inside your compiler. This is, actually, what clang does - except it uses external linker.

Body:
I'm implementing a language using LLVM (C#, .NET Core). I intend this language to have cross-platform compatibility in the sense that its final executable is compiled targeting the local machine, for example Windows 10 x64, or Linux.

To accomplish this, my current strategy is to implement a wrapper CLI utility which consumes my language's compiler library (which uses LLVM), along with packaged LLVM executable for various platforms.

So basically, my CLI tool invokes LLVM's tools automatically (llc, lli, lld-link, etc.).

However, this means that I have to package the LLVM tools compiled for every platform that I want to target (along with some libraries such as libc for Unix-like system to ensure version compatibility and consistency?).

So, if I wanted to target the following platforms:

ubuntu16, ubuntu14, armv7a, windows x86_64, debian8, ...

I'd literally have to somehow acquire their corresponding LLVM compiled executable tools.

The language library, CLI utility, and LLVM tools are compressed ("packaged") into a simple ZIP file.

I'm inclined towards a fully-managed system, so I would like to avoid forcing the users to install the LLVM tools on their local machines.

Should I be packaging the language/compiler onto the standard packaging methods used by corresponding platforms, ex. .RPM for Fedora, etc.?

Is there an alternative, efficient (generic?) method to accomplishing this, specially without the need of having to include LLVM tools and libraries along in the package?

How do other cross-platform compilers tackle this problem, or is it only LLVM-specific?


问:
Building with Lombok's @Slf4j and Intellij: Cannot find symbol log
I have a maven project that builds with no problems from the command line. However, when I build it with IntelliJ, I get the error:

```<code>java: FileName.java:89: cannot find symbol
symbol  : variable log
</code>```

There is no log defined or imported in the java file, but there is a

```<code>@Slf4j
final public class FileName {
</code>```

statement before the class body which should define the log class.

In the project structure window, classes for:

```<code>Maven: org.slf4j:jcl-over-slf4j:1.6.1
Maven: org.slf4j:slf4j-api:1.6.6
Maven: org.slf4j:slf4j-log4j12:1.6.6
Maven: org.slf4j:slf4j-simple:1.6.6
</code>```

are listed under libraries and are indicated as having been downloaded and available.

Any idea why this would build with maven through the command line, but not through IntelliJ and how to resolve the issue?

答: After enabling annotation processors and installing the lombok plugin, it still didn't work. We worked around it by checking the Idea option "Delegate IDE build to gradle"</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a maven project that builds with no problems from the command line. However, when I build it with IntelliJ, I get the error:

java: FileName.java:89: cannot find symbol
symbol  : variable log

There is no log defined or imported in the java file, but there is a

@Slf4j
final public class FileName {

statement before the class body which should define the log class.

In the project structure window, classes for:

Maven: org.slf4j:jcl-over-slf4j:1.6.1
Maven: org.slf4j:slf4j-api:1.6.6
Maven: org.slf4j:slf4j-log4j12:1.6.6
Maven: org.slf4j:slf4j-simple:1.6.6

are listed under libraries and are indicated as having been downloaded and available.

Any idea why this would build with maven through the command line, but not through IntelliJ and how to resolve the issue?


问:
Delete row from dataframe having "None" value in all the columns - Python
I need to delete the row completely in a dataframe having "None" value in all the columns. I am using the following code -

```<code>df.dropna(axis=0,how='all',thresh=None,subset=None,inplace=True)
</code>```

This does not bring any difference to the dataframe. The rows with "None" value are still there.

How to achieve this?

答:
There Nones should be strings, so use replace first:

```<code>df = df.replace('None', np.nan).dropna(how='all')

df = pd.DataFrame({
         'a':['None','a', 'None'],
         'b':['None','g', 'None'],
         'c':['None','v', 'b'],
})

print (df)
      a     b     c
0  None  None  None
1     a     g     v
2  None  None     b

df1 = df.replace('None', np.nan).dropna(how='all')
print (df1)
     a    b  c
1    a    g  v
2  NaN  NaN  b
</code>```

Or test values None with not equal and DataFrame.any:

```<code>df1 = df[df.ne('None').any(axis=1)]
print (df1)
      a     b  c
1     a     g  v
2  None  None  b
</code>```

Body:
I need to delete the row completely in a dataframe having "None" value in all the columns. I am using the following code -

df.dropna(axis=0,how='all',thresh=None,subset=None,inplace=True)

This does not bring any difference to the dataframe. The rows with "None" value are still there.

How to achieve this?

Body:
There Nones should be strings, so use replace first:

df = df.replace('None', np.nan).dropna(how='all')

df = pd.DataFrame({
         'a':['None','a', 'None'],
         'b':['None','g', 'None'],
         'c':['None','v', 'b'],
})

print (df)
      a     b     c
0  None  None  None
1     a     g     v
2  None  None     b

df1 = df.replace('None', np.nan).dropna(how='all')
print (df1)
     a    b  c
1    a    g  v
2  NaN  NaN  b

Or test values None with not equal and DataFrame.any:

df1 = df[df.ne('None').any(axis=1)]
print (df1)
      a     b  c
1     a     g  v
2  None  None  b


问:
SqlDataAdapter.FillSchema with stored procedure that has temporary table
I'm running into a problem similar to this question here (Display DataType and Size of Column from SQL Server Query Results at Runtime) which has not had a solid solution.

I wonder if anyone has found a solution or a work around for it. I can use SqlDataAdapter.Fill() with no problem, but .FillSchema() will report an error that the temp table I create in the stored procedure doesn't exist.

My goal is to be able to fill the DataTable with data and the schema from the source.

答:
Stored procedures and temp tables generally don't mix well with strongly typed implementations of database objects.

If you change your #temp table to a table @variable that should solve your issue.

An example of how to change from temp table to table variable would be like:

```<code>    CREATE TABLE #tempTable (ID INT, Val VARCHAR(50))
</code>```

to

```<code>    DECLARE @tempTable TABLE(ID INT, Val VARCHAR(50))
</code>```

Body:
Stored procedures and temp tables generally don't mix well with strongly typed implementations of database objects.

If you change your #temp table to a table @variable that should solve your issue.

An example of how to change from temp table to table variable would be like:

    CREATE TABLE #tempTable (ID INT, Val VARCHAR(50))

to

    DECLARE @tempTable TABLE(ID INT, Val VARCHAR(50))


问:
WPF - Is it possible to (programmatically) disable multi-touch?
I have a problem with WPF application/presentation for Tablet PC with (multi-) touch screen. One "slide" of the presentation consists of Canvas on background and of a small UserControl. This UserControl is invisible at start, but whenever user touches the screen, it becomes visible and if user moves his finger, the control moves accordingly ("following" the finger, like a cursor). Then, when user stops touching the screen, the control becomes invisible again.

This is not very hard to do using the TouchDown, TouchUp and TouchMove event handlers and it works fine if user touches the screen with just one finger. However, when user holds one finger on position X (e.g. canvas coordinates [100,100]) and another finger on position Y (e.g. [500, 100]), the UserControl starts jumping between positions X and Y, which doesn't look very well...

Now I'd like the screen to react only to one touch at the time, which I can do in operating system (Windows 7) using Control Panel -> Pen and Touch -> Touch by unchecking item "Enable multi-touch gestures and inking".

This works fine, exactly as I want it to, unfortunately it's not very convenient, because sometimes I need to use the multi-touch and I can't change it every time I decide to use the application...

That's why I'd like to ask if there is any way how to disable the multi-touch programmaticaly, in the application (or just in WPF UserControl) where I need it. Thanks a lot in advance for any help.

答:
You can convert the C++ code from the following question to C#: Programatically enable / disable multitouch finger input?

The CodeProject article, "Single App Instance in C#: Yet Another Way" has a C# implementation of the Win32 GlobalAddAtom() function and PInvoke.net has a reference page for SetProp().


问:
For Each is not working, just goes to the first element and then exits, How can i fix this?
I have Two For Each that access to different tables to access the data on them But on the second for each only enter once and exits without looping, I am trying to print data from a procedure on a txt file

I have already checked the tables and they have more than one value, Rebuild the knowledge base, I have checked that it only goes once.
here is the code:

```<code>For Each Table1
    Where Attribute1= &Attribute1
        &Flag = 0
    For Each Table2
        WHERE Attribute2= &Attribute2
        If &Flag=0
            Print Tittle
            &Flag =1
        EndIf
        Print Transacctions
    EndFor
    Print Footer
EndFor

</code>```

答:
First of all, check specification navigation to see if gx is navigatig between the two tables you want.
Another tip i'd tell you is to put sniffers to see what is happening during execution.
And finally, chech taht in your DB, there are more than one record taht match the condition WHERE Attribute2= &Attribute2 and  Attribute1= &Attribute1.
Luck</p>

Body:
I have Two For Each that access to different tables to access the data on them But on the second for each only enter once and exits without looping, I am trying to print data from a procedure on a txt file

I have already checked the tables and they have more than one value, Rebuild the knowledge base, I have checked that it only goes once.
here is the code:

For Each Table1
    Where Attribute1= &Attribute1
        &Flag = 0
    For Each Table2
        WHERE Attribute2= &Attribute2
        If &Flag=0
            Print Tittle
            &Flag =1
        EndIf
        Print Transacctions
    EndFor
    Print Footer
EndFor


问:
Creating a package with resources using the package_create API call in Python
I'm trying to upload a data package with resources to CKAN (via Python). I can upload the package successfully without the "resources", but I keep hitting this error with them:
'message': "Only lists of dicts can be placed against subschema ('resources',), not <type 'list'>"

I've tried reformatting the Python dictionary several times and also used json.dumps() on the dictionary, but I then hit a json error when calling the API.

test_dict =
      {
      'title': 'title of my dataset',
      'start': '2018-09-15 00:00:00',
      'end': '2018-09-20 00:00:00',
      'fact': 'interesting fact',
      'ReportNo': 1234,
      'type': 'data',
      'notes': ' ',
      'owner_org': 'Org',
      'maintainer': 'Me',
      'name': 'Test package for S3',
      'resources': [
          {
                    'package_id': '',
                    'url': 'https://s3-test-bucket/test.txt',
                    'name': 'S3 URL testing',
                    'description': 'does description work?'
                    }
      ]
}

response = requests.post(url, test_dict, headers=auth)
response.json()
```

Expecting: 'success':'True'

Getting: 'message': "Only lists of dicts can be placed against subschema ('resources',), not ",
  '__type': 'Integrity Error'

Please can someone explain the correct Python dictionary format? Preferably with examples.

Thanks!

答:
I found the answer based on this post: Create CKAN dataset using CKAN API and Python Requests library

Here's the code I'm using:

    headers = json.loads(open('API_KEY','rb').read())
    headers['Content-Type'] = 'application/x-www-form-urlencoded'
    ckan = 'https://yourckanwebsite/api/3/action/'
    uri = ckan + 'package_create'

    data_dict = urllib.parse.quote(json.dumps(test_dict))
    response = requests.post(uri, data=data_dict, headers=headers)
    response.json()
```

Body:
I'm trying to upload a data package with resources to CKAN (via Python). I can upload the package successfully without the "resources", but I keep hitting this error with them:
'message': "Only lists of dicts can be placed against subschema ('resources',), not <type 'list'>"

I've tried reformatting the Python dictionary several times and also used json.dumps() on the dictionary, but I then hit a json error when calling the API.

test_dict =
      {
      'title': 'title of my dataset',
      'start': '2018-09-15 00:00:00',
      'end': '2018-09-20 00:00:00',
      'fact': 'interesting fact',
      'ReportNo': 1234,
      'type': 'data',
      'notes': ' ',
      'owner_org': 'Org',
      'maintainer': 'Me',
      'name': 'Test package for S3',
      'resources': [
          {
                    'package_id': '',
                    'url': 'https://s3-test-bucket/test.txt',
                    'name': 'S3 URL testing',
                    'description': 'does description work?'
                    }
      ]
}

response = requests.post(url, test_dict, headers=auth)
response.json()

Expecting: 'success':'True'

Getting: 'message': "Only lists of dicts can be placed against subschema ('resources',), not ",
  '__type': 'Integrity Error'

Please can someone explain the correct Python dictionary format? Preferably with examples.

Thanks!


问:
How to create custom tag's archive page for custom post type?
When i add custom tag to custom post type, the archive page doesn't work.

taxonomy-tags.php has been added,here is some of my code:

function create_taxonomies_tag() {
        $labels = array(
            'name'              => _x( '新标签', 'taxonomy 名称' ),
            'singular_name'     => _x( '新标签', 'taxonomy 单数名称' ),
            'search_items'      => __( '搜索新标签' ),
            'all_items'         => __( '所有新标签' ),
            'parent_item'       => __( '该新标签的上级分类' ),
            'parent_item_colon' => __( '该新标签的上级分类：' ),
            'edit_item'         => __( '编辑新标签' ),
            'update_item'       => __( '更新新标签' ),
            'add_new_item'      => __( '添加新的新标签' ),
            'new_item_name'     => __( '新的标签' ),
            'menu_name'         => __( '新标签' ),
        );
        $args = array(
            'hierarchical'      => false,
            'labels'            => $labels,
            'show_ui'           => true,
            'show_admin_column' => true,
            'query_var'         => true,
            'rewrite'           => array( 'slug' => tags ),
        );
        register_taxonomy( 'tags', array('site'), $args );
    }

```

what should i  do to fix it? please help me,thanks

答: When i click 'Save Changes' button at xxx/wp-admin/options-permalink.php page, then it works</p>

Body:
When i add custom tag to custom post type, the archive page doesn't work.

taxonomy-tags.php has been added,here is some of my code:

function create_taxonomies_tag() {
        $labels = array(
            'name'              => _x( '新标签', 'taxonomy 名称' ),
            'singular_name'     => _x( '新标签', 'taxonomy 单数名称' ),
            'search_items'      => __( '搜索新标签' ),
            'all_items'         => __( '所有新标签' ),
            'parent_item'       => __( '该新标签的上级分类' ),
            'parent_item_colon' => __( '该新标签的上级分类：' ),
            'edit_item'         => __( '编辑新标签' ),
            'update_item'       => __( '更新新标签' ),
            'add_new_item'      => __( '添加新的新标签' ),
            'new_item_name'     => __( '新的标签' ),
            'menu_name'         => __( '新标签' ),
        );
        $args = array(
            'hierarchical'      => false,
            'labels'            => $labels,
            'show_ui'           => true,
            'show_admin_column' => true,
            'query_var'         => true,
            'rewrite'           => array( 'slug' => tags ),
        );
        register_taxonomy( 'tags', array('site'), $args );
    }

what should i  do to fix it? please help me,thanks


问:
How to render json with pretty print when in dev mode
My action has:

```<code>render json: {
   "user" : @user,
    "blah" : @blah
}
</code>```

In dev mode, ie. Rails.env.development? is true I want to render the json using pretty print.

How can I do this?

答:
use</p>

```<code>render json: JSON.pretty_generate(@data.as_json)
</code>```

Body:
My action has:

render json: {
   "user" : @user,
    "blah" : @blah
}

In dev mode, ie. Rails.env.development? is true I want to render the json using pretty print.

How can I do this?

Body:
use

render json: JSON.pretty_generate(@data.as_json)


问:
Populating xml using c# error
I am populating an xml document using c#. If I populate it once then everything is ok but when I try to repopulate it a second time (without closing the program) I get an error message and rubish gets written to the bottom of the xml file.

I'm sure I've found the answer to this question before but I can't find it.

I'm sure its something to do with the fact that I'm not closing something down after updating the xml document or something but I can't remember what exactly I have to close down.

Sorry I hope you all understand. I find it difficult to explain.

Code:

```<code>using (FileStream READER = new FileStream(fpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
      {
                System.Xml.XmlDocument Template = new System.Xml.XmlDocument();// Set up the XmlDocument //
                Template.Load(READER); //Load the data from the file into the XmlDocument //

                //**********Grab nodes to be written to********

                using (FileStream WRITER = new FileStream(fpath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
                {
                    //Set up the filestream (READER) //
                    //Write the data to the filestream
                    Template.Save(WRITER);
</code>```

答:
You read and write in the same file fpath

You have to close the reader after Template.Load(READER);

```<code>  using (FileStream READER = new FileStream(fpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  {
       System.Xml.XmlDocument Template = new System.Xml.XmlDocument();// Set up the XmlDocument //
       Template.Load(READER); //Load the data from the file into the XmlDocument //
  }

  //**********Grab nodes to be written to********

  using (FileStream WRITER = new FileStream(fpath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
  {
     //Set up the filestream (READER) //
     //Write the data to the filestream
     Template.Save(WRITER);
     ...
  }
</code>```

Title: Populating xml using c# error

Body:
I am populating an xml document using c#. If I populate it once then everything is ok but when I try to repopulate it a second time (without closing the program) I get an error message and rubish gets written to the bottom of the xml file.

I'm sure I've found the answer to this question before but I can't find it.

I'm sure its something to do with the fact that I'm not closing something down after updating the xml document or something but I can't remember what exactly I have to close down.

Sorry I hope you all understand. I find it difficult to explain.

Code:

using (FileStream READER = new FileStream(fpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
      {
                System.Xml.XmlDocument Template = new System.Xml.XmlDocument();// Set up the XmlDocument //
                Template.Load(READER); //Load the data from the file into the XmlDocument //

                //**********Grab nodes to be written to********

                using (FileStream WRITER = new FileStream(fpath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
                {
                    //Set up the filestream (READER) //
                    //Write the data to the filestream
                    Template.Save(WRITER);

Body:
You read and write in the same file fpath

You have to close the reader after Template.Load(READER);

  using (FileStream READER = new FileStream(fpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  {
       System.Xml.XmlDocument Template = new System.Xml.XmlDocument();// Set up the XmlDocument //
       Template.Load(READER); //Load the data from the file into the XmlDocument //
  }

  //**********Grab nodes to be written to********

  using (FileStream WRITER = new FileStream(fpath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
  {
     //Set up the filestream (READER) //
     //Write the data to the filestream
     Template.Save(WRITER);
     ...
  }


问:
Create an empty child record in Firebase
I am trying to create a child using the Firebase data view but it seems that this is not possible as the create node directly disappears or rather doesn't show up at any time.
I tried to leave the value field empty but this doesn't work at all as well as writing null into the value field.
Am I doing it wrong?

-Fabian

答: Creating an empty directory is not Supported by Firebase.</p>


问:
Why is asyncio queue await get() blocking?
Why is await queue.get() blocking?

import asyncio

async def producer(queue, item):
    await queue.put(item)

async def consumer(queue):
    val = await queue.get()
    print("val = %d" % val)

async def main():
    queue = asyncio.Queue()
    await consumer(queue)
    await producer(queue, 1)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
```

<p>If I call the <strong>producer()</strong> before <strong>consumer()</strong>, it works fine
That is to say, the following works fine.</p>

<pre class="lang-py prettyprint-override"><code>async def main():
    queue = asyncio.Queue()
    await producer(queue, 1)
    await consumer(queue)
</code>```

Why isn't await queue.get() yielding control back to the event loop so that the producer coroutine can run which will populate the queue so that queue.get() can return.

答:
It's because you call await consumer(queue), which means the next line (procuder) will not be called until consumer returns, which it of course never does because nobody produced yet

check out the Example in the docs and see how they use it there: https://docs.python.org/3/library/asyncio-queue.html#examples

another simple example:

import asyncio
import random

async def produce(queue, n):
    for x in range(1, n + 1):
        # produce an item
        print('producing {}/{}'.format(x, n))
        # simulate i/o operation using sleep
        await asyncio.sleep(random.random())
        item = str(x)
        # put the item in the queue
        await queue.put(item)

    # indicate the producer is done
    await queue.put(None)

async def consume(queue):
    while True:
        # wait for an item from the producer
        item = await queue.get()
        if item is None:
            # the producer emits None to indicate that it is done
            break

        # process the item
        print('consuming item {}...'.format(item))
        # simulate i/o operation using sleep
        await asyncio.sleep(random.random())

loop = asyncio.get_event_loop()
queue = asyncio.Queue(loop=loop)
producer_coro = produce(queue, 10)
consumer_coro = consume(queue)
loop.run_until_complete(asyncio.gather(producer_coro, consumer_coro))
loop.close()
```

Body:
Why is await queue.get() blocking?

import asyncio

async def producer(queue, item):
    await queue.put(item)

async def consumer(queue):
    val = await queue.get()
    print("val = %d" % val)

async def main():
    queue = asyncio.Queue()
    await consumer(queue)
    await producer(queue, 1)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

If I call the producer() before consumer(), it works fine
That is to say, the following works fine.

async def main():
    queue = asyncio.Queue()
    await producer(queue, 1)
    await consumer(queue)

Why isn't await queue.get() yielding control back to the event loop so that the producer coroutine can run which will populate the queue so that queue.get() can return.


问:
Wait until an event is fired in NodeJs
I am writing a function in my server to return data from client A to client B at the time client B is sending request. When function is called, my server send request to client A and then client A send data back to server. The problem is how to make this function wait until server received data from client A.

I already use setTimeout and it worked for me but it not flexible

```<code>//the code for receiving data from client A is written in another file
socketA.emit('getData', JSON.stringify(json));
//I want my function will stopping here
socketB.emit('sendData', somedata);
</code>```

This is my code for receiving data from client

```<code>socket.on('getData', (data) =>{
   storage_data = data;
});
</code>```

I expect there is a way to stop my function without using setTimeout or if I make something wrong, please tell me.

Thanks.

答:
This can be done with async/await syntax

```<code>socket.on('getData', async (data) =>{
   storage_data = await data;
});
</code>```

For reference: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await

Title: Wait until an event is fired in NodeJs

Body:
I am writing a function in my server to return data from client A to client B at the time client B is sending request. When function is called, my server send request to client A and then client A send data back to server. The problem is how to make this function wait until server received data from client A.

I already use setTimeout and it worked for me but it not flexible

//the code for receiving data from client A is written in another file
socketA.emit('getData', JSON.stringify(json));
//I want my function will stopping here
socketB.emit('sendData', somedata);

This is my code for receiving data from client

socket.on('getData', (data) =>{
   storage_data = data;
});

I expect there is a way to stop my function without using setTimeout or if I make something wrong, please tell me.

Thanks.

Body:
This can be done with async/await syntax

socket.on('getData', async (data) =>{
   storage_data = await data;
});

For reference: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await


问:
Session works only on one page in php
I set session variable for login of user but it doesn't work on another pages than login.php.

login.php:

```<code><?php
    session_start();

    if(isset($_POST['submit'])) {

        $conn = mysqli_connect('localhost', 'cp72722_lucky', '3AIp!9f4', 'cp72722_lucky');
        $user_username = mysqli_real_escape_string($conn, trim($_POST['username']));
        $user_password = mysqli_real_escape_string($conn, trim($_POST['password']));
        if(!empty($user_username) && !empty($user_password)) {

            $query = "SELECT user_id , username FROM users WHERE username = '$user_username' AND pwd = SHA('$user_password')";
            $data = mysqli_query($conn,$query);
            if(mysqli_num_rows($data) == 1) {

                $row = mysqli_fetch_assoc($data);
                $user_value = $row['username'];
                $user_id_value = $row['user_id'];
                $_SESSION['username'] = $user_value;
                $_SESSION['user_id'] = $user_id_value;
                echo "Hello," . $_SESSION['username'];
                $home_url = 'http://' . $_SERVER['SERVER_NAME'];
                header('Location: ' . $home_url);
                print_r($home_url);
                exit();
            }
            else {
                echo 'Извините, вы должны ввести правильные имя пользователя и пароль';
            }
        }
        else {
            echo 'Извините, вы должны заполнить поля правильно';
        }
    }

?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="style/style.css" rel="stylesheet">
</head>
<body>
<header>
<ul>
    <li><a href="/">Главная</a></li>

</ul>
</header>
<h2>Вход</h2>
<div class="container">
<form action="http://<?php echo $_SERVER['SERVER_NAME']; ?>" method="POST">
        <label for="username">Логин:</label>
    <input type="text" name="username">
    <label for="password">Пароль:</label>
    <input type="password" name="password">
    <button type="submit" name="submit">Вход</button>
    <a href="auth/signup.php">Регистрация</a>
    </form>
    </div>
<footer>
    <p>Все права защищены</p>
</footer>

</body>

</html>
</code>```

My header.php shows almost on all pages and I want to welcome the users after login. If the session is not set, then should display the form to login. Problem is, if the user is logged in and the profile links, it always displays second choice because session is not set. How do I resolve this issue?

header.php:

```<code><?php

session_start();

print_r($_SESSION);
?>
...
<header id="header">
    <?php
echo 'Glad to see you,'. htmlspecialchars($_SESSION['username']);
?>
...
<div>
<?php
    if(!isset($_SESSION['username'])) {
?>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
        <label for="username">Login:</label>
    <input type="text" name="username">
    <label for="password">Password:</label>
    <input type="password" name="password">
    <button type="submit" name="submit">Enter</button>
    <a href="auth/signup.php">Registration</a>
    </form>
<?php
}
else {
    ?>
    <p><a href="myprofile.php">Profile</a></p>
    <p><a href="exit.php">Exit(<?php echo $_SESSION['username']; ?>)</a></p>
<?php
}
?>
</div>
</code>```

答:
Remove extra space before session_start() function

convert :

```<code>    <?php

    session_start();
</code>```

to this

```<code><?php
session_start();
</code>```

Thank you.

Title: Session works only on one page in php

Body:
I set session variable for login of user but it doesn't work on another pages than login.php.

login.php:

<?php
    session_start();

    if(isset($_POST['submit'])) {

        $conn = mysqli_connect('localhost', 'cp72722_lucky', '3AIp!9f4', 'cp72722_lucky');
        $user_username = mysqli_real_escape_string($conn, trim($_POST['username']));
        $user_password = mysqli_real_escape_string($conn, trim($_POST['password']));
        if(!empty($user_username) && !empty($user_password)) {

            $query = "SELECT user_id , username FROM users WHERE username = '$user_username' AND pwd = SHA('$user_password')";
            $data = mysqli_query($conn,$query);
            if(mysqli_num_rows($data) == 1) {

                $row = mysqli_fetch_assoc($data);
                $user_value = $row['username'];
                $user_id_value = $row['user_id'];
                $_SESSION['username'] = $user_value;
                $_SESSION['user_id'] = $user_id_value;
                echo "Hello," . $_SESSION['username'];
                $home_url = 'http://' . $_SERVER['SERVER_NAME'];
                header('Location: ' . $home_url);
                print_r($home_url);
                exit();
            }
            else {
                echo 'Извините, вы должны ввести правильные имя пользователя и пароль';
            }
        }
        else {
            echo 'Извините, вы должны заполнить поля правильно';
        }
    }

?>
<!DOCTYPE html>

<meta charset="utf-8">
<link href="style/style.css" rel="stylesheet">

Главная

Вход

<form action="http://<?php echo $_SERVER['SERVER_NAME']; ?>" method="POST">
        Логин:
    <input type="text" name="username">
    Пароль:
    <input type="password" name="password">
    <button type="submit" name="submit">Вход</button>
    Регистрация
    </form>

Все права защищены

My header.php shows almost on all pages and I want to welcome the users after login. If the session is not set, then should display the form to login. Problem is, if the user is logged in and the profile links, it always displays second choice because session is not set. How do I resolve this issue?

header.php:

<?php

session_start();

print_r($_SESSION);
?>
...

    <?php
echo 'Glad to see you,'. htmlspecialchars($_SESSION['username']);
?>
...

<?php
    if(!isset($_SESSION['username'])) {
?>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
        Login:
    <input type="text" name="username">
    Password:
    <input type="password" name="password">
    <button type="submit" name="submit">Enter</button>
    Registration
    </form>
<?php
}
else {
    ?>

Profile

Exit(<?php echo $_SESSION['username']; ?>)

<?php
}
?>

Body:
Remove extra space before session_start() function

convert :

    <?php

    session_start();

to this

<?php
session_start();

Thank you.


问:
Java get value by key in JSON data
```<code>[
{
    "boylam":31.8039,
    "enlem":40.5906,
    "il":"",
    "ilPlaka":"",
    "ilce":"",
    "oncelik":0,
    "yukseklik":2052,
    "aciklama":"",
    "modelId":124774,
    "gps":0
}]
</code>```

Hi I have such a JSON data in my hand. I had a hard time getting the data out of here. For example, how do I print the "boylam" option in JSON data?

答:
You can use JSON.simple to convert string data to JSON objects. https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1</p>

```<code>public static void main(String[] args) throws ParseException {

    String data = "[\n" +
            "{\n" +
            "    \"boylam\":31.8039,\n" +
            "    \"enlem\":40.5906,\n" +
            "    \"il\":\"\",\n" +
            "    \"ilPlaka\":\"\",\n" +
            "    \"ilce\":\"\",\n" +
            "    \"oncelik\":0,\n" +
            "    \"yukseklik\":2052,\n" +
            "    \"aciklama\":\"\",\n" +
            "    \"modelId\":124774,\n" +
            "    \"gps\":0\n" +
            "}]";

    JSONParser parser = new JSONParser();

    JSONArray jsonArray = (JSONArray) parser.parse(data);

    JSONObject jsonObject = (JSONObject) jsonArray.get(0);

    System.out.println(jsonObject.get("boylam"));

}
</code>```

Title: Java get value by key in JSON data

Body:
[
{
    "boylam":31.8039,
    "enlem":40.5906,
    "il":"",
    "ilPlaka":"",
    "ilce":"",
    "oncelik":0,
    "yukseklik":2052,
    "aciklama":"",
    "modelId":124774,
    "gps":0
}]

Hi I have such a JSON data in my hand. I had a hard time getting the data out of here. For example, how do I print the "boylam" option in JSON data?

Body:
You can use JSON.simple to convert string data to JSON objects. https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1

public static void main(String[] args) throws ParseException {

    String data = "[\n" +
            "{\n" +
            "    \"boylam\":31.8039,\n" +
            "    \"enlem\":40.5906,\n" +
            "    \"il\":\"\",\n" +
            "    \"ilPlaka\":\"\",\n" +
            "    \"ilce\":\"\",\n" +
            "    \"oncelik\":0,\n" +
            "    \"yukseklik\":2052,\n" +
            "    \"aciklama\":\"\",\n" +
            "    \"modelId\":124774,\n" +
            "    \"gps\":0\n" +
            "}]";

    JSONParser parser = new JSONParser();

    JSONArray jsonArray = (JSONArray) parser.parse(data);

    JSONObject jsonObject = (JSONObject) jsonArray.get(0);

    System.out.println(jsonObject.get("boylam"));

}


问:
How to update the value of a key field in a dictionary in Python?
I have a dictionary as given below:

```<code>test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}
</code>```

I have written below program to retrieve keys from the dictionary:

```<code>test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}

for keys in test.keys():
    print(keys)
</code>```

I want to update the keys field value when we got a digit value in keys field. Example in the above dictionary

```<code>keys: 100
value: 271
</code>```

When we got keys value is an integer then I want to updates keys value like this xx_100:271

I would like to solve the problem in the simplest way possible using python.

Body:
I have a dictionary as given below:

test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}

I have written below program to retrieve keys from the dictionary:

test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}

for keys in test.keys():
    print(keys)

I want to update the keys field value when we got a digit value in keys field. Example in the above dictionary

keys: 100
value: 271

When we got keys value is an integer then I want to updates keys value like this xx_100:271

I would like to solve the problem in the simplest way possible using python.

Body:
test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}

for keys in test.keys():

if isinstance(test[keys], int):
    test[keys] = "xx_" + str(test[keys])

 print(test)


问:
Is hashinfo equivalent to peer ID in Mainline DHT?
I am working on Mainline DHT and I don't understand one nuance.

Here: https://www.bittorrent.org/beps/bep_0005.html writes: "A "distance metric" is used to compare two node IDs or a node ID and an info hash for "closeness."

Also writes: "Announce that the peer, controlling the querying node, is downloading a torrent on a port. announce_peer has four arguments: "id" containing the node ID of the querying node, "info_hash" containing the info hash of the torrent, "port" containing the port as an integer, and the "token" received in response to a previous get_peers query."

So, for example, we have a peer with ID 223456789zxcvbnmasdf which IP is 86.23.145.714 and port is: 7853
I know that this peer downloaded 2 torrent files with info hashes: 023456789zxcvbnmasdf and 123456789zxcvbnmasdf.

So how exactly my k-bucket record should look like?
Like this:

```<code>{"id": "223456789zxcvbnmasdf", "ip": "86.23.145.714", "port": "7853", "torrents": ["023456789zxcvbnmasdg", "123456789zxcvbnmasdh"]} ?
</code>```

Or should torrent files be like an "equivalent" record (with duplicated ips and ports) in k-buckets along with peer:

```<code>{"id": "223456789zxcvbnmasdf", "ip": "86.23.145.714", "port": "7853"},

{"id": "023456789zxcvbnmasdg", "ip": "86.23.145.714", "port": "7853"},

{"id": "123456789zxcvbnmasdh", "ip": "86.23.145.714", "port": "7853"} ?
</code>```

I am asking because this is not just implementation nuance. Because "k" is normally 20 or some other integer in all clients. So if I would use k-buckets to store torrent files as full-right members, I would have less space to store real peers data.

Thanks for answers!

答:
How you structure your data internally is up to you. All it has to do is fulfill the contract of the specification. In principle one could associate torrents with buckets based on the xor distance – e.g. for resource accounting reasons – but most implementations keep the routing table and the storage separate.

The primary routing table only contains nodes, structural members of the DHT overlay itself. Torrents on the other hand are not part of the overlay. They're data stored on top of the overlay, the hash table abstraction. Hence the name, Distributed Hash Table. I.e. they exist on different abstraction levels.

Body:
I am working on Mainline DHT and I don't understand one nuance.

Here: https://www.bittorrent.org/beps/bep_0005.html writes: "A "distance metric" is used to compare two node IDs or a node ID and an info hash for "closeness."

Also writes: "Announce that the peer, controlling the querying node, is downloading a torrent on a port. announce_peer has four arguments: "id" containing the node ID of the querying node, "info_hash" containing the info hash of the torrent, "port" containing the port as an integer, and the "token" received in response to a previous get_peers query."

So, for example, we have a peer with ID 223456789zxcvbnmasdf which IP is 86.23.145.714 and port is: 7853
I know that this peer downloaded 2 torrent files with info hashes: 023456789zxcvbnmasdf and 123456789zxcvbnmasdf.

So how exactly my k-bucket record should look like?
Like this:

{"id": "223456789zxcvbnmasdf", "ip": "86.23.145.714", "port": "7853", "torrents": ["023456789zxcvbnmasdg", "123456789zxcvbnmasdh"]} ?

Or should torrent files be like an "equivalent" record (with duplicated ips and ports) in k-buckets along with peer:

{"id": "223456789zxcvbnmasdf", "ip": "86.23.145.714", "port": "7853"},

{"id": "023456789zxcvbnmasdg", "ip": "86.23.145.714", "port": "7853"},

{"id": "123456789zxcvbnmasdh", "ip": "86.23.145.714", "port": "7853"} ?

I am asking because this is not just implementation nuance. Because "k" is normally 20 or some other integer in all clients. So if I would use k-buckets to store torrent files as full-right members, I would have less space to store real peers data.

Thanks for answers!


问:
JQuery: How to select label of input's ancestor
I have the following HTML:

  Description/Pack Size

    <input type="text" name="packetSize" class="wfinput required form_error" id="packetSize" />

      This field is required.

```

Is there a way to select the  element that is the child of .control-group (ie, the one with "Description/Pack Size" text), from the <input /> text field in my HTML?

答:
If you want to get all label that class was named "control-label-sub".

```<code>var element = $("label.control-label-sub")
</code>```

And If you want to get only that label I prefer following

```<code>var element = $("input#packetSize").parent().prev()
</code>```

Body:
I have the following HTML:

  Description/Pack Size

    <input type="text" name="packetSize" class="wfinput required form_error" id="packetSize" />

      This field is required.

Is there a way to select the  element that is the child of .control-group (ie, the one with "Description/Pack Size" text), from the <input /> text field in my HTML?

Body:
If you want to get all label that class was named "control-label-sub".

var element = $("label.control-label-sub")

And If you want to get only that label I prefer following

var element = $("input#packetSize").parent().prev()


问:
TimeType ARRIVAL not working in Android SDK
I want my users to be able to switch between departure and arrival time. But when I send a routeplan request with TimeType.ARRIVAL in the routeOptions.setTime it gives me an INVALID_PARAMETERS error. But the exact same request with TimeType.DEPARTURE works fine.

Below is my code. Did I do something wrong or is TimeType.ARRIVAL deprecated or just not working?

```<code>   RoutePlan routePlan = new RoutePlan();

    RouteOptions routeOptions = new RouteOptions();
    routeOptions.setTransportMode(RouteOptions.TransportMode.PUBLIC_TRANSPORT);
    routeOptions.setRouteType(RouteOptions.Type.FASTEST);
    routeOptions.setRouteCount(3);
    routeOptions.setLocale(Locale.getDefault());
    if (toggleSwitch.getCheckedTogglePosition() == 0) {
        routeOptions.setTime(selected_time, RouteOptions.TimeType.DEPARTURE);
    }
    else {
        routeOptions.setTime(selected_time, RouteOptions.TimeType.ARRIVAL);
    }
    routePlan.setRouteOptions(routeOptions);

    // Select Waypoints for your routes
    routePlan.addWaypoint(new RouteWaypoint(start_address_coordinate));
    routePlan.addWaypoint(new RouteWaypoint(end_address_coordinate));
    router.calculateRoute(routePlan, new RouterListener());
</code>```

答:
As per the HERE documentation:

ARRIVAL time type option is supported only for UMRouteOptions. Using this value in RouteOptions.setTime(Date, TimeType), with unsupported RouteOptions, will result in RoutingError.INVALID_PARAMETERS when requesting a route.

So, the error you are getting is an expected behaviour. Please correct your code as per the HERE documentation.

Body:
I want my users to be able to switch between departure and arrival time. But when I send a routeplan request with TimeType.ARRIVAL in the routeOptions.setTime it gives me an INVALID_PARAMETERS error. But the exact same request with TimeType.DEPARTURE works fine.

Below is my code. Did I do something wrong or is TimeType.ARRIVAL deprecated or just not working?

   RoutePlan routePlan = new RoutePlan();

    RouteOptions routeOptions = new RouteOptions();
    routeOptions.setTransportMode(RouteOptions.TransportMode.PUBLIC_TRANSPORT);
    routeOptions.setRouteType(RouteOptions.Type.FASTEST);
    routeOptions.setRouteCount(3);
    routeOptions.setLocale(Locale.getDefault());
    if (toggleSwitch.getCheckedTogglePosition() == 0) {
        routeOptions.setTime(selected_time, RouteOptions.TimeType.DEPARTURE);
    }
    else {
        routeOptions.setTime(selected_time, RouteOptions.TimeType.ARRIVAL);
    }
    routePlan.setRouteOptions(routeOptions);

    // Select Waypoints for your routes
    routePlan.addWaypoint(new RouteWaypoint(start_address_coordinate));
    routePlan.addWaypoint(new RouteWaypoint(end_address_coordinate));
    router.calculateRoute(routePlan, new RouterListener());


问:
Enable Popups chrome browser for protractor test
Protractor creates a brand new Chrome profile every time it runs. So what i want to do it will enable popup for chrome browser every time when protractor test runs.
I don't want to use existing profile.Is there any way to do ?</p>

答:
You can create instance of chrome custom profile and it can be passed to capabilities.</p>

```<code>export const chromeProfile = {
           browserName : 'chrome',
           maxInstances: 1,
           chromeOptions: {
                args: [
                      // mention list of all setting for chrome browser
                      //For example following two lines disable chrome popup
                      'disable-infobars=true',
                      '--disable-popup-blocking'
                        ],
                  prefs: {
                         // disable password popup
                         'credentials_enable_service': false
                          }
                           }
                              };
</code>```

Body:
You can create instance of chrome custom profile and it can be passed to capabilities.

export const chromeProfile = {
           browserName : 'chrome',
           maxInstances: 1,
           chromeOptions: {
                args: [
                      // mention list of all setting for chrome browser
                      //For example following two lines disable chrome popup
                      'disable-infobars=true',
                      '--disable-popup-blocking'
                        ],
                  prefs: {
                         // disable password popup
                         'credentials_enable_service': false
                          }
                           }
                              };


问:
Issue using certbot with nginx
I'm actually working on a webapp, I use Reactjs for the frontend and Golang for the backend. Those 2 programs are hosted separately on 2 VMs on Google-Compute-Engine. I want to serve my app through https so I choose to use Nginx for serving the frontend in production. Firstly I made my config file for Nginx:

```<code>#version: nginx/1.14.0 (ubuntu)
server {
     listen 80 default_server;
     listen [::]:80 default_server;

     root /var/www/banshee;
     server_name XX.XXX.XX.XXX; #public IP of my frontend VM

     index index.html;

     location / {
       try_files $uri /index.html =404;
     }
   }
</code>```

For this part everything works as expected but after that I want to serve my App over https following this tutorial. I installed the packages software-properties-common,python-certbot-apache
 and certbot but when I tried

sudo cerbot --nginx certonly

I get the following message:

```<code>gdes@frontend:/etc/nginx$ sudo certbot --nginx certonly
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Could not choose appropriate plugin: The requested nginx plugin does not appear to be installed
The requested nginx plugin does not appear to be installed
</code>```

I made some searches on Google and here and I still can't figure out which plugin is missing or an other way to fix this.

Does someone have an idea tohelp me ?

Thanks a lot :)

答:
I was trying to create Let's Encrypt certificate using certbot for my sub-domain and had the following issue.
Command:

ubuntu@localhost:~$ certbot --nginx -d my_subdomain.website.com -d my_subdomain2.website.com

Issue:

The requested Nginx plugin does not appear to be installed

Solution:

Ubuntu 20+

ubuntu@localhost:~$ sudo apt-get install python3-certbot-nginx

Earlier Versions

ubuntu@localhost:~$ sudo apt-get install python-certbot-nginx

Title: Issue using certbot with nginx

Body:
I'm actually working on a webapp, I use Reactjs for the frontend and Golang for the backend. Those 2 programs are hosted separately on 2 VMs on Google-Compute-Engine. I want to serve my app through https so I choose to use Nginx for serving the frontend in production. Firstly I made my config file for Nginx:

#version: nginx/1.14.0 (ubuntu)
server {
     listen 80 default_server;
     listen [::]:80 default_server;

     root /var/www/banshee;
     server_name XX.XXX.XX.XXX; #public IP of my frontend VM

     index index.html;

     location / {
       try_files $uri /index.html =404;
     }
   }

For this part everything works as expected but after that I want to serve my App over https following this tutorial. I installed the packages software-properties-common,python-certbot-apache
 and certbot but when I tried

sudo cerbot --nginx certonly

I get the following message:

gdes@frontend:/etc/nginx$ sudo certbot --nginx certonly
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Could not choose appropriate plugin: The requested nginx plugin does not appear to be installed
The requested nginx plugin does not appear to be installed

I made some searches on Google and here and I still can't figure out which plugin is missing or an other way to fix this.

Does someone have an idea tohelp me ?

Thanks a lot :)


问:
no multithreading benefit with single core
I'm new to concurrrent programming and multithreading.
I can understand the benefits of multithreading with multicore processors, but does those benefit exist on single core processor,

For example, let's say we have a multicore computer and  a program to sum up a very large number as:

```<code>int sum = 0;
for (i=1, i<9999999999, i++)
{
   sum += i;
}

doOtherStuff();  // execute other function that is irrelevant to sum
...
...
//and then finally print the sum
Console.WriteLine(sum);
</code>```

so for the long running sum task, we can create a second thread to calculate the sum and the main thread keeps executing other functions.

But if we run this program on a single core computer, there is no benefits to create multithreads, isn't it? it is even worse with multithreads because of the context switches?

答:
In addition to Jeremy answer, (all correct), there is:

Multithreaded designs often allow the same software to take advantage of extra cores, when available, without rebuilds.

Multiple threads can allow execution-independent subsystems to be built that can be added to other apps with negligible effort or impact.

Many designs lend themselves naturally to multiple threads, the alternative of explicit, user-level state machines being complex and messy.

Body:
I'm new to concurrrent programming and multithreading.
I can understand the benefits of multithreading with multicore processors, but does those benefit exist on single core processor,

For example, let's say we have a multicore computer and  a program to sum up a very large number as:

int sum = 0;
for (i=1, i<9999999999, i++)
{
   sum += i;
}

doOtherStuff();  // execute other function that is irrelevant to sum
...
...
//and then finally print the sum
Console.WriteLine(sum);

so for the long running sum task, we can create a second thread to calculate the sum and the main thread keeps executing other functions.

But if we run this program on a single core computer, there is no benefits to create multithreads, isn't it? it is even worse with multithreads because of the context switches?


问:
Is Kubernetes ephemeral storage elastic?
In Kubernetes pods have requests and limit for ephemeral storage. But it isn't clear whether this is an elastic resource i.e. if you save a file inside a K8S pod and then delete it, does the ephemeral storage usage go up and then back down again? Or once you have consumed any ephemeral storage, does that usage count towards the overall usage for the lifetime of the pod?</p>

答:
As you mentioned, Kubernetes Ephemeral storage can be managed by implementing requests and limits for the containers inside a Pod, that is quite well described in the official k8s documentation.

Although, on Pod level local storage consists of a sum of entire container consumers, the main capacitor here is Node where the Pod actually resides on. Node level represents a mechanism of Allocation compute resources between a Pods which are spawned on this Node as per K8s scheduler Decision. The way how the compute resources are distributed between underlying Pods on the particular Node is nicely described in this Example.

Generally, when the Pod successfully assigned to a Node it obtains emptyDir as a part of local ephemeral storage volume as well as container logs, image layers and container writable layers; furthermore container disaster does not affect parent Pod emptyDir data.

Basically, Ephemeral storage is persistent during life of the Pod, although it counts resources shared by all containers in the Pod, the most common usage would be for storing temporary or caching data.


问:
How to put text inside triangle button?
I create triangle button at header of my page, and i would like to put text in button.

Now text is outside button.

My code:

.collapsible {
    position: absolute;
    left: 40%;
}

.triangle {
    font-size: 22px;
    color: #000;
    width: 190px;
    height: 140px;
    border-top: solid 140px #2b2b2b;
    border-left: solid 140px transparent;
    border-right: solid 140px transparent;
    border-bottom: transparent;
    background-color: transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="collapsible triangle" id="collapse">Some content</button></code>```

So as u can see text is outside of buuton, how it's possible to set inside button?

答:
You could do it like this. The only problem is that the triangle is black and the inside text is black too. You should change the triangle color instead to see the text.

<button class="collapsible triangle" id="collapse" value="Some content"></button>

Title: How to put text inside triangle button?

Body:
I create triangle button at header of my page, and i would like to put text in button.

Now text is outside button.

My code:

.collapsible {
    position: absolute;
    left: 40%;
}

.triangle {
    font-size: 22px;
    color: #000;
    width: 190px;
    height: 140px;
    border-top: solid 140px #2b2b2b;
    border-left: solid 140px transparent;
    border-right: solid 140px transparent;
    border-bottom: transparent;
    background-color: transparent;
}

<button class="collapsible triangle" id="collapse">Some content</button>

So as u can see text is outside of buuton, how it's possible to set inside button?


问:
SQL Server Transactional Replication Over VPN
I have transactional replication running between two servers over a dedicated VPN connection.  The databases are fairly large, so I initially use the backup and restore method to get the initial snapshot over to the subscriber machine and then let it apply the incremental transactions from there.

Everything runs fine until the VPN line gets flaky (which it does occassionally) at which point the replication process is prone to locking up. When I look on the subscriber side, there are a few SQL processes which appear to be hung and have locks held on the subscriber database and tables.  The crazy thing is that those processes are coming from the replication service.  I can assure you (from trial and error) that no other processes are locking this database except for replication itself.

So why would the replication process trip over its own feet like that?  Why would it get hung just because of a loss of network connectivity?  Any suggestions for somehow making it more reliable?

答:
I'll ask some questions and maybe they can give you some ideas as I don't have a clue here either.

Is there a way for the replicator to test for connectivity before attempting to start copying?  Is there a way to put a connectivity test into whatever script you're using to perform replication?  Is there a way to have the script bail in case of failure?

OwnerDisplayName: codeflunky

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: codeflunky

OwnerDisplayName: Paul Robinson


问:
Need help understanding how to version an iOS app
In Xcode I have Bundle Version and Bundle Version string, short.  There is also a version in iTunes Connect.  Just trying to see what I should use for each one and which one iOS uses to determine the version of the app so that a newer version properly replaces and older version.

答:
Here's the excellent post on how to do the versioning easy way. My general approach is tou use x.y.z where 'x' is gets increased on major releases, 'y' is increased for versions introducing new functionality and 'z' is used for bug-fixes releases. Examples: 1.0.0, 1.0.4, 3.2.1 etc...
The relation between Bundle Version and iTunes connect is simple: whatever you use for your version in the Xcode, is also used in iTunes, so the user of your app can identify you app version easily - you just have to be consistent. Later you can introduce more granularity, e.g. build numbers.

EDIT:
Important addition: your app can get rejected if you're inconsistent with numbering. More details here. dead link, however it is still true that because of inconsistent versioning app can get rejected.


问:
Syntax error while executing a python script to make a web application
this is my first time using pycharm and flask library. i am fairly new to advanced programing and i was trying to create an executable link for my program but im getting a syntax error. when i run the same script in idle without the flask functions and without the if __name__=="__main__": line in python IDLE, it works just as expected.

from flask import Flask
import os
import csv
import sqlite3
import tkinter.filedialog
import pandas as pd
from tkinter import filedialog
from tkinter import *

app=Flask(__name__)
@app.route('/')

k=Tk()
k.filename =  filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("csv files","*.csv"),("all files","*.*")))
database=sqlite3.connect("C:\SQLiteStudio\data.db")
d=database.cursor()
task1="""CREATE TABLE z (
        date DATE ,
        time TIME ,
        value_1 DOUBLE PRECISION ,
        value_2 DOUBLE PRECISION ,
        final_value DOUBLE
    );"""
task2="""INSERT INTO z (date, time, value_1, value_2, final_value) VALUES (?,?,?,?,?)"""
#d.execute(task1)
out=pd.read_csv(k.filename, header=None)
print(len(out))
print(out.iloc[0])
row=1
if str(out.iloc[0,0])=='Date' and str(out.iloc[0,1])=='Time' and str(out.iloc[0,2])=='Lat' and str(out.iloc[0,3])=='Long' and str(out.iloc[0,4])=='Temp':
    while row< len(out):
        print(row)
        d.execute(task2,out.iloc[row])
        database.commit()
        row+=1
else:
    print("The data is not in expected format.")
database.close()

if __name__=="__main__":
    app.run()
```

```"C:\Users\Jay Paliwal\Desktop\Internship\venv\Scripts\python.exe"
"C:/Users/Jay Paliwal/Desktop/Internship/task 1.py"
File "C:/Users/Jay Paliwal/Desktop/Internship/task 1.py", line 13
        k=Tk()
        ^
    SyntaxError: invalid syntax

    Process finished with exit code 1
```

this is the output I got. I was expecting a link to come which when one visited opens a dialogue box for the tkinter function used

答:
You can't just have a decorator on its own. A decorator needs to state a function.

Your code should be in a function anyway.

(Note though, it makes no sense to try to use tkinter in a Flask app. Why are you using Flask at all here?)

Body:
this is my first time using pycharm and flask library. i am fairly new to advanced programing and i was trying to create an executable link for my program but im getting a syntax error. when i run the same script in idle without the flask functions and without the if __name__=="__main__": line in python IDLE, it works just as expected.

from flask import Flask
import os
import csv
import sqlite3
import tkinter.filedialog
import pandas as pd
from tkinter import filedialog
from tkinter import *

app=Flask(__name__)
@app.route('/')

k=Tk()
k.filename =  filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("csv files","*.csv"),("all files","*.*")))
database=sqlite3.connect("C:\SQLiteStudio\data.db")
d=database.cursor()
task1="""CREATE TABLE z (
        date DATE ,
        time TIME ,
        value_1 DOUBLE PRECISION ,
        value_2 DOUBLE PRECISION ,
        final_value DOUBLE
    );"""
task2="""INSERT INTO z (date, time, value_1, value_2, final_value) VALUES (?,?,?,?,?)"""
#d.execute(task1)
out=pd.read_csv(k.filename, header=None)
print(len(out))
print(out.iloc[0])
row=1
if str(out.iloc[0,0])=='Date' and str(out.iloc[0,1])=='Time' and str(out.iloc[0,2])=='Lat' and str(out.iloc[0,3])=='Long' and str(out.iloc[0,4])=='Temp':
    while row< len(out):
        print(row)
        d.execute(task2,out.iloc[row])
        database.commit()
        row+=1
else:
    print("The data is not in expected format.")
database.close()

if __name__=="__main__":
    app.run()

"C:\Users\Jay Paliwal\Desktop\Internship\venv\Scripts\python.exe"
"C:/Users/Jay Paliwal/Desktop/Internship/task 1.py"
File "C:/Users/Jay Paliwal/Desktop/Internship/task 1.py", line 13
        k=Tk()
        ^
    SyntaxError: invalid syntax

    Process finished with exit code 1

this is the output I got. I was expecting a link to come which when one visited opens a dialogue box for the tkinter function used


问:
protected destructor with unique_ptr
I am trying to call APIs from a third party library.

There is a trouble when I want to use unique_ptr with a class having protected destructor.

Here is the example,

```<code>#include <memory>
#include <iostream>

using namespace std;

class Parent {
  public:
    Parent () //Constructor
    {
        cout << "\n Parent constructor called\n" << endl;
    }
  protected:
    ~ Parent() //Dtor
    {
        cout << "\n Parent destructor called\n" << endl;
    }
};

class Child : public Parent
{
  public:
    Child () //Ctor
    {
        cout << "\nChild constructor called\n" << endl;
    }
    ~Child() //dtor
    {
        cout << "\nChild destructor called\n" << endl;
    }
};

Parent* get() {
  return new Child();
}

int main(int argc, char const* argv[])
{
  Parent * p1 = get(); // this is ok
  std::unique_ptr<Parent> p2(get()); // this is not ok
  return 0;
}
</code>```

I am trying to use unique_ptr with Parent class. But the compiler threw the errors

```<code>/usr/include/c++/5/bits/unique_ptr.h: In instantiation
of ‘void std::default_delete<_Tp>::operator()(_Tp*) const
[with _Tp = Parent]’:
/usr/include/c++/5/bits/unique_ptr.h:236:17:   required
from ‘std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp
= Parent; _Dp = std::default_delete<Parent>]’
main.cpp:38:35:   required from here
main.cpp:12:5: error: ‘Parent::~Parent()’ is protected
 ~ Parent() //Dtor
 ^
In file included from /usr/include/c++/5/memory:81:0,
             from main.cpp:2:
/usr/include/c++/5/bits/unique_ptr.h:76:2: error: within
this context
  delete __ptr;
</code>```

Any idea about getting rid of this issue? I can't hack Parent and Child class since they are the classes of the third party library.

答:
You can make std::default_delete<Parent> a friend of Parent to fix that error. And you may also like to make ~Parent virtual to avoid undefined behaviour when deleteing a derived class through Parent pointer.

E.g.:

```<code>class Parent {
    friend std::default_delete<Parent>;
    // ...
protected:
    virtual ~Parent();
    // ...
</code>```

However, Parent design makes it clear that you are not supposed to delete through Parent pointer, this is why the destructor is non-public. Read Virtuality for more details:

Guideline #4: A base class destructor should be either public and virtual, or protected and nonvirtual.

You may like to introduce another intermediate base class to solve the issue:

```<code>class Parent { // Comes from a 3rd-party library header.
protected:
    ~Parent();
};

struct MyParent : Parent {  // The intermediate base class.
    virtual ~MyParent();
};

class Derived : public MyParent {};

std::unique_ptr<MyParent> createDerived() {
    return std::unique_ptr<MyParent>(new Derived);
}

int main() {
    auto p = createDerived();
}
</code>```

Title: protected destructor with unique_ptr

Body:
I am trying to call APIs from a third party library.

There is a trouble when I want to use unique_ptr with a class having protected destructor.

Here is the example,

#include <memory>
#include <iostream>

using namespace std;

class Parent {
  public:
    Parent () //Constructor
    {
        cout << "\n Parent constructor called\n" << endl;
    }
  protected:
    ~ Parent() //Dtor
    {
        cout << "\n Parent destructor called\n" << endl;
    }
};

class Child : public Parent
{
  public:
    Child () //Ctor
    {
        cout << "\nChild constructor called\n" << endl;
    }
    ~Child() //dtor
    {
        cout << "\nChild destructor called\n" << endl;
    }
};

Parent* get() {
  return new Child();
}

int main(int argc, char const* argv[])
{
  Parent * p1 = get(); // this is ok
  std::unique_ptr<Parent> p2(get()); // this is not ok
  return 0;
}

I am trying to use unique_ptr with Parent class. But the compiler threw the errors

/usr/include/c++/5/bits/unique_ptr.h: In instantiation
of ‘void std::default_delete<_Tp>::operator()(_Tp*) const
[with _Tp = Parent]’:
/usr/include/c++/5/bits/unique_ptr.h:236:17:   required
from ‘std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp
= Parent; _Dp = std::default_delete<Parent>]’
main.cpp:38:35:   required from here
main.cpp:12:5: error: ‘Parent::~Parent()’ is protected
 ~ Parent() //Dtor
 ^
In file included from /usr/include/c++/5/memory:81:0,
             from main.cpp:2:
/usr/include/c++/5/bits/unique_ptr.h:76:2: error: within
this context
  delete __ptr;

Any idea about getting rid of this issue? I can't hack Parent and Child class since they are the classes of the third party library.

Body:
You can make std::default_delete<Parent> a friend of Parent to fix that error. And you may also like to make ~Parent virtual to avoid undefined behaviour when deleteing a derived class through Parent pointer.

E.g.:

class Parent {
    friend std::default_delete<Parent>;
    // ...
protected:
    virtual ~Parent();
    // ...

However, Parent design makes it clear that you are not supposed to delete through Parent pointer, this is why the destructor is non-public. Read Virtuality for more details:

Guideline #4: A base class destructor should be either public and virtual, or protected and nonvirtual.

You may like to introduce another intermediate base class to solve the issue:

class Parent { // Comes from a 3rd-party library header.
protected:
    ~Parent();
};

struct MyParent : Parent {  // The intermediate base class.
    virtual ~MyParent();
};

class Derived : public MyParent {};

std::unique_ptr<MyParent> createDerived() {
    return std::unique_ptr<MyParent>(new Derived);
}

int main() {
    auto p = createDerived();
}


问:
Is my counter variable safe for concurrent tasks?
Is below counter thread safe? I think that if I reach the sync function over async function, counter would work fine. Am I right? My explanation is function a() is sync function. It means that this function is atomic, that's why only one process works inside. it also means that counter get increased safely ?</p>

```<code>    `var counter = 0;
     function a(){
     counter++
     }
     async function count(){
      //IO code;
      a();
     }
     count();`
</code>```

答:
Yes, the code is thread safe. Most values (except SharedArrayBuffers) can't be shared between threads, so they can't be accessed concurrently by two different threads.

As you mentioned "async functions": They run asynchronously in the sense that they might halt at specified points (basically when you await), and other code might run then, but all the other code will run till completion (so other code might only run inbetween when you use await).

An example of the same operation that could fail:

```<code>  counter = counter + await Promise.resolve(1);
</code>```

This might fail as counter gets evaluated, then the promise gets awaited, other code might change counter in the meantime, and then you assign back to counter.

Body:
Is below counter thread safe? I think that if I reach the sync function over async function, counter would work fine. Am I right? My explanation is function a() is sync function. It means that this function is atomic, that's why only one process works inside. it also means that counter get increased safely ?

    `var counter = 0;
     function a(){
     counter++
     }
     async function count(){
      //IO code;
      a();
     }
     count();`

Body:
Yes, the code is thread safe. Most values (except SharedArrayBuffers) can't be shared between threads, so they can't be accessed concurrently by two different threads.

As you mentioned "async functions": They run asynchronously in the sense that they might halt at specified points (basically when you await), and other code might run then, but all the other code will run till completion (so other code might only run inbetween when you use await).

An example of the same operation that could fail:

  counter = counter + await Promise.resolve(1);

This might fail as counter gets evaluated, then the promise gets awaited, other code might change counter in the meantime, and then you assign back to counter.


问:
Laravel routes, two registration forms on one page
I am creating a registration form. On one page /pages/register i have two forms. One for "register as a person" and one for "register as a company".

Form one has action="{{ route('frontend.persons.store') }}" on it and it works.

When i create the second form with
action="{{ route('frontend.companies.store') }}"

it stops working with error

"Route [frontend.persons.store] not defined."

The problem is that the routes are defined.

Routes:

```<code>Route::get('/pages/register', 'Frontend\PagesController@register')->name('register'); (returns a view)

Route::post('/pages/register', 'Frontend\FrontendPersonsController@store')->name('frontend.persons.store');

Route::post('/pages/register', 'Frontend\FrontendCompaniesController@store')->name('frontend.companies.store');
</code>```

I am using Laravel Framework 5.8.11

What am i doing wrong?

答:
You've two identical URI's for two different controller method, as a result only the first one works, but when you try to fire second one the error undefined route throws up.

/pages/register

```<code>Route::post('/pages/register', 'Frontend\FrontendPersonsController@store')->name('frontend.persons.store');
</code>```

/pages/register

```<code>Route::post('/pages/register', 'Frontend\FrontendCompaniesController@store')->name('frontend.companies.store');
</code>```

try changing the either route, for example

```<code> Route::post('/pages/company/register', 'Frontend\FrontendCompaniesController@store')->name('frontend.companies.store');
</code>```

Body:
I am creating a registration form. On one page /pages/register i have two forms. One for "register as a person" and one for "register as a company".

Form one has action="{{ route('frontend.persons.store') }}" on it and it works.

When i create the second form with
action="{{ route('frontend.companies.store') }}"

it stops working with error

"Route [frontend.persons.store] not defined."

The problem is that the routes are defined.

Routes:

Route::get('/pages/register', 'Frontend\PagesController@register')->name('register'); (returns a view)

Route::post('/pages/register', 'Frontend\FrontendPersonsController@store')->name('frontend.persons.store');

Route::post('/pages/register', 'Frontend\FrontendCompaniesController@store')->name('frontend.companies.store');

I am using Laravel Framework 5.8.11

What am i doing wrong?

Body:
You've two identical URI's for two different controller method, as a result only the first one works, but when you try to fire second one the error undefined route throws up.

/pages/register

Route::post('/pages/register', 'Frontend\FrontendPersonsController@store')->name('frontend.persons.store');

/pages/register

Route::post('/pages/register', 'Frontend\FrontendCompaniesController@store')->name('frontend.companies.store');

try changing the either route, for example

 Route::post('/pages/company/register', 'Frontend\FrontendCompaniesController@store')->name('frontend.companies.store');


问:
How Deserialize JSON Api result
I take thi result by Api. I don't realize which class need to cofigurate to dessirialize this.

```<code>"{
  \"errors\":{\"Email\": [\"This field should be filled in\"],
            \"Password\": [\"This field should be filled in\"]},
  \"title\":\"One or more validation errors occurred.\",
  \"status\":400,
  \"traceId\":\"8000006c-0002-fe00-b63f-84710c7967bb\"
}"
</code>```

i write this classes to deserialize

```<code>public class Content
{
    public List<Error> Errors { get; set; }
    public string Tutle { get; set; }
    public int Status { get; set; }
    public string TraceId { get; set; }
}

public class Error
{
    public string Email { get; set; }
    public string Password { get; set; }
}
</code>```

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[AppStore.WPF.Services.Helpers.Error]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

it was later and later, accually doesn't mean how write the class correctly

答:
You are attempting to use:

```<code>public List<Error> Errors { get; set; }

public class Error
{
    public string Email { get; set; }
    public string Password { get; set; }
}
</code>```

to deserialize:

```<code>\"errors\":{\"Email\": [\"This field should be filled in\"],
        \"Password\": [\"This field should be filled in\"]},
</code>```

Look closely at the JSON (and the error message); Email and Password require an array of strings.  A hypothetical response from the API might look like:

```<code>\"errors\":{\"Email\": [\"This field should be filled in\"],
        \"Password\": [\"Password must be at least 8 characters\",
                      \"Password must contain at least one digit\"]
},
</code>```

A first attempt to correct this might be:

```<code>public class Error
{
    public string[] Email { get; set; }
    public string[] Password { get; set; }
}
</code>```

However it seems likely from the context that Email and Password refer to input items that are being validated, and that the result could contain other items, e.g. PhoneNumber:

```<code>\"errors\":{\"Email\": [\"This field should be filled in\"],
        \"Password\": [\"This field should be filled in\"],
        \"PhoneNumber\": [\"This field should be filled in\"]
},
</code>```

so that you really want to deserialize it as a dictionary, i.e. replace:

```<code>public List<Error> Errors { get; set; }
</code>```

by:

```<code>public Dictionary<string, string[]> Errors {get; set; }
</code>```

Title: How Deserialize JSON Api result

Body:
I take thi result by Api. I don't realize which class need to cofigurate to dessirialize this.

"{
  \"errors\":{\"Email\": [\"This field should be filled in\"],
            \"Password\": [\"This field should be filled in\"]},
  \"title\":\"One or more validation errors occurred.\",
  \"status\":400,
  \"traceId\":\"8000006c-0002-fe00-b63f-84710c7967bb\"
}"

i write this classes to deserialize

public class Content
{
    public List<Error> Errors { get; set; }
    public string Tutle { get; set; }
    public int Status { get; set; }
    public string TraceId { get; set; }
}

public class Error
{
    public string Email { get; set; }
    public string Password { get; set; }
}

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[AppStore.WPF.Services.Helpers.Error]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

it was later and later, accually doesn't mean how write the class correctly

Body:
You are attempting to use:

public List<Error> Errors { get; set; }

public class Error
{
    public string Email { get; set; }
    public string Password { get; set; }
}

to deserialize:

\"errors\":{\"Email\": [\"This field should be filled in\"],
        \"Password\": [\"This field should be filled in\"]},

Look closely at the JSON (and the error message); Email and Password require an array of strings.  A hypothetical response from the API might look like:

\"errors\":{\"Email\": [\"This field should be filled in\"],
        \"Password\": [\"Password must be at least 8 characters\",
                      \"Password must contain at least one digit\"]
},

A first attempt to correct this might be:

public class Error
{
    public string[] Email { get; set; }
    public string[] Password { get; set; }
}

However it seems likely from the context that Email and Password refer to input items that are being validated, and that the result could contain other items, e.g. PhoneNumber:

\"errors\":{\"Email\": [\"This field should be filled in\"],
        \"Password\": [\"This field should be filled in\"],
        \"PhoneNumber\": [\"This field should be filled in\"]
},

so that you really want to deserialize it as a dictionary, i.e. replace:

public List<Error> Errors { get; set; }

by:

public Dictionary<string, string[]> Errors {get; set; }


问:
calling functions with STL parameters from a shared library
I know that it's not possible to safely export a function C++ parameters (eg STL strings), because C++ does not specify a standard ABI. (I've read that as an answer to How to call a function from a shared library? )

People tend to believe that if both your library and your program have been built with the same compiler then this isn't an issue, but unfortunately, for some VC++ compilers, this is not entirely true.

Herb Sutter and Alexandrescu in "C++ Coding Standards" propose to rely on portable types (eg built-in types) instead of a function that takes a string.

ie instead of using std::string in a module interface

```<code> std::string Translate( const std::string & );
</code>```

use a

```<code>void Translate( const char *src, char* dest, size_t destSize );
</code>```

Although they agree this is fairly complex for both the caller and the callee, they don't propose a nicer alternative.

How can one nicely pass a more complex object, such as a std::map using low-level types?  (not to mention something as complex as map<string,vector<something_complex> >)

How do you tackle such cases when exporting functions ?

答:
Not only do you have to have built the program using the same compiler (or compatible ABI), you need to have used the same settings:  debug & release mode, DLL and Static mode, checked iterators (or not), and so on.  In one respect, STLPort did it right:  the std::string when building for their library is renamed into distinct symbols based on these settings, avoiding the issue entirely.

The other option is to pass along opaque pointers to objects allocated, disposed, and used within the DLL.  In effect, making your own virtual interface to the functions you need, if you want to use them as objects outside the DLL.

Body:
I know that it's not possible to safely export a function C++ parameters (eg STL strings), because C++ does not specify a standard ABI. (I've read that as an answer to How to call a function from a shared library? )

People tend to believe that if both your library and your program have been built with the same compiler then this isn't an issue, but unfortunately, for some VC++ compilers, this is not entirely true.

Herb Sutter and Alexandrescu in "C++ Coding Standards" propose to rely on portable types (eg built-in types) instead of a function that takes a string.

ie instead of using std::string in a module interface

 std::string Translate( const std::string & );

use a

void Translate( const char *src, char* dest, size_t destSize );

Although they agree this is fairly complex for both the caller and the callee, they don't propose a nicer alternative.

How can one nicely pass a more complex object, such as a std::map using low-level types?  (not to mention something as complex as map<string,vector<something_complex> >)

How do you tackle such cases when exporting functions ?


问:
Why doesn't soup.select('.r a') find anything in my google search?
I'm trying out the lucky.py project in this book, https://automatetheboringstuff.com/chapter11/. The program runs fine, but I can't get beautifulsoup to select the correct links.

What I've tried:

I've tried soup.select('div') and it chooses all the links from the top.

Tried soup.select('span div') and it selects all the sublinks on each search result.

Looked up lots over questions, but none of them seems to answer why soup.select('.r a') doesn't work or how to fix it.

When I enter print(linkElems) in the code, it shows me an empty dictionary.

This is my code:

```<code>#! /usr/bin/env python3
import requests, sys, webbrowser, bs4

print('Googling...')    # display text while downloading the Google page

res = requests.get('https://google.com/search?q=' + ' '.join(sys.argv[1:]))
res.raise_for_status()

soup = bs4.BeautifulSoup(res.text, features="html.parser")

linkElems = soup.select('.r a')
numOpen = min(5, len(linkElems))
for i in range(numOpen):
    webbrowser.open('https://google.com' + linkElems[i].get('href'))
</code>```

I'm expecting it to open the first 5 links of the google search in new tabs, but nothing comes up because the selector isn't working properly.

答:
It seems like class r (.r) means tag for one link.

If class r has only one a tag, multiple links can't be opened.

So, you might need to search upper tag like "div tag + id='search'", for example, div#search

Then, returned object will contain all a tags because element of "div#search" is located upper than all a tags

Body:
I'm trying out the lucky.py project in this book, https://automatetheboringstuff.com/chapter11/. The program runs fine, but I can't get beautifulsoup to select the correct links.

What I've tried:

I've tried soup.select('div') and it chooses all the links from the top.

Tried soup.select('span div') and it selects all the sublinks on each search result.

Looked up lots over questions, but none of them seems to answer why soup.select('.r a') doesn't work or how to fix it.

When I enter print(linkElems) in the code, it shows me an empty dictionary.

This is my code:

#! /usr/bin/env python3
import requests, sys, webbrowser, bs4

print('Googling...')    # display text while downloading the Google page

res = requests.get('https://google.com/search?q=' + ' '.join(sys.argv[1:]))
res.raise_for_status()

soup = bs4.BeautifulSoup(res.text, features="html.parser")

linkElems = soup.select('.r a')
numOpen = min(5, len(linkElems))
for i in range(numOpen):
    webbrowser.open('https://google.com' + linkElems[i].get('href'))

I'm expecting it to open the first 5 links of the google search in new tabs, but nothing comes up because the selector isn't working properly.


问:
What does "listPointer->leftPointer->rightPointer = newNodePtr;" do?
It is my first time encountering this type of pointer. It points then points again, what does this imply? I encountered this on a doubly linked list program.</p>

```<code>listPointer->leftPointer->rightPointer = newNodePtr;
</code>```

答:
Maybe used to remove listPointer from the link list like mentioned below:

```<code>listPointer->leftPointer->rightPointer = newNodePtr;
newNodePtr->rightPointer = listPointer
</code>```

Body:
It is my first time encountering this type of pointer. It points then points again, what does this imply? I encountered this on a doubly linked list program.

listPointer->leftPointer->rightPointer = newNodePtr;

Body:
Maybe used to remove listPointer from the link list like mentioned below:

listPointer->leftPointer->rightPointer = newNodePtr;
newNodePtr->rightPointer = listPointer


问:
Simulate the interaction with a CLI
I have a CLI that can launch processes, especially interactive shells and waits for them, they can be closed using the same CLI. I need to create some end to end tests for it using bash but I cannot see how to simulate the execution in the terminal; the output should be sent to the process in the "foreground".

Suppose that executing my-cli start launches a python script that start a subprocess (running an interactive shell) and waits to it.
in the testing script, exec(my-cli start) will replace the current process with the process running python script and not the interactive shell, so I cannot interact with the interactive shell after.

I thought about using pipes, but I think something that can simulate using a terminal will be better, any ideas ?

Example:

Suppose the code of my CLI (cli.py) is:

```<code>import subprocess

process = subprocess.Popen(['/bin/bash', '-i'], shell=False)
process.communicate()
</code>```

Using expect I don't know if it's possible to communicate with the interactive shell (/bin/bash -i)

```<code>#!/usr/bin/expect -f

spawn python3 cli.py

#expect eof

send -- "echo $$\r"
</code>```

答:
As mentioned in a comment by Benjamin. I and many others have used expect in this scenario. As long as you can tell the text that will be presented in the terminal then you can use the following web pages as a guide to creating an expect script.

https://www.poftut.com/expect-scripting-tutorial-examples/

https://www.shellscript.sh/expect.html

https://www.journaldev.com/1405/expect-script-ssh-example-tutorial

Update based on the example provided. For this, I have a file foo.py:

import subprocess

process = subprocess.Popen(['/bin/bash', '-i'], shell=False)
process.communicate()
```

<p>An expect file (expect-example.exp):</p>

```#!/usr/bin/expect
spawn  python3 foo.py

expect "*bash*"
send "date\r"
send "exit\r"

interact
```

<p>When I run this <code>expect expect-example.exp</code> I get the following:</p>

```$ expect expect-example.exp
spawn python3 foo.py
bash-3.2$ date
Mon  3 Jun 2019 14:03:37 BST
bash-3.2$ exit
exit
$
```

It is worth mentioning, given that I am running a single command date and I want to see the output from it I must include the interact command at the end of the script. Otherwise, my expect script will exit as soon as it has sent the date command and won't wait for the response.

Title: Simulate the interaction with a CLI

Body:
I have a CLI that can launch processes, especially interactive shells and waits for them, they can be closed using the same CLI. I need to create some end to end tests for it using bash but I cannot see how to simulate the execution in the terminal; the output should be sent to the process in the "foreground".

Suppose that executing my-cli start launches a python script that start a subprocess (running an interactive shell) and waits to it.
in the testing script, exec(my-cli start) will replace the current process with the process running python script and not the interactive shell, so I cannot interact with the interactive shell after.

I thought about using pipes, but I think something that can simulate using a terminal will be better, any ideas ?

Example:

Suppose the code of my CLI (cli.py) is:

import subprocess

process = subprocess.Popen(['/bin/bash', '-i'], shell=False)
process.communicate()

Using expect I don't know if it's possible to communicate with the interactive shell (/bin/bash -i)

#!/usr/bin/expect -f

spawn python3 cli.py

#expect eof

send -- "echo $$\r"

Body:
As mentioned in a comment by Benjamin. I and many others have used expect in this scenario. As long as you can tell the text that will be presented in the terminal then you can use the following web pages as a guide to creating an expect script.

https://www.poftut.com/expect-scripting-tutorial-examples/

https://www.shellscript.sh/expect.html

https://www.journaldev.com/1405/expect-script-ssh-example-tutorial

Update based on the example provided. For this, I have a file foo.py:

import subprocess

process = subprocess.Popen(['/bin/bash', '-i'], shell=False)
process.communicate()

An expect file (expect-example.exp):

#!/usr/bin/expect
spawn  python3 foo.py

expect "*bash*"
send "date\r"
send "exit\r"

interact

When I run this expect expect-example.exp I get the following:

$ expect expect-example.exp
spawn python3 foo.py
bash-3.2$ date
Mon  3 Jun 2019 14:03:37 BST
bash-3.2$ exit
exit
$

It is worth mentioning, given that I am running a single command date and I want to see the output from it I must include the interact command at the end of the script. Otherwise, my expect script will exit as soon as it has sent the date command and won't wait for the response.