问:
TypeScript Union Type missing properties
I have 3 Types:

```<code>export type FooInitialStateType = {
  Id: string;
  Name: string;
  Email: string;
  Password: string
};

export type BarInitialStateType = {
  Id: string;
  Balance: number;
};

export type BazInitialStateType = {
  Id: string;
  Limit: number;
};
</code>```

Which I then create a Union Type like so:

```<code>export type FooBarBazType = FooInitialStateType | BarInitialStateType | BazInitialStateType
</code>```

I then have a generic method which processes arrays containing all 3 above Types:

```<code>  getFooBarBaz (
    events: FooBarBazType[]
  ): {
    foobarbaz0: FooBarBazType;
  } {
    const foobarbaz0 = <FooBarBazType>events[0];
    return {
      foobarbaz0
    };
  }
</code>```

I then call this generic method from each class (foo, bar, baz):

```<code>    const {
      foobarbaz0
    }: {
      foobarbaz0: FooInitialStateType;
    } = this.getFooBarBaz(fooEvents);
</code>```

I get a TS error:

Type 'FooBarBazType' is not assignable to type 'FooInitialStateType'.

Because FooInitialStateType doesn't contain properties from BarInitialStateType and BazInitialStateType.

Actual questions:

How can I utilise the Union Type for the generic method to accept an array with all 3 Types, but then where I invoke the method, specify what exact Type the returned value should be?

Is a Union Type the correct thing to use here? I have one method that accepts 3 different Types, and produces one Type. I need the invoking function to know, and specify, the returned Type

答:
It's possible that you want getFooBarBaz() to be a generic function where the output type depends on the input type:

```<code>function getFooBarBaz<T extends FooBarBazType>(events: T[]): { foobarbaz0: T; } {
    const foobarbaz0 = events[0];
    return {
        foobarbaz0
    };
}
</code>```

Then it might behave the way you'd like:

```<code>const fooEvents = [
    {
        Id: "foo",
        Name: "Foobert",
        Email: "foobert@example.com",
        Password: "Emb4rr4ss|ngP455w%?d"
    }
];

const {
    foobarbaz0
}: {
    foobarbaz0: FooInitialStateType;
} = getFooBarBaz(fooEvents); // no error now
</code>```

Does that help?  Good luck!

Playground link to code

Body:
I have 3 Types:

export type FooInitialStateType = {
  Id: string;
  Name: string;
  Email: string;
  Password: string
};

export type BarInitialStateType = {
  Id: string;
  Balance: number;
};

export type BazInitialStateType = {
  Id: string;
  Limit: number;
};

Which I then create a Union Type like so:

export type FooBarBazType = FooInitialStateType | BarInitialStateType | BazInitialStateType

I then have a generic method which processes arrays containing all 3 above Types:

  getFooBarBaz (
    events: FooBarBazType[]
  ): {
    foobarbaz0: FooBarBazType;
  } {
    const foobarbaz0 = <FooBarBazType>events[0];
    return {
      foobarbaz0
    };
  }

I then call this generic method from each class (foo, bar, baz):

    const {
      foobarbaz0
    }: {
      foobarbaz0: FooInitialStateType;
    } = this.getFooBarBaz(fooEvents);

I get a TS error:

Type 'FooBarBazType' is not assignable to type 'FooInitialStateType'.

Because FooInitialStateType doesn't contain properties from BarInitialStateType and BazInitialStateType.

Actual questions:

How can I utilise the Union Type for the generic method to accept an array with all 3 Types, but then where I invoke the method, specify what exact Type the returned value should be?

Is a Union Type the correct thing to use here? I have one method that accepts 3 different Types, and produces one Type. I need the invoking function to know, and specify, the returned Type

Body:
It's possible that you want getFooBarBaz() to be a generic function where the output type depends on the input type:

function getFooBarBaz<T extends FooBarBazType>(events: T[]): { foobarbaz0: T; } {
    const foobarbaz0 = events[0];
    return {
        foobarbaz0
    };
}

Then it might behave the way you'd like:

const fooEvents = [
    {
        Id: "foo",
        Name: "Foobert",
        Email: "foobert@example.com",
        Password: "Emb4rr4ss|ngP455w%?d"
    }
];

const {
    foobarbaz0
}: {
    foobarbaz0: FooInitialStateType;
} = getFooBarBaz(fooEvents); // no error now

Does that help?  Good luck!

<a href="https://www.typescriptlang.org/play/#code/KYDwDg9gTgLgBDAnmYcBiEIEkB2BLGPAQwBsBlGImYAFWVQF44BvAKDg7iwBMAuOAM4woeHAHMA3O04A5IgFtg-ISPFTOcAKLyieEsuGjJ0jgAUiAgQHdofQYfGsAvlNahIsBPTgAhIlFwCYnJKajoUOCY2DR4DVWMNPxIiHABjJTgcAFd5ACNgKCkXVjdwaHgkCL8AL0DCUgoqWm8oky47FSN1TgAZPHkCfmy8gqL1Uo8K7wwIPyga8MZ0TDrgxrDvAB9ff1WG0OaI7Zq9kKbFkoAzLLTCCBw4MWAYGbmagB4aOFBqHG4BZazfwLegAPgAFMAAG7AHAwAT8GgAbQAugBKfjMOCXTC5fx46oABkREjgThYbVS9yE2Nx+KIRMi3xhcIESMJKO6HCgzyyUAe0Q0nBxEDxUAJhLaxScJSpOBpIs0LPhTKRbUFQva-AARCLtQAaNoaOSKHUzfKwA1GzjaXT6OC63EFGAAAVACjAJGAADoqfIrZqzBZrLYddpcgAWKBQCOWTbiUwRgCsSasAFIAPzcbVS1ic2XU+Aa2mi+lE5yYtoisUS-gzU7rQ7AIpMp4vTBvBngxXKgRoiRAA" rel="nofollow noreferrer">Playground link to code


来源: stackexchange

问:
Pycharm (a Python IDE) can only show the first 300 members of a list
When I populate a list with more than 300 elements the working environment I'm using to read Python which is Pycharm will only show the first 300 elements.  This applies to both the community editions and the professional edition.  Does anyone know how to fix this and if not does anyone know of an IDE which can display all the elements of a list, even if that list has 10,000 elements?

Again I want to emphasize that for debugging purposes I need to be able to view the elements of a list.

This shows that more than 300 elements cannot be viewed

This shows the length of the list in question.

答:
The question is a few years old but it deals with a problem that remains relevant when using the default settings today. For PyCharm 2019.3 Community Edition on macOS (tested on 10.11.6), the solution is slightly different than in @VaclavKasal's answer. The  settings file is at /Applications/PyCharm\ CE.app/Contents/plugins/python-ce/helpers/pydev/_pydevd_bundle/pydevd_resolver.py
To display 3000 items, for example, rather than the default 100

change from:

```<code># Note: 300 is already a lot to see in the outline (after that the user should really use the shell to get things)
# and this also means we'll pass less information to the client side (which makes debugging faster).
MAX_ITEMS_TO_HANDLE = 300 if not IS_PYCHARM else 100
</code>```

to:

```<code># Note: 300 is already a lot to see in the outline (after that the user should really use the shell to get things)
# and this also means we'll pass less information to the client side (which makes debugging faster).
MAX_ITEMS_TO_HANDLE = 300 if not IS_PYCHARM else 3000
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The question is a few years old but it deals with a problem that remains relevant when using the default settings today. For PyCharm 2019.3 Community Edition on macOS (tested on 10.11.6), the solution is slightly different than in @VaclavKasal's answer. The  settings file is at /Applications/PyCharm\ CE.app/Contents/plugins/python-ce/helpers/pydev/_pydevd_bundle/pydevd_resolver.py
To display 3000 items, for example, rather than the default 100

change from:

# Note: 300 is already a lot to see in the outline (after that the user should really use the shell to get things)
# and this also means we'll pass less information to the client side (which makes debugging faster).
MAX_ITEMS_TO_HANDLE = 300 if not IS_PYCHARM else 100

to:

# Note: 300 is already a lot to see in the outline (after that the user should really use the shell to get things)
# and this also means we'll pass less information to the client side (which makes debugging faster).
MAX_ITEMS_TO_HANDLE = 300 if not IS_PYCHARM else 3000

ContentLicense: CC BY-SA 4.0


问:
Error when passing variables to C function
The program I am currently working on gets some variables from a text file and uses them to log in into a security camera. I have a config file which contains these variables as following:

```<code>192.168.1.30
8000
admin
12345
./var/users/user/files_camera/
</code>```

I am able to read and print them in the console with:

```<code>fp = fopen(filename, "r");
  if (fp == NULL)
  {
        printf("Could not open file %s",filename);
        return 0;
  }
for(int i=0; i<variables; i++)
  {
    if(fgets(str, MAXCHAR, fp) != NULL)
    {
      if(i==0)
      {
        strcpy(ip, str);
      }
      if(i==1)
      {
        sscanf(str, "%d", &port);
      }
      if(i==2)
      {
        strcpy(user, str);
      }
      if(i==3)
      {
        strcpy(password, str);
      }
      if(i==4)
      {
        strcpy(directory, str);
      }
    }
  }
  fclose(fp);

  printf("%s", ip);
  printf("%d\n", port);
  printf("%s", user);
  printf("%s", password);
  printf("%s", directory);
</code>```

The thing is that program works when using the following function:

```<code>lUserID = NET_DVR_Login_V30("192.168.1.30", 8000, "admin", "12345", &struDeviceInfo);
</code>```

But not when using:

```<code>lUserID = NET_DVR_Login_V30(ip, port, user, password, &struDeviceInfo);
</code>```

There is no error when compiling, it is just the program not working as expected: the program compiles and executes but the camera returns a login error due to wrong username and password. This is the declaration of the variables:

```<code>#define MAXCHAR 50
char ip[MAXCHAR];
int port;
char user[MAXCHAR];
char password[MAXCHAR];
char directory[MAXCHAR];
</code>```

What am I doing wrong?

答:
As Alex Skalozub said, fgets function includes newline character at the end and I was not keeping that in mind. This is what I did to solve the problem:

```<code>char buffer[MAXCHAR];

strcpy(buffer, str);
strncpy(ip, buffer, strlen(buffer)-1);
</code>```

Used an extra variable to read each line and remove the \n character at the end of each variable.

Now it is working! Thank you!

Body:
The program I am currently working on gets some variables from a text file and uses them to log in into a security camera. I have a config file which contains these variables as following:

192.168.1.30
8000
admin
12345
./var/users/user/files_camera/

I am able to read and print them in the console with:

fp = fopen(filename, "r");
  if (fp == NULL)
  {
        printf("Could not open file %s",filename);
        return 0;
  }
for(int i=0; i<variables; i++)
  {
    if(fgets(str, MAXCHAR, fp) != NULL)
    {
      if(i==0)
      {
        strcpy(ip, str);
      }
      if(i==1)
      {
        sscanf(str, "%d", &port);
      }
      if(i==2)
      {
        strcpy(user, str);
      }
      if(i==3)
      {
        strcpy(password, str);
      }
      if(i==4)
      {
        strcpy(directory, str);
      }
    }
  }
  fclose(fp);

  printf("%s", ip);
  printf("%d\n", port);
  printf("%s", user);
  printf("%s", password);
  printf("%s", directory);

The thing is that program works when using the following function:

lUserID = NET_DVR_Login_V30("192.168.1.30", 8000, "admin", "12345", &struDeviceInfo);

But not when using:

lUserID = NET_DVR_Login_V30(ip, port, user, password, &struDeviceInfo);

There is no error when compiling, it is just the program not working as expected: the program compiles and executes but the camera returns a login error due to wrong username and password. This is the declaration of the variables:

#define MAXCHAR 50
char ip[MAXCHAR];
int port;
char user[MAXCHAR];
char password[MAXCHAR];
char directory[MAXCHAR];

What am I doing wrong?

Body:
As Alex Skalozub said, fgets function includes newline character at the end and I was not keeping that in mind. This is what I did to solve the problem:

char buffer[MAXCHAR];

strcpy(buffer, str);
strncpy(ip, buffer, strlen(buffer)-1);

Used an extra variable to read each line and remove the \n character at the end of each variable.

Now it is working! Thank you!


问:
Heroku Node.js App Works Locally but not when deployed
I have a MEAN Stack Heroku app that was running just fine. But then I added a new function:

```<code>app.get('/userCreated/:id', function(req, res) {

if (req.cookies.userCreated == req.params.id) {
    res.send(true);
}
else {
    res.send(false);
}

});
</code>```

And now I get a 503 (Service Unavailable) error upon loading the app. Anyone have an idea why this might be?

I'm using Angular and $http.get() to access this Express.js function...

Edit: here is my client side Angular code that is making a call to the server:

```<code>var deferred = $q.defer();
function thisUserCreated(id) {
$http.get('/userCreated/' + id).success(function(data) {
deferred.resolve(data);
// returns boolean indicating whether the current user has the proper cookie
// saying this user created the given group
});
return deferred.promise;
};
</code>```

答: I dealt with this problem in many different forms with Node/Heroku exit status 1 and status H10 etc. etc..  I searched and search tried everything from purging the node cache to rolling everything back via git and starting again.  It seemed as though my node_modules kept updating somewhere and I would jump from getting errors to functioning locally to crashing once deployed.  The only thing that finally worked was to "not check in generated directories" in my .gitignore file, which if works for others in this situation seems like a stupid and obvious solution.  The different troubleshooting steps can be found here https://devcenter.heroku.com/articles/troubleshooting-node-deploys</p>

Body:
I have a MEAN Stack Heroku app that was running just fine. But then I added a new function:

app.get('/userCreated/:id', function(req, res) {

if (req.cookies.userCreated == req.params.id) {
    res.send(true);
}
else {
    res.send(false);
}

});

And now I get a 503 (Service Unavailable) error upon loading the app. Anyone have an idea why this might be?

I'm using Angular and $http.get() to access this Express.js function...

Edit: here is my client side Angular code that is making a call to the server:

var deferred = $q.defer();
function thisUserCreated(id) {
$http.get('/userCreated/' + id).success(function(data) {
deferred.resolve(data);
// returns boolean indicating whether the current user has the proper cookie
// saying this user created the given group
});
return deferred.promise;
};


问:
C# How do i get the Right(String) based on one character?
I have this:

```<code>MyString = @"C:\\Somepath\otherpath\etc\string";
</code>```

And i need this string (which can be longer than a group of characters)

How can i do something like:

```<code>NewString = MyString.Right(string, when last "\" is found) ?
</code>```

答:
This will return everything after the last instance of the character '\'.  </p>

```<code>var result = MyString.Substring(MyString.LastIndexOf('\\') + 1);
</code>```

Body:
I have this:

MyString = @"C:\\Somepath\otherpath\etc\string";

And i need this string (which can be longer than a group of characters)

How can i do something like:

NewString = MyString.Right(string, when last "\" is found) ?

Body:
This will return everything after the last instance of the character '\'.

var result = MyString.Substring(MyString.LastIndexOf('\\') + 1);


问:
SimpleDateFormat giving wrong date instead of error
I am using following pattern and date

Date : 13-13-2007

Pattern : dd-MM-yyyy

Output: Sun Jan 13 00:00:00 IST 2008
Or
2008-01-13 00:00:00.0

I was expecting exception here. What can i do to generate exception when given date is inproper.

答: Use DateFormat.setLenient(false) to tell the DateFormat/SimpleDateFormat that you want it to be strict.


问:
Microsoft Bot Framework Skill
Is it possible to have a separate dispatcher for skill (dispatch template and QnA model of its own)? I am not seeing this option in the skill template. Also if I can configure one how do you make it work with a parent LUIS dispatcher? I am very new to skills and following the below documentation ...
https://microsoft.github.io/botframework-solutions/skills/tutorials/customize-skill/csharp/1-intro/
Thanks</p>

答:
Just to provide more context to the Dispatch model in Virtual Assistant as you are new to skills.

The Dispatch model brings together the LUIS models and QnAMaker Knowledge bases into one experience by extracting utterances from each configured LUIS model and questions from QnA Maker and then creating a central dispatch LUIS model. The Dispatch model is used at the core of each project created using the template. It is referenced within the MainDialog class to identify whether the target is a LUIS model or QnA. In the case of LUIS, the secondary LUIS model is invoked returning the intent and entities as usual.

Dispatcher is also used for interruption detection and Skill processing whereby your Dispatch model will be updated each time you add a new Skill. The Virtual Assistant integrates Skill support for your assistant, enabling you to easily register skills through the execution of the botskills command-line tool. The ability to trigger skills based on utterances relies heavily on the Dispatcher which is automatically provisioned as part of your assistant deployment.

I would suggest you to read through the following this documentation to get a hang of the terminologies and components involved and then follow the tutorial.

Title: Microsoft Bot Framework Skill


问:
How to find every genre from an artist in a music database in MYSQL?
So I've got a database with 4 tables: artist, genre, track and album. Track table points in a many to one way to Genre table, and so on with Track to Album, and Album to Artist.

Suppose I want to find every genre that 'John Coltrane' plays, so I thought about saying

```<code>SELECT DISTINCT Artist.name, Genre.name
FROM Artist
JOIN Genre
JOIN Album
JOIN Track
WHERE Artist.name = 'John Coltrane'
  AND Track.genre_id = Genre.genre_id
</code>```

But this just gives me

i.e. ALL genres jointed to John Coltrane, instead of just 'Jazz' which is what I'm seeking...

Why is it not working?

答:
Since you didn't show all the table columns which would be used to join tables together. I will make some assumptions for you. I will be more accurate if I notice that you updated the topic and I will update my answer when I see it. Where I am incorrect about the column name that I join on just substitute the actual column with the one I put here and it will do what you are trying to do. ;-)</p>

```<code>SELECT DISTINCT ART.name,
       Genre.name
  FROM Artist ART
  JOIN Album ALB ON ART.artist_id = ALB.artist_id
  JOIN Track TRK ON ALB.album_id = TRK.album_id
  JOIN Genre G ON TRK.genre_id = G.genre_id
 WHERE ART.name = 'John Coltrane'
</code>```

Body:
So I've got a database with 4 tables: artist, genre, track and album. Track table points in a many to one way to Genre table, and so on with Track to Album, and Album to Artist.

Suppose I want to find every genre that 'John Coltrane' plays, so I thought about saying

SELECT DISTINCT Artist.name, Genre.name
FROM Artist
JOIN Genre
JOIN Album
JOIN Track
WHERE Artist.name = 'John Coltrane'
  AND Track.genre_id = Genre.genre_id

But this just gives me

i.e. ALL genres jointed to John Coltrane, instead of just 'Jazz' which is what I'm seeking...

Why is it not working?

Body:
Since you didn't show all the table columns which would be used to join tables together. I will make some assumptions for you. I will be more accurate if I notice that you updated the topic and I will update my answer when I see it. Where I am incorrect about the column name that I join on just substitute the actual column with the one I put here and it will do what you are trying to do. ;-)

SELECT DISTINCT ART.name,
       Genre.name
  FROM Artist ART
  JOIN Album ALB ON ART.artist_id = ALB.artist_id
  JOIN Track TRK ON ALB.album_id = TRK.album_id
  JOIN Genre G ON TRK.genre_id = G.genre_id
 WHERE ART.name = 'John Coltrane'


问:
Can you stop unused static objects from being constructed?
When I link a file that contains a static object, that object's constructor is ran regardless of whether the object is ever used or the header is even included. Is there a way in g++ to stop this behavior from occurring, or is the only answer to just not link the file?

foo.h

```<code>#include <iostream>

class Bar {
public:
    Bar(int inMemberInt) {
        std::cout << "In Bar constructor." << std::endl;
    }
};

class Foo {
public:
    static const Bar constVar;
};
</code>```

foo.cpp

```<code>#include "foo.h"

const Bar Foo::constVar(1);
</code>```

main.cpp

```<code>#include <iostream>

int main() {
    std::cout << "Hello." << std::endl;

    return 1;
}
</code>```

Build command

```<code>g++ foo.h foo.cpp main.cpp -o main
</code>```

Output

```<code>In Bar constructor.
Hello.
</code>```

答: Another option is to a define static object in its own source file. Then compile that source file into an object file and link that into a static library (.a) along with other object files (if any). When linking your executable (or shared library) against a static library the linker includes only those .o files from the static library that resolve any of unresolved symbols. So that if nothing refers to that static object the object file where it is defined isn't linked into your executable or shared library.

Body:
When I link a file that contains a static object, that object's constructor is ran regardless of whether the object is ever used or the header is even included. Is there a way in g++ to stop this behavior from occurring, or is the only answer to just not link the file?

foo.h

#include <iostream>

class Bar {
public:
    Bar(int inMemberInt) {
        std::cout << "In Bar constructor." << std::endl;
    }
};

class Foo {
public:
    static const Bar constVar;
};

foo.cpp

#include "foo.h"

const Bar Foo::constVar(1);

main.cpp

#include <iostream>

int main() {
    std::cout << "Hello." << std::endl;

    return 1;
}

Build command

g++ foo.h foo.cpp main.cpp -o main

Output

In Bar constructor.
Hello.


问:
If function based on query function results
Can you wrap a query function with an if function?

My query can produce 3 results, yes yes, yes no, no no. These results occur in two different cells. I want the if function to then say - yes yes - true and either of the other results false. When doing it simply it just gives an error.

答:
I was able to get an answer with using the IFS function =ifs(query(Sheet2!A3:J9,"select G where A = '"&A4&"' and '"&E4&"' = B",0)="yes","TRUE",query(Sheet2!A3:J9,"select G where A = '"&A4&"' and '"&E4&"' = B",0)="no","FALSE")

That was able to solve the issue that the simple if function could not solve


问:
Pass value from iframe to parent of different domain or port
I want to Pass value from iframe to parent of different domain and port , can  i do that if yes than how? </p>

答: I think you require postMessage</p>

Body: I think you require postMessage


问:
How to test ES6 modules (these with import) with mocha?
It is my first time with testing JS frontend and I chose mocha for that.

I have a class let us say Market which uses other classes I made.

I use import ... from ... clause and export default Market in the end.

so Market class looks like that:

```<code>import { math, AnotherClass, MyOtherClass } from '../index.js'
class Market {
  constructor () {
    // code here
  }
  methodToTest(input) {
    // some code here ...
    return output
  }
}
export default Market
</code>```

and then my test.js

```<code>var assert = require('assert')
// import { Market } from '../public/mm/ai/Market.js'
var Market = require('../public/mm/ai/Market')

describe('Market', function() {
    describe('#methodToTest()', function() {
        it('should return 0 input is greater than mean + 4 * sigma', function() {
           var market = new Market()
           assert.equal(market.methodToTest(45), 0)
        })
    })
})
</code>```

and after running the test I get the error:

```<code>import { math, AnotherClass, MyOtherClass } from '../index.js'
^^^^^^

SyntaxError: Cannot use import statement outside a module
</code>```

and an error stack.

And the question is: How to make mocha test my modules with these imports?

As you see I also tried to use import directly in test.js and it failed also.
But I don't want to rewrite my whole project to use require as it works perfectly fine in the browser as it is now.

答:
So I have found the solution myself.

Babel & mocha - the best, cause no intermediate files

First the .mocharc.js file to configure mocha to use babel and chai:

```<code>module.exports = {
    require: ['chai', '@babel/register'],
    ui: 'bdd',
    // ui: 'tdd',
    reporter: 'spec',
    growl: false,
};
</code>```

I have chosen ui:'bdd' because I used the describe in test.js:
describe('Market class:', function() {

Secondly I added babel configuration in package.json:

```<code>"babel": {
    "env": {
      "test-console": {
        "presets": ["@babel/preset-env"],
        "plugins": ["@babel/plugin-proposal-class-properties"]
      }
    ,
      "test": {
        "presets": ["@babel/preset-env"],
        "plugins": ["@babel/plugin-proposal-class-properties", "transform-remove-console"]
      }
    }
  },
</code>```

Two environments to use with console output and wituhout it.

It leads to package.json scripts section to execute one of them:

```<code> "scripts": {
    "test": "BABEL_ENV=test mocha || TRUE",
    "test-console-log": "BABEL_ENV=test-console mocha || TRUE"
  },
</code>```

and now I was ready to have my test.js executed and imports in my modules worked.

Here is the head of test.js:

```<code>var assert = require('chai').assert
import Market from '../public/mm/ai/Market.js'
...
</code>```

I switched to import when regarding my own modules.

Webpack, babel & mocha

Everything in webpack config:

```<code>var path = require('path');
const TerserPlugin = require('terser-webpack-plugin')

module.exports = {
  mode: 'none',
  entry: './test/test.js',
  output: {
      path: path.resolve(__dirname, 'test/'),
      filename: 'exec_test.js'
  },
  module: {
    rules: [
        {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/preset-env'],
                    plugins: ['@babel/plugin-proposal-class-properties']
                }
            }
        }
    ]
  },
  optimization: {
      minimize: true,
      minimizer: [new TerserPlugin({
          terserOptions: {
              compress:
              {
                  drop_console: true
                }
            }
        })]
    }
};
</code>```

and then you can build and run it by:

```<code>"scripts": {
   "build-tests-webpack": "webpack --config webpack.config.test.js",
   "exec test": "mocha --ui bdd test/exec_test.js"
}
</code>```

in package.json

Body:
It is my first time with testing JS frontend and I chose mocha for that.

I have a class let us say Market which uses other classes I made.

I use import ... from ... clause and export default Market in the end.

so Market class looks like that:

import { math, AnotherClass, MyOtherClass } from '../index.js'
class Market {
  constructor () {
    // code here
  }
  methodToTest(input) {
    // some code here ...
    return output
  }
}
export default Market

and then my test.js

var assert = require('assert')
// import { Market } from '../public/mm/ai/Market.js'
var Market = require('../public/mm/ai/Market')

describe('Market', function() {
    describe('#methodToTest()', function() {
        it('should return 0 input is greater than mean + 4 * sigma', function() {
           var market = new Market()
           assert.equal(market.methodToTest(45), 0)
        })
    })
})

and after running the test I get the error:

import { math, AnotherClass, MyOtherClass } from '../index.js'
^^^^^^

SyntaxError: Cannot use import statement outside a module

and an error stack.

And the question is: How to make mocha test my modules with these imports?

As you see I also tried to use import directly in test.js and it failed also.
But I don't want to rewrite my whole project to use require as it works perfectly fine in the browser as it is now.

Body:
So I have found the solution myself.

Babel & mocha - the best, cause no intermediate files

First the .mocharc.js file to configure mocha to use babel and chai:

module.exports = {
    require: ['chai', '@babel/register'],
    ui: 'bdd',
    // ui: 'tdd',
    reporter: 'spec',
    growl: false,
};

I have chosen ui:'bdd' because I used the describe in test.js:
describe('Market class:', function() {

Secondly I added babel configuration in package.json:

"babel": {
    "env": {
      "test-console": {
        "presets": ["@babel/preset-env"],
        "plugins": ["@babel/plugin-proposal-class-properties"]
      }
    ,
      "test": {
        "presets": ["@babel/preset-env"],
        "plugins": ["@babel/plugin-proposal-class-properties", "transform-remove-console"]
      }
    }
  },

Two environments to use with console output and wituhout it.

It leads to package.json scripts section to execute one of them:

 "scripts": {
    "test": "BABEL_ENV=test mocha || TRUE",
    "test-console-log": "BABEL_ENV=test-console mocha || TRUE"
  },

and now I was ready to have my test.js executed and imports in my modules worked.

Here is the head of test.js:

var assert = require('chai').assert
import Market from '../public/mm/ai/Market.js'
...

I switched to import when regarding my own modules.

Webpack, babel & mocha

Everything in webpack config:

var path = require('path');
const TerserPlugin = require('terser-webpack-plugin')

module.exports = {
  mode: 'none',
  entry: './test/test.js',
  output: {
      path: path.resolve(__dirname, 'test/'),
      filename: 'exec_test.js'
  },
  module: {
    rules: [
        {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/preset-env'],
                    plugins: ['@babel/plugin-proposal-class-properties']
                }
            }
        }
    ]
  },
  optimization: {
      minimize: true,
      minimizer: [new TerserPlugin({
          terserOptions: {
              compress:
              {
                  drop_console: true
                }
            }
        })]
    }
};

and then you can build and run it by:

"scripts": {
   "build-tests-webpack": "webpack --config webpack.config.test.js",
   "exec test": "mocha --ui bdd test/exec_test.js"
}

in package.json


答:
For a path specifically, you can use Path.GetFileName(String).

var MyString = @"C:\Somepath\otherpath\etc\string";
var NewString = Path.GetFileName(MyString);
```

Despite the name of the method, it also works on directory names, provided they aren't followed by a trailing backslash. So C:\directory becomes directory, but C:\directory\ becomes the empty string. (This might be what you want, based on how you phrased the question.)

Title: C# How do i get the Right(String) based on one character?

Body:
For a path specifically, you can use Path.GetFileName(String).

var MyString = @"C:\Somepath\otherpath\etc\string";
var NewString = Path.GetFileName(MyString);

Despite the name of the method, it also works on directory names, provided they aren't followed by a trailing backslash. So C:\directory becomes directory, but C:\directory\ becomes the empty string. (This might be what you want, based on how you phrased the question.)


问:
Is there a way to print a pointer with %x argument
I have tried to make a program with the parameter %d in a pointer but it does not work, I changed  to %p, but that is for the address, I want to print the value.
This is the error

```
gcc null_Pointer.c -o null_Pointer
null_Pointer.c: In function ‘main’:
null_Pointer.c:7:35: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
    7 |    printf("The value of ptr is : %x\n", ptr  );
      |                                  ~^     ~~~
      |                                   |     |
      |                                   |     int *
      |                                   unsigned int
      |                                  %ls
```

this  is the  code

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

int main () {

   int  *ptr = NULL;

   printf("The value of ptr is : %x\n", ptr  );

   return 0;
}
</code>```

答:
To print the address value stored in ptr:

```<code>printf( "The value of ptr is %p\n", (void *) ptr );
</code>```

The print the value of the thing ptr points to:

```<code>printf( "The value of what ptr points to: " );
if ( !ptr )
  printf( "(null)\n" );
else
  printf( "%d\n", *ptr );
</code>```

If ptr is NULL, this code will print the string (null).  If ptr is not NULL but otherwise invalid (doesn't point to an int object within that object's lifetime), then the behavior is undefined.  You may get garbage output, you may get a runtime error, "The Lonely Goatherd" may start playing out of your computer, etc.  There's no good way to test if a non-NULL pointer is valid, which is why it's a good idea to set unused pointer objects to NULL.

Body:
I have tried to make a program with the parameter %d in a pointer but it does not work, I changed  to %p, but that is for the address, I want to print the value.
This is the error

gcc null_Pointer.c -o null_Pointer
null_Pointer.c: In function ‘main’:
null_Pointer.c:7:35: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
    7 |    printf("The value of ptr is : %x\n", ptr  );
      |                                  ~^     ~~~
      |                                   |     |
      |                                   |     int *
      |                                   unsigned int
      |                                  %ls

this  is the  code

#include <stdio.h>

int main () {

   int  *ptr = NULL;

   printf("The value of ptr is : %x\n", ptr  );

   return 0;
}

Body:
To print the address value stored in ptr:

printf( "The value of ptr is %p\n", (void *) ptr );

The print the value of the thing ptr points to:

printf( "The value of what ptr points to: " );
if ( !ptr )
  printf( "(null)\n" );
else
  printf( "%d\n", *ptr );

If ptr is NULL, this code will print the string (null).  If ptr is not NULL but otherwise invalid (doesn't point to an int object within that object's lifetime), then the behavior is undefined.  You may get garbage output, you may get a runtime error, "The Lonely Goatherd" may start playing out of your computer, etc.  There's no good way to test if a non-NULL pointer is valid, which is why it's a good idea to set unused pointer objects to NULL.


问:
Why does mutating a value of a parent directive's scope in link not provide that mutated state to a child directive?
I have a parent directive being passed an array as the value for one of its attributes. The parent directive's job is render some components, and then send a modified version of that array to a child directive. The child directive needs to then render the modified array.

Adjusting this array in the parent directive's link function does not seem to propagate the change to the rendered child directive.

Why is this?

I am only a couple days into AngularJS and may have a fundamental misunderstanding of scope or lifecycle, though I'm not sure which.

The example below modifies an array of [1,2] provided to the parent directive by having the parent directive push 3 into it.

The parent directive renders a template containing the child directive and, what I had hoped to be, the mutated array.

The screen will render the unmutated array (rendered from the child directive) but console.log the mutated array (logged from the parent directive)

https://codesandbox.io/s/trusting-fire-k4so0?fontsize=14&hidenavigation=1&theme=dark

src/index.js

```<code>"use_strict";

var angular = require("angular");

angular
  .module("App", [])
  .controller("IgnorableController", [function(){}])
  .directive("parentIsolatedScope", [
    function() {
      return {
        restrict: "E",
        template:
          "<child-isolated-scope mutated-array='mutableArray'></child-isolated-scope>",
        scope: {
          mutableArray: "<"
        },
        link: function(scope) {
          scope.mutableArray.push(3);
          console.log(scope.mutableArray);
        }
      };
    }
  ])
  .directive("childIsolatedScope", [
    function() {
      return {
        restrict: "E",
        template: "<div>{{mutatedArray | json}}</div>",
        scope: {
          mutatedArray: "<"
        }
      };
    }
  ]);
</code>```

index.html

```<code><!DOCTYPE html>
<html ng-app="App">
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <script src="src/index.js"></script>
  </head>

  <body ng-controller="IgnorableController">
    <parent-isolated-scope mutable-array="[1,2]"></parent-isolated-scope>
  </body>
</html>
</code>```

答:
If you declare a variable for the initial array and use it to pass the array into the directive it will work as expected:

```<code><body ng-controller="IgnorableController">
    <parent-isolated-scope mutable-array="initialArray"></parent-isolated-scope>
</body>
</code>```

in IgnorableController, array variable:

```<code>$scope.initialArray= [1, 2];
</code>```

working demo: DEMO

Body:
I have a parent directive being passed an array as the value for one of its attributes. The parent directive's job is render some components, and then send a modified version of that array to a child directive. The child directive needs to then render the modified array.

Adjusting this array in the parent directive's link function does not seem to propagate the change to the rendered child directive.

Why is this?

I am only a couple days into AngularJS and may have a fundamental misunderstanding of scope or lifecycle, though I'm not sure which.

The example below modifies an array of [1,2] provided to the parent directive by having the parent directive push 3 into it.

The parent directive renders a template containing the child directive and, what I had hoped to be, the mutated array.

The screen will render the unmutated array (rendered from the child directive) but console.log the mutated array (logged from the parent directive)

https://codesandbox.io/s/trusting-fire-k4so0?fontsize=14&hidenavigation=1&theme=dark

src/index.js

"use_strict";

var angular = require("angular");

angular
  .module("App", [])
  .controller("IgnorableController", [function(){}])
  .directive("parentIsolatedScope", [
    function() {
      return {
        restrict: "E",
        template:
          "<child-isolated-scope mutated-array='mutableArray'></child-isolated-scope>",
        scope: {
          mutableArray: "<"
        },
        link: function(scope) {
          scope.mutableArray.push(3);
          console.log(scope.mutableArray);
        }
      };
    }
  ])
  .directive("childIsolatedScope", [
    function() {
      return {
        restrict: "E",
        template: "
{{mutatedArray | json}}
",
        scope: {
          mutatedArray: "<"
        }
      };
    }
  ]);

index.html

<!DOCTYPE html>

    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />

    <parent-isolated-scope mutable-array="[1,2]"></parent-isolated-scope>

Body:
If you declare a variable for the initial array and use it to pass the array into the directive it will work as expected:

<body ng-controller="IgnorableController">
    <parent-isolated-scope mutable-array="initialArray"></parent-isolated-scope>
</body>

in IgnorableController, array variable:

$scope.initialArray= [1, 2];

working demo: DEMO


问:
Why I am not getting the Coverage with SonarQube?
I am running a Jenkin's job to run the test cases with Mocha and to run sonar-scanner on a project with AngularJS and Node. In SonarQube, I am not getting the coverage result but I am getting the other results. And I have included lcov.info file path as well. And below are the properties and the values that I have given to Sonar.

```<code>sonar.projectKey=my:project
sonar.projectName=my
sonar.projectVersion=1.0

sonar.sources=lib
sonar.tests=test
sonar.language=js
sonar.javascript.lcov.reportPaths=coverage/lcov.info
</code>```

Can anyone please help me to find a solution for this?

答: I was using an older version of Sonar Qube. So, it is getting the coverage with sonar.javascript.lcov.reportPath, not with  sonar.javascript.lcov.reportPaths.

Body:
I am running a Jenkin's job to run the test cases with Mocha and to run sonar-scanner on a project with AngularJS and Node. In SonarQube, I am not getting the coverage result but I am getting the other results. And I have included lcov.info file path as well. And below are the properties and the values that I have given to Sonar.

sonar.projectKey=my:project
sonar.projectName=my
sonar.projectVersion=1.0

sonar.sources=lib
sonar.tests=test
sonar.language=js
sonar.javascript.lcov.reportPaths=coverage/lcov.info

Can anyone please help me to find a solution for this?


问:
SQLite Getting multiple results with LIMIT 1
I have the following problem.

Part of a task is to determine the visitor(s) with the most money spent between 2000 and 2020.
It just looks like this.

```<code>SELECT UserEMail FROM Visitor
JOIN Ticket ON Visitor.UserEMail = Ticket.VisitorUserEMail
where Ticket.Date> date('2000-01-01') AND Ticket.Date < date ('2020-12-31')
Group by Ticket.VisitorUserEMail
order by SUM(Price) DESC;
</code>```

Is it possible to output more than one person if both have spent the same amount?

答:
Use rank():

```<code>SELECT VisitorUserEMail
FROM (SELECT VisitorUserEMail, SUM(PRICE) as sum_price,
             RANK() OVER (ORDER BY SUM(Price) DESC) as seqnum
      FROM Ticket t
      WHERE t.Date >= date('2000-01-01') AND Ticket.Date <= date('2021-01-01')
      GROUP BY t.VisitorUserEMail
     ) t
WHERE seqnum = 1;
</code>```

Note:  You don't need the JOIN, assuming that ticket buyers are actually visitors.  If that assumption is not true, then use the JOIN.

Body:
I have the following problem.

Part of a task is to determine the visitor(s) with the most money spent between 2000 and 2020.
It just looks like this.

SELECT UserEMail FROM Visitor
JOIN Ticket ON Visitor.UserEMail = Ticket.VisitorUserEMail
where Ticket.Date> date('2000-01-01') AND Ticket.Date < date ('2020-12-31')
Group by Ticket.VisitorUserEMail
order by SUM(Price) DESC;

Is it possible to output more than one person if both have spent the same amount?

Body:
Use rank():

SELECT VisitorUserEMail
FROM (SELECT VisitorUserEMail, SUM(PRICE) as sum_price,
             RANK() OVER (ORDER BY SUM(Price) DESC) as seqnum
      FROM Ticket t
      WHERE t.Date >= date('2000-01-01') AND Ticket.Date <= date('2021-01-01')
      GROUP BY t.VisitorUserEMail
     ) t
WHERE seqnum = 1;

Note:  You don't need the JOIN, assuming that ticket buyers are actually visitors.  If that assumption is not true, then use the JOIN.


问:
Should I return an array or a collection from a function?
What's the preferred container type when returning multiple objects of the same type from a function?

Is it against good practice to return a simple array (like MyType[]), or should you wrap it in some generic container (like ICollection<MyType>)?

Thanks!

答:
Why not IList<MyType>?

It supports direct indexing which is hallmark for an array without removing the possibility to return a List<MyType> some day. If you want to suppress this feature, you probably want to return IEnumerable<MyType>.

OwnerDisplayName: Pwninstein

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Mehrdad Afshari


问:
Embeding video in Safari
Below is the source code for my html web page on Safari.
But when I am opening this web page it displays the source code instead of playing the video.

Any help on this will be appreciated.
I am completely new to this domain so pardon my ignorance.

答: Displays the source code?  Are you certain it isn't actually dropping '<' / '>' into your code?  As an element, even if it isn't understood by the browser (which shouldn't be the case here), it shouldn't show the source.</p>

Title: Embeding video in Safari

Body: Displays the source code?  Are you certain it isn't actually dropping '&lt;' / '&gt;' into your code?  As an element, even if it isn't understood by the browser (which shouldn't be the case here), it shouldn't show the source.


问:
Runtime Error 91 : Export Global contact list in outlook 2016
Now I'm export Global contact list in outlook 2016. to Excel file. This's my code:

```<code> Sub ExportOutlookAddressBook()
 Application.ScreenUpdating = False
 Dim olApp As Outlook.Application
 Dim olNS As Outlook.Namespace
 Dim olAL As Outlook.AddressList
 Dim olEntry As Outlook.AddressEntry

 Set olApp = Outlook.Application
 Set olNS = olApp.GetNamespace("MAPI")
 Set olAL = olNS.AddressLists("Global Address List") 'Change name if different contacts list name
 ActiveWorkbook.ActiveSheet.Range("a1").Select
 For Each olEntry In olAL.AddressEntries
 'ActiveCell.Value = olEntry.GetContact.FullName
 ActiveCell.Offset(0, 0).Value = olEntry.Name
 ActiveCell.Offset(1, 0).Select
 Next olEntry
 Set olApp = Nothing
 Set olNS = Nothing
 Set olAL = Nothing
 Application.ScreenUpdating = True
 End Sub
</code>```

It have Runtime Error 91!.How can I Fix this Error? >/\<

答:
Use GetExchangeUser istead of GetContact.

For example:

```<code>    Dim olExUser As Outlook.ExchangeUser

    Set olExUser = Nothing
    Set olExUser = olEntry.GetExchangeUser
    If Not olExUser Is Nothing Then
        With olExUser
            ActiveCell.Value = .FirstName & " " & .LastName
        End With
    End If
</code>```

Body:
Now I'm export Global contact list in outlook 2016. to Excel file. This's my code:

 Sub ExportOutlookAddressBook()
 Application.ScreenUpdating = False
 Dim olApp As Outlook.Application
 Dim olNS As Outlook.Namespace
 Dim olAL As Outlook.AddressList
 Dim olEntry As Outlook.AddressEntry

 Set olApp = Outlook.Application
 Set olNS = olApp.GetNamespace("MAPI")
 Set olAL = olNS.AddressLists("Global Address List") 'Change name if different contacts list name
 ActiveWorkbook.ActiveSheet.Range("a1").Select
 For Each olEntry In olAL.AddressEntries
 'ActiveCell.Value = olEntry.GetContact.FullName
 ActiveCell.Offset(0, 0).Value = olEntry.Name
 ActiveCell.Offset(1, 0).Select
 Next olEntry
 Set olApp = Nothing
 Set olNS = Nothing
 Set olAL = Nothing
 Application.ScreenUpdating = True
 End Sub

It have Runtime Error 91!.How can I Fix this Error? >/\<

Body:
Use GetExchangeUser istead of GetContact.

For example:

    Dim olExUser As Outlook.ExchangeUser

    Set olExUser = Nothing
    Set olExUser = olEntry.GetExchangeUser
    If Not olExUser Is Nothing Then
        With olExUser
            ActiveCell.Value = .FirstName & " " & .LastName
        End With
    End If


问:
how to get specific characters between others in a string with jquery?
Having a string such like this one:

```<code>var str = "https://www.portalinmobiliario.com/venta/departamento/vitacura-metropolitana/6579-parque-arboleda-nva";
</code>```

I need to be able to only get "6579" number from that string, because it is an ID I need to use. In fact,
this ID is always located between that last "/" and the next "-" that follows.

So considering that the url is dynamic but this "ID" is always between these two characters "/" and "-", I have to be able to always get the ID.

Any Idea how could I solve this?

I tried with this but

```<code>var id = str.lastIndexOf('/');
</code>```

答:
If you do not want to use a regexp.

```<code>'"https://www.portalinmobiliario.com/venta/departamento/vitacura-metropolitana/6579-parque-arboleda-nva"'
  .split('/').pop()
  .split('-').shift();
</code>```

pop() removes the last element.

shift() removes the first element.

Body:
Having a string such like this one:

var str = "https://www.portalinmobiliario.com/venta/departamento/vitacura-metropolitana/6579-parque-arboleda-nva";

I need to be able to only get "6579" number from that string, because it is an ID I need to use. In fact,
this ID is always located between that last "/" and the next "-" that follows.

So considering that the url is dynamic but this "ID" is always between these two characters "/" and "-", I have to be able to always get the ID.

Any Idea how could I solve this?

I tried with this but

var id = str.lastIndexOf('/');

Body:
If you do not want to use a regexp.

'"https://www.portalinmobiliario.com/venta/departamento/vitacura-metropolitana/6579-parque-arboleda-nva"'
  .split('/').pop()
  .split('-').shift();

pop() removes the last element.

shift() removes the first element.


问:
How to reference HtmlTemplate variables in javascript in Google Apps Script
I'm trying to reference a variable I've set in my html template inside the javascript section of my HTML file.

Using the Google example code

```<code>function doGet() {
  var t = HtmlService.createTemplateFromFile('Index');
  t.data = SpreadsheetApp
      .openById('1234567890abcdefghijklmnopqrstuvwxyz')
      .getActiveSheet()
      .getDataRange()
      .getValues();
  return t.evaluate();
}
</code>```

I could reference t.data in my HTML with

```<code><? data ?>
</code>```

But how do I reference the same variable in javascript?

答:
You could use </p>

```<code><script>
  const data = <? data ?>
</script>
</code>```

Body:
I'm trying to reference a variable I've set in my html template inside the javascript section of my HTML file.

Using the Google example code

function doGet() {
  var t = HtmlService.createTemplateFromFile('Index');
  t.data = SpreadsheetApp
      .openById('1234567890abcdefghijklmnopqrstuvwxyz')
      .getActiveSheet()
      .getDataRange()
      .getValues();
  return t.evaluate();
}

I could reference t.data in my HTML with

<? data ?>

But how do I reference the same variable in javascript?

Body:
You could use

<script>
  const data = <? data ?>
</script>


问:
Error when passing variables to C function
The program I am currently working on gets some variables from a text file and uses them to log in into a security camera. I have a config file which contains these variables as following:

```<code>192.168.1.30
8000
admin
12345
./var/users/user/files_camera/
</code>```

I am able to read and print them in the console with:

```<code>fp = fopen(filename, "r");
  if (fp == NULL)
  {
        printf("Could not open file %s",filename);
        return 0;
  }
for(int i=0; i<variables; i++)
  {
    if(fgets(str, MAXCHAR, fp) != NULL)
    {
      if(i==0)
      {
        strcpy(ip, str);
      }
      if(i==1)
      {
        sscanf(str, "%d", &port);
      }
      if(i==2)
      {
        strcpy(user, str);
      }
      if(i==3)
      {
        strcpy(password, str);
      }
      if(i==4)
      {
        strcpy(directory, str);
      }
    }
  }
  fclose(fp);

  printf("%s", ip);
  printf("%d\n", port);
  printf("%s", user);
  printf("%s", password);
  printf("%s", directory);
</code>```

The thing is that program works when using the following function:

```<code>lUserID = NET_DVR_Login_V30("192.168.1.30", 8000, "admin", "12345", &struDeviceInfo);
</code>```

But not when using:

```<code>lUserID = NET_DVR_Login_V30(ip, port, user, password, &struDeviceInfo);
</code>```

There is no error when compiling, it is just the program not working as expected: the program compiles and executes but the camera returns a login error due to wrong username and password. This is the declaration of the variables:

```<code>#define MAXCHAR 50
char ip[MAXCHAR];
int port;
char user[MAXCHAR];
char password[MAXCHAR];
char directory[MAXCHAR];
</code>```

What am I doing wrong?

答:
```<code>  printf("%s", ip);
  printf("%d\n", port);
  printf("%s", user);
  printf("%s", password);
  printf("%s", directory);
</code>```

Did you notice you've needed "%d\n" for the port but didn't need "\n" for string parameters? That should give the idea those parameters already end with newline characters. So you pass wrond string to the function, not "12345", but "12345\n".

Body:
The program I am currently working on gets some variables from a text file and uses them to log in into a security camera. I have a config file which contains these variables as following:

192.168.1.30
8000
admin
12345
./var/users/user/files_camera/

I am able to read and print them in the console with:

fp = fopen(filename, "r");
  if (fp == NULL)
  {
        printf("Could not open file %s",filename);
        return 0;
  }
for(int i=0; i<variables; i++)
  {
    if(fgets(str, MAXCHAR, fp) != NULL)
    {
      if(i==0)
      {
        strcpy(ip, str);
      }
      if(i==1)
      {
        sscanf(str, "%d", &port);
      }
      if(i==2)
      {
        strcpy(user, str);
      }
      if(i==3)
      {
        strcpy(password, str);
      }
      if(i==4)
      {
        strcpy(directory, str);
      }
    }
  }
  fclose(fp);

  printf("%s", ip);
  printf("%d\n", port);
  printf("%s", user);
  printf("%s", password);
  printf("%s", directory);

The thing is that program works when using the following function:

lUserID = NET_DVR_Login_V30("192.168.1.30", 8000, "admin", "12345", &struDeviceInfo);

But not when using:

lUserID = NET_DVR_Login_V30(ip, port, user, password, &struDeviceInfo);

There is no error when compiling, it is just the program not working as expected: the program compiles and executes but the camera returns a login error due to wrong username and password. This is the declaration of the variables:

#define MAXCHAR 50
char ip[MAXCHAR];
int port;
char user[MAXCHAR];
char password[MAXCHAR];
char directory[MAXCHAR];

What am I doing wrong?

Body:
  printf("%s", ip);
  printf("%d\n", port);
  printf("%s", user);
  printf("%s", password);
  printf("%s", directory);

Did you notice you've needed "%d\n" for the port but didn't need "\n" for string parameters? That should give the idea those parameters already end with newline characters. So you pass wrond string to the function, not "12345", but "12345\n".


问:
Not able to pass down an object to history.push()
Basically, I have an object name as currentUser generated from chatkit server. This object contains all the information as well as some methods of currently logged in user.

I want to pass this object as a prop to another component. I tried passing it to history.push by initially stringifying it, but after parsing the object at receiving end, I am not able to access the methods of the object. I know that json.stringify does exclude functions. Is there any other way that the stringify method does include the methods as well?

Can anyone suggest another way for passing down this object as props. I have seen something called localStorage. I am not sure how to use it. I would be grateful for any help.

答:
Try this one</p>

```<code>this.props.history.push({
  pathname: '/your url',
  state: { anyKeyName: yourObject }
})
</code>```

Body:
Try this one

this.props.history.push({
  pathname: '/your url',
  state: { anyKeyName: yourObject }
})


问:
How do I find package names for java classes when I don't know what package it's in?
What is an easy way to find what package to import when you know the name of the class, but don't know what package it's found in?

This drives me nuts, and I waste a lot of time. For example ... I have a bit of example code

```<code>    String[] people = wholeFile.Split(
        new String[] { Environment.NewLine + Environment.NewLine },
                       StringSplitOptions.RemoveEmptyEntries
    );
</code>```

But I have no idea where to locate Environment or StringSplitOptions.

People post examples of code, and that's great. But I waste time trying to figure out what package holds the classes afterwards. In this case ... I couldn't figure it out at all. What's the use of code examples when you have no clue what package to import? No search I've found resolves where to find a class you know the name of, but not what package you have to import to use it.

I shouldn't have to post here and say "What package is so and so found in ..."

So, what package is StringSplitOptions found in ... and Environment ...

There has to be an easier way to resolve knowing a class name, but needing to find what package to import to use it.

答:
The code you've posted is C#, not Java. They have very similar syntax, so the mistake is understandable.

My usual solution to this problem is google. When I googled "java Environment.NewLine" the first result was a question about finding the Java equivalent for that in C#. I found something similar when googling "java StringSplitOptions". The only reasonable conclusion, then, is that this isn't Java code.

Body:
What is an easy way to find what package to import when you know the name of the class, but don't know what package it's found in?

This drives me nuts, and I waste a lot of time. For example ... I have a bit of example code

    String[] people = wholeFile.Split(
        new String[] { Environment.NewLine + Environment.NewLine },
                       StringSplitOptions.RemoveEmptyEntries
    );

But I have no idea where to locate Environment or StringSplitOptions.

People post examples of code, and that's great. But I waste time trying to figure out what package holds the classes afterwards. In this case ... I couldn't figure it out at all. What's the use of code examples when you have no clue what package to import? No search I've found resolves where to find a class you know the name of, but not what package you have to import to use it.

I shouldn't have to post here and say "What package is so and so found in ..."

So, what package is StringSplitOptions found in ... and Environment ...

There has to be an easier way to resolve knowing a class name, but needing to find what package to import to use it.


问:
Cocos2d animations across multiple objects
I have a tile object which I look through to see if I need to create an animation. If I need to I create the animation and add it to an array

I then go off and loop through some more tile objects adding more animation to the array.

I then want to run the array of animation in sequence however I don't have the original object to instantiate run action from, this means they have to be run on the last object which means they all start from that last objects position instead of the position that the animation was created from.

Can anyone suggest a way that I can build up an array of animations for multiple different objects then run it so they appear in the position on the board where I created them at.

答: I have resolved my issue by having a function i call in a loop after the animation has completed, not as clean as i hoped but a suitable solution.</p>


问:
How to add more then one array on same "for" in lua
how can I use "for k, j in pairs() do" for 2 arrays in lua?</p>

```<code> local blipmarker1 = {
      { x = 10 , y = 5, z = 3 },
      { x = 5, y = 5, z= 3}
}
local blipmarker2 = {
      { x = 100, y= 150, z=30 }
}
function createtext(){
    local pos = GetEntityCoords(PlayerPedId(), true)
    for k, j in pairs(blipmarker1,blimarker2) do
        draw3DText(pos.x, pos.y, pos.z, j.x, j.y, j.z)
    end
 }
</code>```

答:
Function pairs() accepts only one argument of type table. You need a loop for each table:

```<code>for k,j in pairs(blipmarker1) do
  ...
end
for k,j in pairs(blipmarker2) do
  ...
end
</code>```

Body:
how can I use "for k, j in pairs() do" for 2 arrays in lua?

 local blipmarker1 = {
      { x = 10 , y = 5, z = 3 },
      { x = 5, y = 5, z= 3}
}
local blipmarker2 = {
      { x = 100, y= 150, z=30 }
}
function createtext(){
    local pos = GetEntityCoords(PlayerPedId(), true)
    for k, j in pairs(blipmarker1,blimarker2) do
        draw3DText(pos.x, pos.y, pos.z, j.x, j.y, j.z)
    end
 }

Body:
Function pairs() accepts only one argument of type table. You need a loop for each table:

for k,j in pairs(blipmarker1) do
  ...
end
for k,j in pairs(blipmarker2) do
  ...
end


问:
Showing an image based on a number range in Javascript
I am trying to create a javascript program that prompts the user for a number. If a user puts in a number that is less then 21, an image of soda will show. If the number is 21 or greater, the image is beer. There is an image of a bar that is shown when the page loads. Negatives and non-numbers are not allowed in the code. I have worked on this code for over a couple of days and the code does run. The only problem I have with it is that it will say that any input is an invalid entry. I have looked around for any solutions and I'm not sure what to do. I am new to javascript and any help would be appreciated.

Below is the javascript I am using:

```<code>function start()
{
  let button1 = document.getElementById("button1");
  button1.onclick = toggleContent;
}

function toggleContent()
{
  let number = document.getElementById('number');
  let liquid = document.getElementById('Bar');

  if parseInt(number <= 20)
  {
      liquid.src = 'assets/Soda.png';
      liquid.alt = 'Spicy water';
  }
  else if (number >= 21)
  {
    liquid.src = 'assets/Beer.png';
    liquid.alt = 'Angry Juice';
  }
  else if (isNaN(number) || number < 0)
  {
    alert("Invalid Entry. Enter a Number.")
  }
}
window.onload = start;
</code>```

Here is the HTML code that goes with it:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>ID Check?</title>
    <script src="scripts/pt2script.js"></script>
  </head>
  <body>
    <img id="Bar" src="assets/barimage.png" alt="Image of a Bar Sign.">
    <p>Enter a number into the text box.</p>
    <input type="text" id="number" value="Enter a number...">
    <button onclick="toggleContent()" id="button1">Submit</button>
  </body>
</html>

</code>```

答:
You are attempting to convert a boolean to an integer. This will not work sense (num >= 20) or whatever will evaluate to true or false, and not a number (NaN). You can convert the value to a number before trying to do a logical comparison. I'd do something such as:

```<code>$('.btn').on('click', function() {
    let val = $('#num').val();
    val = parseInt(val);
    if(val >= 21) {
        $('img').attr('src', '/path-to-soda');
    }
    else {
        $('img').attr('src', '/other-path');
    }
});
</code>```

As soon as an event triggers your number comparison I would instantly convert it to a number (i'm assuming you are using a number input which will do this for you), and then perform the logical operation. If you're using a number input (which again, i'm just assuming), you won't even need to convert the value to a number. That's only necessary if you're using a text input or something along those lines.

Body:
I am trying to create a javascript program that prompts the user for a number. If a user puts in a number that is less then 21, an image of soda will show. If the number is 21 or greater, the image is beer. There is an image of a bar that is shown when the page loads. Negatives and non-numbers are not allowed in the code. I have worked on this code for over a couple of days and the code does run. The only problem I have with it is that it will say that any input is an invalid entry. I have looked around for any solutions and I'm not sure what to do. I am new to javascript and any help would be appreciated.

Below is the javascript I am using:

function start()
{
  let button1 = document.getElementById("button1");
  button1.onclick = toggleContent;
}

function toggleContent()
{
  let number = document.getElementById('number');
  let liquid = document.getElementById('Bar');

  if parseInt(number <= 20)
  {
      liquid.src = 'assets/Soda.png';
      liquid.alt = 'Spicy water';
  }
  else if (number >= 21)
  {
    liquid.src = 'assets/Beer.png';
    liquid.alt = 'Angry Juice';
  }
  else if (isNaN(number) || number < 0)
  {
    alert("Invalid Entry. Enter a Number.")
  }
}
window.onload = start;

Here is the HTML code that goes with it:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>ID Check?</title>

Enter a number into the text box.

    <input type="text" id="number" value="Enter a number...">
    <button onclick="toggleContent()" id="button1">Submit</button>

Body:
You are attempting to convert a boolean to an integer. This will not work sense (num >= 20) or whatever will evaluate to true or false, and not a number (NaN). You can convert the value to a number before trying to do a logical comparison. I'd do something such as:

$('.btn').on('click', function() {
    let val = $('#num').val();
    val = parseInt(val);
    if(val >= 21) {
        $('img').attr('src', '/path-to-soda');
    }
    else {
        $('img').attr('src', '/other-path');
    }
});

As soon as an event triggers your number comparison I would instantly convert it to a number (i'm assuming you are using a number input which will do this for you), and then perform the logical operation. If you're using a number input (which again, i'm just assuming), you won't even need to convert the value to a number. That's only necessary if you're using a text input or something along those lines.


答:
You can use a regular expression to match digits, followed by a dash and making sure anything after it is not a slash.

var str = "https://www.portalinmobiliario.com/venta/departamento/vitacura-metropolitana/6579-parque-arboleda-nva";
console.log(str.match(/\/(\d+)-[^/]+$/)[1])```

Title: how to get specific characters between others in a string with jquery?


问:
Speeding up loops over a Numpy array
In my code I have for loop that indexes over a multidimensional numpy array and does some operation using the sub-array that is obtained at each iteration. It looks like this

```<code>for sub in Arr:
  #do stuff using sub
</code>```

Now the stuff that is done using sub is fully vectorized, so it should be efficient. On the other hand this loop iterates about ~10^5  times and is the bottleneck. Do you think I will get an improvement by offloading this part to C. I am somewhat reluctant to do so because the do stuff using sub uses broadcasting, slicing, smart-indexing tricks that would be tedious to write in plain C. I would also welcome thoughts and suggestions about how to deal with broadcasting, slicing, smart-indexing when offloading computation to C.

答: Besides using Cython, you can write the bottle-neck part(s) in Fortran. Then use f2py to compile it to Python .pyd file.</p>

Title: Speeding up loops over a Numpy array

Body:
In my code I have for loop that indexes over a multidimensional numpy array and does some operation using the sub-array that is obtained at each iteration. It looks like this

for sub in Arr:
  #do stuff using sub

Now the stuff that is done using sub is fully vectorized, so it should be efficient. On the other hand this loop iterates about ~10^5  times and is the bottleneck. Do you think I will get an improvement by offloading this part to C. I am somewhat reluctant to do so because the do stuff using sub uses broadcasting, slicing, smart-indexing tricks that would be tedious to write in plain C. I would also welcome thoughts and suggestions about how to deal with broadcasting, slicing, smart-indexing when offloading computation to C.


问:
Convert struct to *interface{}
I'm using checkr/goflagr, specifically trying to build an EvalContext and fill in the EntityContext field (some content removed below for the sake of brevity)

type EvalContext struct {

    EntityContext *interface{} `json:"entityContext,omitempty"`
    // flagID
    FlagID int64 `json:"flagID,omitempty"`

}
```

<p>This code is generated by SwaggerGen, and I'm not sure how I can send in a struct to this function without having some awful workaround.</p>

<p>My intuition said I should be able to just pass the address of an instance of a struct, e.g.</p>

<pre class="lang-golang prettyprint-override"><code>    type entityContext struct {
        Environment string `json:"environment"`
    }

    entityContextImpl := entityContext{Environment:"prod"}

    eval_ctx := goflagr.EvalContext{
        FlagID: int64(19),
        EntityContext: &entityContextImpl,
    }
</code>```

But this fails with

```<code>cannot use &entityContextImpl (type *entityContext) as type *interface {} in field value:
    *interface {} is pointer to interface, not interface
</code>```

I've gotten it to work with the following workaround:

func convertToStarInterface(i interface{}) *interface{} {
    return &i
}

func myFunc() {
    type entityContext struct {
        Environment string `json:"environment"`
    }

    entityContextImpl := entityContext{Environment:"prod"}

    ec := goflagr.EvalContext{
        FlagID: int64(18),
        EntityContext: convertToStarInterface(entityContextImpl),
    }
}
```

But it feels like there must be a way around having to use this converter function

答:
An *interface{} is as ugly as it can get. It is perfectly possible to implement omitempty with an interface{}, because an interface{} can be nil. You should consider submitting a bug for this. Anyhow...

If you need to pass an *interface{}, you can do it:

```<code>var i interface{}
i=someStruct{}
ctx.EntityContext=&i
</code>```

Your function works as well, however, it is not necessarily efficient or easier on the eye.

Title: Convert struct to *interface{}

Body:
I'm using checkr/goflagr, specifically trying to build an EvalContext and fill in the EntityContext field (some content removed below for the sake of brevity)

type EvalContext struct {

    EntityContext *interface{} `json:"entityContext,omitempty"`
    // flagID
    FlagID int64 `json:"flagID,omitempty"`

}

This code is generated by SwaggerGen, and I'm not sure how I can send in a struct to this function without having some awful workaround.

My intuition said I should be able to just pass the address of an instance of a struct, e.g.

    type entityContext struct {
        Environment string `json:"environment"`
    }

    entityContextImpl := entityContext{Environment:"prod"}

    eval_ctx := goflagr.EvalContext{
        FlagID: int64(19),
        EntityContext: &entityContextImpl,
    }

But this fails with

cannot use &entityContextImpl (type *entityContext) as type *interface {} in field value:
    *interface {} is pointer to interface, not interface

I've gotten it to work with the following workaround:

func convertToStarInterface(i interface{}) *interface{} {
    return &i
}

func myFunc() {
    type entityContext struct {
        Environment string `json:"environment"`
    }

    entityContextImpl := entityContext{Environment:"prod"}

    ec := goflagr.EvalContext{
        FlagID: int64(18),
        EntityContext: convertToStarInterface(entityContextImpl),
    }
}

But it feels like there must be a way around having to use this converter function

Body:
An *interface{} is as ugly as it can get. It is perfectly possible to implement omitempty with an interface{}, because an interface{} can be nil. You should consider submitting a bug for this. Anyhow...

If you need to pass an *interface{}, you can do it:

var i interface{}
i=someStruct{}
ctx.EntityContext=&i

Your function works as well, however, it is not necessarily efficient or easier on the eye.


问:
Sphinx docs builds fail on readthedocs for private GitHub repository
I have set up and built Sphinx docs (2.1.2) for a Python 3.6 project which is currently in a private GitHub repository. I want to host the docs on readthedocs.org after releasing the project publicly, but at the moment the readthedocs builds are always failing with this error message

```<code> git clone --no-single-branch --depth 50 https://github.com/<user name>/<repo name> .

Cloning into '.'...
fatal: could not read Username for 'https://github.com': terminal prompts disabled
</code>```

I've tried to look at the readthedocs project settings but I can't seem to find the right settings to modify to get the builds to work. The config. YAML was copied directly from the readthedocs template for Python projects.

```<code># .readthedocs.yml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details

# Required
version: 2

# Build documentation in the docs/ directory with Sphinx
sphinx:
  builder: html
  configuration: docs/conf.py
  fail_on_warning: false

# Build documentation with MkDocs
#mkdocs:
#  configuration: mkdocs.yml

# Optionally build your docs in additional formats such as PDF and ePub
formats: htmlzip

# Optionally set the version of Python and requirements required to build your docs
python:
   version: 3.6
   install:
      - requirements: docs/requirements.txt
      - requirements: requirements.txt
      - method: pip
   system_packages: true
</code>```

This is docs/conf.py.

```<code># Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath(os.pardir))

# -- Project information -----------------------------------------------------

project = '<project name>'
copyright = '2019, <author>'
author = '<author>'

# The full version, including alpha/beta/rc tags
release = '0.1.0'

# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'recommonmark',
    'sphinx.ext.autodoc',
    'sphinxcontrib.httpdomain',
    'sphinx.ext.intersphinx',
    'sphinx.ext.todo',
    'sphinx.ext.coverage',
    'sphinx.ext.viewcode',
    'sphinx.ext.githubpages'
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
source_suffix = ['.rst', '.md']

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}
</code>```

答:
This could happen because ReadTheDocs allows access to public repositories from its free membership.

However, for private GitHub repositories, we will have to use ReadtheDocs for Bussiness noted here

As of February 2020, the costs for each Plan are as under:

```<code>Plan:
 Advanced ($150 per month)

Plan Features:
Style your documentation to fit your company's brand
Support custom SSL certificates
Host documentation on your own domain
</code>```

And

Plan:   Basic ($50/month)

Plan Features:
      For hosting documentation for employees at your company

Hope this helps

Body:
I have set up and built Sphinx docs (2.1.2) for a Python 3.6 project which is currently in a private GitHub repository. I want to host the docs on readthedocs.org after releasing the project publicly, but at the moment the readthedocs builds are always failing with this error message

 git clone --no-single-branch --depth 50 https://github.com/<user name>/<repo name> .

Cloning into '.'...
fatal: could not read Username for 'https://github.com': terminal prompts disabled

I've tried to look at the readthedocs project settings but I can't seem to find the right settings to modify to get the builds to work. The config. YAML was copied directly from the readthedocs template for Python projects.

# .readthedocs.yml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details

# Required
version: 2

# Build documentation in the docs/ directory with Sphinx
sphinx:
  builder: html
  configuration: docs/conf.py
  fail_on_warning: false

# Build documentation with MkDocs
#mkdocs:
#  configuration: mkdocs.yml

# Optionally build your docs in additional formats such as PDF and ePub
formats: htmlzip

# Optionally set the version of Python and requirements required to build your docs
python:
   version: 3.6
   install:
      - requirements: docs/requirements.txt
      - requirements: requirements.txt
      - method: pip
   system_packages: true

This is docs/conf.py.

# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath(os.pardir))

# -- Project information -----------------------------------------------------

project = '<project name>'
copyright = '2019, <author>'
author = '<author>'

# The full version, including alpha/beta/rc tags
release = '0.1.0'

# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'recommonmark',
    'sphinx.ext.autodoc',
    'sphinxcontrib.httpdomain',
    'sphinx.ext.intersphinx',
    'sphinx.ext.todo',
    'sphinx.ext.coverage',
    'sphinx.ext.viewcode',
    'sphinx.ext.githubpages'
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
source_suffix = ['.rst', '.md']

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}

Body:
This could happen because ReadTheDocs allows access to public repositories from its free membership.

However, for private GitHub repositories, we will have to use ReadtheDocs for Bussiness noted here

As of February 2020, the costs for each Plan are as under:

Plan:
 Advanced ($150 per month)

Plan Features:
Style your documentation to fit your company's brand
Support custom SSL certificates
Host documentation on your own domain

And

Plan:   Basic ($50/month)

Plan Features:
      For hosting documentation for employees at your company

Hope this helps


问:
Unignore subdirectories of ignored directories in Git
Let's say I have ignored a directory, but I want to unignore specific subdirectories therein. So I have the setup:

```<code>/uploads/
/uploads/rubbish/
/uploads/rubbish/stuff/KEEP_ME/
/uploads/foo/
/uploads/foo/bar/lose/
</code>```

And I want to ignore everything but the KEEP_ME directory. I would hope the ignore would look something like:

```<code>/uploads/*
!/uploads/rubbish/stuff/KEEP_ME/
</code>```

But that's not working, and neither are several permutations on the same theme.

One that does work is

```<code>/uploads/**/**/**/
!/uploads/rubbish/stuff/KEEP_ME/
</code>```

But that feels a little restrictive and verbose?

答:
The solution presented as the most-upvoted answer is incorrect, and easily demonstrable as such.

Start with ignoring everything in uploads/*:

```<code>mkdir -p uploads/rubbish/stuff/KEEP_ME
touch uploads/a uploads/rubbish/a uploads/rubbish/stuff/a uploads/rubbish/stuff/KEEP_ME/a
echo '/uploads/*' >> .gitignore
git init
git add .
git commit -m "Initial commit"
</code>```

Now unignore the parent directory of the ignored stuff as above:

```<code>echo 'uploads/rubbish/stuff/KEEP_ME/' >> .gitignore
echo 'uploads/rubbish/stuff/KEEP_ME/*' >> .gitignore
git status -u
</code>```

Shows no untracked files.

In order to get it to work, you need to ignore all files under the uploads/ tree (uploads/**/*, not just the top level, uploads/*) and then add all parent directories of the tree you want to keep

```<code>echo '/uploads/**/*' > .gitignore
echo '!/uploads/rubbish/' >> .gitignore
echo '!/uploads/rubbish/stuff' >> .gitignore
echo '!/uploads/rubbish/stuff/KEEP_ME' >> .gitignore
echo '!/uploads/rubbish/stuff/KEEP_ME/*' >> .gitignore
git status -u
</code>```

Which gives:

```<code>On branch master
...
Untracked files:
  (use "git add <file>..." to include in what will be committed)
        uploads/rubbish/stuff/KEEP_ME/a
</code>```

If we had used uploads/* in the .gitignore above, then all the intermediate files would have been included as well, so for example uploads/rubbish/a would show up in the status command above.

Body:
Let's say I have ignored a directory, but I want to unignore specific subdirectories therein. So I have the setup:

/uploads/
/uploads/rubbish/
/uploads/rubbish/stuff/KEEP_ME/
/uploads/foo/
/uploads/foo/bar/lose/

And I want to ignore everything but the KEEP_ME directory. I would hope the ignore would look something like:

/uploads/*
!/uploads/rubbish/stuff/KEEP_ME/

But that's not working, and neither are several permutations on the same theme.

One that does work is

/uploads/**/**/**/
!/uploads/rubbish/stuff/KEEP_ME/

But that feels a little restrictive and verbose?

Body:
The solution presented as the most-upvoted answer is incorrect, and easily demonstrable as such.

Start with ignoring everything in uploads/*:

mkdir -p uploads/rubbish/stuff/KEEP_ME
touch uploads/a uploads/rubbish/a uploads/rubbish/stuff/a uploads/rubbish/stuff/KEEP_ME/a
echo '/uploads/*' >> .gitignore
git init
git add .
git commit -m "Initial commit"

Now unignore the parent directory of the ignored stuff as above:

echo 'uploads/rubbish/stuff/KEEP_ME/' >> .gitignore
echo 'uploads/rubbish/stuff/KEEP_ME/*' >> .gitignore
git status -u

Shows no untracked files.

In order to get it to work, you need to ignore all files under the uploads/ tree (uploads/**/*, not just the top level, uploads/*) and then add all parent directories of the tree you want to keep

echo '/uploads/**/*' > .gitignore
echo '!/uploads/rubbish/' >> .gitignore
echo '!/uploads/rubbish/stuff' >> .gitignore
echo '!/uploads/rubbish/stuff/KEEP_ME' >> .gitignore
echo '!/uploads/rubbish/stuff/KEEP_ME/*' >> .gitignore
git status -u

Which gives:

On branch master
...
Untracked files:
  (use "git add <file>..." to include in what will be committed)
        uploads/rubbish/stuff/KEEP_ME/a

If we had used uploads/* in the .gitignore above, then all the intermediate files would have been included as well, so for example uploads/rubbish/a would show up in the status command above.


问:
Dealing with an "Access to fetch blocked by CORS policy" exception in React app connecting to Azure Cosmos DB (SQL API)
I am trying to create a very simple React, front-end application that will connect to Azure Cosmos DB and allow the user to perform simple tasks like search the database. I am using the SQL API of CosmosDB, not MongoDB, and am having trouble connecting my application to CosmosDB. As of right now, it is just a simple webpage with a connect button that, when clicked, attempts to create a database if it doesn't exist and then create a container in that db. My code looks like this (with the endpoint and key left out intentionally):

```<code>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
const CosmosClient = require('@azure/cosmos').CosmosClient;

class App extends Component {

  constructor() {
    super();
    this.state = {
      client : new CosmosClient({
        endpoint: "my-endpoint",
        key: "my-primary-key"
      }),
      databaseID : "My-db-name",
      containerID : "My-db-container"
    };
    this.connect = this.connect.bind(this);
    this.init = this.init.bind(this);
  }

  connect() {
    this.init(err => {
      console.error(err);
    })
    .catch(err => {
      console.error(err);
      console.error(
        'Shutting down because there was an error setting up the database.'
      );
    });
  }

  async init() {
    const dbResponse = await this.state.client.databases.createIfNotExists({
        id: this.state.databaseID
    });
    const coResponse = await dbResponse.database.containers.createIfNotExists({
        id: this.state.containerID
    });
  }

  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
        </div>
        <button className="Connect-Button" onClick={this.connect}>
          Connect to Azure
        </button>
      </div>
    );
  }
}

export default App;
</code>```

When I click on the "Connect to Azure" button, I receive the following errors:

"Access to fetch at 'https://react-test-db.documents.azure.com/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."

Along with: "GET https://react-test-db.documents.azure.com/ net::ERR_FAILED" and "TypeError: Failed to fetch"

I have tried to enable CORS like suggested in https://medium.com/@alexishevia/using-cors-in-express-cac7e29b005b, however that didn't seem to do anything.

In the Microsoft Azure Portal, there is a CORS tab that allows you to add domains to make cross-origin calls to your DB. However, localhost:3000/ is an "invalid origin" and is not allowed. Does that have something to do with it? Or is there something wrong with my code?

答: Have you tried using your machine's IP address instead of localhost? If you have a UNIX like machine the IP address can be found from the terminal using ifconfig command.

Body:
I am trying to create a very simple React, front-end application that will connect to Azure Cosmos DB and allow the user to perform simple tasks like search the database. I am using the SQL API of CosmosDB, not MongoDB, and am having trouble connecting my application to CosmosDB. As of right now, it is just a simple webpage with a connect button that, when clicked, attempts to create a database if it doesn't exist and then create a container in that db. My code looks like this (with the endpoint and key left out intentionally):

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
const CosmosClient = require('@azure/cosmos').CosmosClient;

class App extends Component {

  constructor() {
    super();
    this.state = {
      client : new CosmosClient({
        endpoint: "my-endpoint",
        key: "my-primary-key"
      }),
      databaseID : "My-db-name",
      containerID : "My-db-container"
    };
    this.connect = this.connect.bind(this);
    this.init = this.init.bind(this);
  }

  connect() {
    this.init(err => {
      console.error(err);
    })
    .catch(err => {
      console.error(err);
      console.error(
        'Shutting down because there was an error setting up the database.'
      );
    });
  }

  async init() {
    const dbResponse = await this.state.client.databases.createIfNotExists({
        id: this.state.databaseID
    });
    const coResponse = await dbResponse.database.containers.createIfNotExists({
        id: this.state.containerID
    });
  }

  render() {
    return (

        <button className="Connect-Button" onClick={this.connect}>
          Connect to Azure
        </button>

    );
  }
}

export default App;

When I click on the "Connect to Azure" button, I receive the following errors:

"Access to fetch at 'https://react-test-db.documents.azure.com/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."

Along with: "GET https://react-test-db.documents.azure.com/ net::ERR_FAILED" and "TypeError: Failed to fetch"

I have tried to enable CORS like suggested in https://medium.com/@alexishevia/using-cors-in-express-cac7e29b005b, however that didn't seem to do anything.

In the Microsoft Azure Portal, there is a CORS tab that allows you to add domains to make cross-origin calls to your DB. However, localhost:3000/ is an "invalid origin" and is not allowed. Does that have something to do with it? Or is there something wrong with my code?


问:
jQuery Sortable Events - undefined parameters
i'm in litle trouble triing to obtain information about events fired by jQuery sortable.

I have this code working :

```<code>var sortable = $("#datatable-wrapper #example tbody").sortable({
        cursor: "move",
        tolerance: 'pointer',
});

sortable.bind( "sortout",function(e, ui) {
        for(i in e)
             alert("e."+i+" : " + e.i);
        for(i in ui)
             alert("ui."+i+" : " + ui.i);
        for(i in this)
             alert("this."+i+" : " + this.i);
        for(i in $(this))
             alert("$(this)."+i+" : " + $(this).i);
});
</code>```

The problem is : I always get something like :

```<code>e.SomeProp : undefined //same for ui, this, and $(this)
</code>```

It shows me the structure of these objects, but none of these propertys are defined. What did I do wrong ?

Thanks by advance.

答: Your loop puts the properties' name into the i variable as a string, but you're trying to access literally e.i, not the named property, and that IS undefined. Try e[i] to access the object property by its name.

Body:
i'm in litle trouble triing to obtain information about events fired by jQuery sortable.

I have this code working :

var sortable = $("#datatable-wrapper #example tbody").sortable({
        cursor: "move",
        tolerance: 'pointer',
});

sortable.bind( "sortout",function(e, ui) {
        for(i in e)
             alert("e."+i+" : " + e.i);
        for(i in ui)
             alert("ui."+i+" : " + ui.i);
        for(i in this)
             alert("this."+i+" : " + this.i);
        for(i in $(this))
             alert("$(this)."+i+" : " + $(this).i);
});

The problem is : I always get something like :

e.SomeProp : undefined //same for ui, this, and $(this)

It shows me the structure of these objects, but none of these propertys are defined. What did I do wrong ?

Thanks by advance.


问:
Why do I get "permission denied" in PHP when trying to rename a directory?
I chmod'ed the directory to 777, same with the directory contents. Still, I get a "permission denied" error. Does PHP throw this error if apache is not the group/owner, regardless of the file permissions? Here's the call that's failing:</p>

```<code>rename('/correct/path/to/dir/1', '/correct/path/to/dir/2');
</code>```

答:
You must change the permissions of the folder and the files contained in it recursively.
You need to do this from ssh as root user and then run the following command:

```<code>chown -R www-data:www-data /directory/path/to/apply/chown
</code>```

then you can execute the chown statement without any problems.

I found this way after researching, testing for several hours.

Remember that a folder or root owner file cannot be manipulated by another user (delete, rename, move, change properties), while root can do so above any user.

Best regards

OwnerDisplayName: Andrew Hedges

Body:
I chmod'ed the directory to 777, same with the directory contents. Still, I get a "permission denied" error. Does PHP throw this error if apache is not the group/owner, regardless of the file permissions? Here's the call that's failing:

rename('/correct/path/to/dir/1', '/correct/path/to/dir/2');

Body:
You must change the permissions of the folder and the files contained in it recursively.
You need to do this from ssh as root user and then run the following command:

chown -R www-data:www-data /directory/path/to/apply/chown

then you can execute the chown statement without any problems.

I found this way after researching, testing for several hours.

Remember that a folder or root owner file cannot be manipulated by another user (delete, rename, move, change properties), while root can do so above any user.

Best regards


问:
Can `pip install foo-package==1.0.0` download different code today than it did yesterday
I need to make sure that the package which was allowed for a secure system will remain static if installed again in the future.  Can a bad actor (the package owner) trick user into downloading insecure/unvetted source code?</p>

答: PyPI prohibits users from uploading a file with the same name.  So if the user uploads a package which has a wheel file that looks like foo-1.0.0-py2py3-none-any.whl they cannot update that file to contain other source code. However, what they can do is delete v1.0.0 from PyPI change the source code and then upload both: foo-1.0.0-py2-none-any.whl and foo-1.0.0-py3-none-any.whl effectively tricking the user into downloading a potentially malicious wheel.


问:
How do you unittest exceptions in Dart?
Consider a function that does some exception handling based on the arguments passed:

List range(start, stop) {
    if (start >= stop) {
      throw new ArgumentError("start must be less than stop");
    }
    // remainder of function
}
```

How do I test that the right kind of exception is raised?

答:
As a more elegant solution to @Shailen Tuli's proposal, if you want to expect an error with a specific message, you can use having.

In this situation, you are looking for something like this:

expect(
  () => range(5, 3),
  throwsA(
    isA<ArgumentError>().having(
      (error) => error.message,        // The feature you want to check.
      'message',                       // The description of the feature.
      'start must be less than stop',  // The error message.
    ),
  ),
);
```

Title: How do you unittest exceptions in Dart?

Body:
Consider a function that does some exception handling based on the arguments passed:

List range(start, stop) {
    if (start >= stop) {
      throw new ArgumentError("start must be less than stop");
    }
    // remainder of function
}

How do I test that the right kind of exception is raised?


问:
How can I stop displaying css animations upon loading linked pages with the same header/footer?
I have a few simple css animations on load up of the landing page for a site. I want to move my navbar and footer to a partial and link to it on each page, but I don't want those animations to play on any page but the landing page.

This is my first time messing with css animations, so I am wondering if there is a way to include the header and footer in a partial on all the linked pages without triggering the animation.

I could redo the header and footer in a partial with separate class names so that they don't correspond to the same css, but that will add a good amount of clutter that I would like to avoid.

答:
You have two choices

Create a separated CSS for animations and do not load it in any other page but your landing page.

If your animation classes are mixed with other CSS or you just want to keep them together with your main CSS, just create an exclusive class for your landing page body like "landing-with-animations" like this

```<code><body class="landing-with-animations">
</code>```

and then place your animations within this class in your CSS like

```<code>.landing-with-animations .animation1 {
/*rules here*/
}

.landing-with-animations .animation2{
/*rules here*/
}
</code>```

this way, your animations only work when they are within your landing page within its body with class "landing-with animations"

Body:
You have two choices

Create a separated CSS for animations and do not load it in any other page but your landing page.

If your animation classes are mixed with other CSS or you just want to keep them together with your main CSS, just create an exclusive class for your landing page body like "landing-with-animations" like this

<body class="landing-with-animations">

and then place your animations within this class in your CSS like

.landing-with-animations .animation1 {
/*rules here*/
}

.landing-with-animations .animation2{
/*rules here*/
}

this way, your animations only work when they are within your landing page within its body with class "landing-with animations"