问:
How do [ H | _ ] and [ _ | T ] in predicates work?
I am still learning Prolog and I came across this little snippet of code that I don't quite know if I have understood correctly.

Code:

% Takes the spiders friends and returns a list with persons who don't know each other.
getConspirators( [], Res, Res).

getConspirators( [H|T], CConspirators, Res):-
  append( [H|T], CConspirators, PK),
  knowsAtleastOne( PK),
  % Gets all the friends of the possible conspirator H.
  allFriends( H, PFriends),
  subtract( T, PFriends, Pprim),
  getConspirators( Pprim, [H|CConspirators], Res).

getConspirators( [_|T], CConspirators, Res) :-
  getConspirators( T, CConspirators, Res).

% Checks if any person Y or Y's friends know anybody in PK.
knowsAtleastOne( PK):-
    forall( person(Y), (memberchk(Y,PK) ; friendCons(Y,PK)) ).

% Checks if a person X's friends know any of the conspirators.
friendCons( X, Conspirators):-
    friend( X, Y),
    memberchk( Y, Conspirators),
    !.
```

(this is NOT the whole program, just a small snippet of it)

I am not sure if I have understood the getConspirators( [H|T], CConspirators, Res) :- and the getConspirators( [_|T], CConspirators, Res) :- parts of the
getConspirators predicate. They look almost the same! Now, I do know that the "_" symbol means "literally any value" (AKA Prolog doesn't care about what value it is). But how does Prolog know which case to pick when running through the code? My theory is that Prolog runs the getConspirators( [_|T], CConspirators, Res) :- case if and only if the getConspirators( [H|T], CConspirators, Res) :- case fails (returns false) somewhere along the way. Have I understood this correctly?

答:
There are three elements in play here: backtracking, unification and the list notation. I'll explain the three with a simpler example:

```<code>moon(europa).
moon(ganymede).

planet(jupiter).
planet(saturn).
</code>```

We know that Europa and Ganymede are two moons (of Jupiter) and that Jupiter and Saturn are planets. When we query what planets are known, we write:

```<code>?- planet(X).
X = jupiter ;  % type ; for the next answer
X = saturn.    % there's no more answer, hence .
</code>```

Unification happens when prolog looks for a rule head which fits to the query where the variables are substituted accordingly. For instance, there is no substitution that makes moon(X) = planet(Y) equal, but there is one for planet(jupiter) = planet(X), namely X=jupiter. That's how you obtain the first solution. For the second solution, Prolog needs to unifywith the second rule head, namely planet(saturn) = planet(X). Because this is done after the first option is completely enumerated, we call this backtracking.

Now we can focus on (linked) lists. A list is either empty ([]) or it has a first element X prepended to a tail list Xs ([X|Xs]). Prolog has also a nicer notation for the list [X | [Y | [] ]], namely [X,Y]. Internally they are the same. When we now want to collect a list of astral objects, we can formulate the following three rules:

```<code>astral_objects([]).        % The empty list is a list of astral objects.

astral_objects([X|Xs]) :-  % The list [X | Xs] is a list of astral objects if...
    moon(X),               % ... its first element X is a moon
    astral_objects(Xs).    % ... and the remaining list Xs is a list of astral objects

astral_object([X|Xs]) :-   % Likewise for planets
    planet(X),
    astral_objects(Xs).
</code>```

When we formulate query for a two-element list, we get all combinations of objects:

```<code>?- astral_object([A,B]).
A = B, B = europa ;
A = europa,
B = ganymede ;
A = europa,
B = jupiter ;
A = europa,
B = saturn ;
A = ganymede,
B = europa ;
A = B, B = ganymede ;
A = ganymede,
B = jupiter
%...
</code>```

By unification, only rules 2 and 3 apply. In both cases we have astral_objects([X|Xs]) = astral_objects([A,B]). Remember that [A,B] is shorthand for [A|[B]] and there for X=A and Xs=[B]. The first rule of the body will unify X with the corresponding moon/planet and the recursion step describes the tail. Again, we unify astral_objects([X|Xs]) = astral_objects([B]), leading to X=B and Xs = []. Now the recursion step will only match the terminal case of the empty list and we have fully explored this path.

Now what happens if we look for an arbitrary list of astral objects?

```<code>?- astral_object(Xs).
Xs = [] ;
Xs = [europa] ;
Xs = [europa, europa] ;
Xs = [europa, europa, europa] ;
Xs = [europa, europa, europa, europa] ;
Xs = [europa, europa, europa, europa, europa]
%... does not terminate
</code>```

The head astral_objects(Xs) matches all three bodies. After returning the substitution for the terminal case, it descends into the first rule over and over again. Since the length of the list is unrestricted, there are an infinite number of solutions to find before the third rule is ever tried. To avoid this, you can fairly enumerate the lists before you try to make them satisfy the predicate:

```<code>?- length(Xs,_), astral_object(Xs).
Xs = [] ;
Xs = [europa] ;
Xs = [ganymede] ;
Xs = [jupiter] ;
Xs = [saturn] ;
Xs = [europa, europa] ;
Xs = [europa, ganymede] ;
Xs = [europa, jupiter] ;
Xs = [europa, saturn] ;
Xs = [ganymede, europa]
%...
</code>```

It still does not terminate, but you see the lists in ascending length and therefore the variety.

Body:
I am still learning Prolog and I came across this little snippet of code that I don't quite know if I have understood correctly.

Code:

% Takes the spiders friends and returns a list with persons who don't know each other.
getConspirators( [], Res, Res).

getConspirators( [H|T], CConspirators, Res):-
  append( [H|T], CConspirators, PK),
  knowsAtleastOne( PK),
  % Gets all the friends of the possible conspirator H.
  allFriends( H, PFriends),
  subtract( T, PFriends, Pprim),
  getConspirators( Pprim, [H|CConspirators], Res).

getConspirators( [_|T], CConspirators, Res) :-
  getConspirators( T, CConspirators, Res).

% Checks if any person Y or Y's friends know anybody in PK.
knowsAtleastOne( PK):-
    forall( person(Y), (memberchk(Y,PK) ; friendCons(Y,PK)) ).

% Checks if a person X's friends know any of the conspirators.
friendCons( X, Conspirators):-
    friend( X, Y),
    memberchk( Y, Conspirators),
    !.

(this is NOT the whole program, just a small snippet of it)

I am not sure if I have understood the getConspirators( [H|T], CConspirators, Res) :- and the getConspirators( [_|T], CConspirators, Res) :- parts of the
getConspirators predicate. They look almost the same! Now, I do know that the "_" symbol means "literally any value" (AKA Prolog doesn't care about what value it is). But how does Prolog know which case to pick when running through the code? My theory is that Prolog runs the getConspirators( [_|T], CConspirators, Res) :- case if and only if the getConspirators( [H|T], CConspirators, Res) :- case fails (returns false) somewhere along the way. Have I understood this correctly?

Body:
There are three elements in play here: backtracking, unification and the list notation. I'll explain the three with a simpler example:

moon(europa).
moon(ganymede).

planet(jupiter).
planet(saturn).

We know that Europa and Ganymede are two moons (of Jupiter) and that Jupiter and Saturn are planets. When we query what planets are known, we write:

?- planet(X).
X = jupiter ;  % type ; for the next answer
X = saturn.    % there's no more answer, hence .

Unification happens when prolog looks for a rule head which fits to the query where the variables are substituted accordingly. For instance, there is no substitution that makes moon(X) = planet(Y) equal, but there is one for planet(jupiter) = planet(X), namely X=jupiter. That's how you obtain the first solution. For the second solution, Prolog needs to unifywith the second rule head, namely planet(saturn) = planet(X). Because this is done after the first option is completely enumerated, we call this backtracking.

Now we can focus on (linked) lists. A list is either empty ([]) or it has a first element X prepended to a tail list Xs ([X|Xs]). Prolog has also a nicer notation for the list [X | [Y | [] ]], namely [X,Y]. Internally they are the same. When we now want to collect a list of astral objects, we can formulate the following three rules:

astral_objects([]).        % The empty list is a list of astral objects.

astral_objects([X|Xs]) :-  % The list [X | Xs] is a list of astral objects if...
    moon(X),               % ... its first element X is a moon
    astral_objects(Xs).    % ... and the remaining list Xs is a list of astral objects

astral_object([X|Xs]) :-   % Likewise for planets
    planet(X),
    astral_objects(Xs).

When we formulate query for a two-element list, we get all combinations of objects:

?- astral_object([A,B]).
A = B, B = europa ;
A = europa,
B = ganymede ;
A = europa,
B = jupiter ;
A = europa,
B = saturn ;
A = ganymede,
B = europa ;
A = B, B = ganymede ;
A = ganymede,
B = jupiter
%...

By unification, only rules 2 and 3 apply. In both cases we have astral_objects([X|Xs]) = astral_objects([A,B]). Remember that [A,B] is shorthand for [A|[B]] and there for X=A and Xs=[B]. The first rule of the body will unify X with the corresponding moon/planet and the recursion step describes the tail. Again, we unify astral_objects([X|Xs]) = astral_objects([B]), leading to X=B and Xs = []. Now the recursion step will only match the terminal case of the empty list and we have fully explored this path.

Now what happens if we look for an arbitrary list of astral objects?

?- astral_object(Xs).
Xs = [] ;
Xs = [europa] ;
Xs = [europa, europa] ;
Xs = [europa, europa, europa] ;
Xs = [europa, europa, europa, europa] ;
Xs = [europa, europa, europa, europa, europa]
%... does not terminate

The head astral_objects(Xs) matches all three bodies. After returning the substitution for the terminal case, it descends into the first rule over and over again. Since the length of the list is unrestricted, there are an infinite number of solutions to find before the third rule is ever tried. To avoid this, you can fairly enumerate the lists before you try to make them satisfy the predicate:

?- length(Xs,_), astral_object(Xs).
Xs = [] ;
Xs = [europa] ;
Xs = [ganymede] ;
Xs = [jupiter] ;
Xs = [saturn] ;
Xs = [europa, europa] ;
Xs = [europa, ganymede] ;
Xs = [europa, jupiter] ;
Xs = [europa, saturn] ;
Xs = [ganymede, europa]
%...

It still does not terminate, but you see the lists in ascending length and therefore the variety.


来源: stackexchange

问:
NLog - Parameters not passed to query when writing to database
I'm pretty new to NLog so please forgive my basic question.

I've inherited a Winforms application written by some contractors, I'm mainly a database developer but I've managed to do some development of the application but I sometimes struggle with tracking down error messages encountered by users, therefore I'm attempting to retrofit logging into the application via NLog, I first encountered the issue in NLog 4.4.5 and I've since updated to 4.4.12 and that hasn't solved the problem. I've verified that NLog is catching the errors correctly as it will output to a text file but when I try to direct it to a database output I can't get it to work.

This is my database table:

My problem is that I can only get errors written to the database only if I don't pass any parameters to the insert statement (which is pretty useless). That is to say that the following in my NLog.config file works:

```<code><target name="database" xsi:type="Database">
  <commandText>INSERT INTO [tblException] (DbVersionID, ExceptionDateTime) SELECT MAX(DbVersionID), GETDATE() FROM tblDbVersion</commandText>

  <dbProvider>System.Data.SqlServerCe.4.0</dbProvider>
  <connectionString>Data Source=${basedir}\Database.sdf</connectionString>
</target>
</code>```

But this doesnt':

```<code><target name="database" xsi:type="Database">
   <commandText>INSERT INTO [tblException] (DbVersionID, ExceptionDateTime, Message) SELECT MAX(DbVersionID), GETDATE(), @message FROM tblDbVersion</commandText>

   <parameter name="@message" layout="${message}" />

   <dbProvider>System.Data.SqlServerCe.4.0</dbProvider>
   <connectionString>Data Source=${basedir}\Database.sdf</connectionString>
</target>
</code>```

I've enabled internal logging and the following is what I get:

```<code>2017-11-28 11:26:45.8063 Trace Executing Text: INSERT INTO [tblException] (DbVersionID, ExceptionDateTime, Message) SELECT MAX(DbVersionID), GETDATE(), @Message FROM tblDbVersion
2017-11-28 11:26:45.8063 Trace   Parameter: '@message' = 'Test Error Message' (String)
2017-11-28 11:26:45.8063 Error Error when writing to database. Exception: System.Data.SqlServerCe.SqlCeException (0x80004005): A parameter is not allowed in this location. Ensure that the '@' sign is in a valid location or that parameters are valid at all in this SQL statement.
   at System.Data.SqlServerCe.SqlCeCommand.ProcessResults(Int32 hr)
   at System.Data.SqlServerCe.SqlCeCommand.CompileQueryPlan()
   at System.Data.SqlServerCe.SqlCeCommand.ExecuteCommand(CommandBehavior behavior, String method, ResultSetOptions options)
   at System.Data.SqlServerCe.SqlCeCommand.ExecuteNonQuery()
   at NLog.Targets.DatabaseTarget.WriteEventToDatabase(LogEventInfo logEvent)
   at NLog.Targets.DatabaseTarget.Write(LogEventInfo logEvent)
</code>```

It appears that the parameter isn't getting replaced in the query before it's being run. I tried adding single quotes in the command text just in case that would help but it just resulted in the literal string '@message' being inserted into the database field.

I can't see anything that I've done differently to the examples, so any help would be appreciated.

Regards,

Alex

答:
As per the comment from @pmcilreavy

Have you tried temporarily removing the MAX and replacing with a literal and changing to INSERT INTO .. (blah) VALUES (blah, @Message); SqlCe has quite a few limitations and quirks compared to Sql Server so might be worth simplifying things where possible.

The issue appears to be that SQLCE doesn't support parameters in the select part of a select statement.

ContentLicense: CC BY-SA 3.0

Body:
I'm pretty new to NLog so please forgive my basic question.

I've inherited a Winforms application written by some contractors, I'm mainly a database developer but I've managed to do some development of the application but I sometimes struggle with tracking down error messages encountered by users, therefore I'm attempting to retrofit logging into the application via NLog, I first encountered the issue in NLog 4.4.5 and I've since updated to 4.4.12 and that hasn't solved the problem. I've verified that NLog is catching the errors correctly as it will output to a text file but when I try to direct it to a database output I can't get it to work.

This is my database table:

My problem is that I can only get errors written to the database only if I don't pass any parameters to the insert statement (which is pretty useless). That is to say that the following in my NLog.config file works:

<target name="database" xsi:type="Database">
  <commandText>INSERT INTO [tblException] (DbVersionID, ExceptionDateTime) SELECT MAX(DbVersionID), GETDATE() FROM tblDbVersion</commandText>

  <dbProvider>System.Data.SqlServerCe.4.0</dbProvider>
  <connectionString>Data Source=${basedir}\Database.sdf</connectionString>
</target>

But this doesnt':

<target name="database" xsi:type="Database">
   <commandText>INSERT INTO [tblException] (DbVersionID, ExceptionDateTime, Message) SELECT MAX(DbVersionID), GETDATE(), @message FROM tblDbVersion</commandText>

   <parameter name="@message" layout="${message}" />

   <dbProvider>System.Data.SqlServerCe.4.0</dbProvider>
   <connectionString>Data Source=${basedir}\Database.sdf</connectionString>
</target>

I've enabled internal logging and the following is what I get:

2017-11-28 11:26:45.8063 Trace Executing Text: INSERT INTO [tblException] (DbVersionID, ExceptionDateTime, Message) SELECT MAX(DbVersionID), GETDATE(), @Message FROM tblDbVersion
2017-11-28 11:26:45.8063 Trace   Parameter: '@message' = 'Test Error Message' (String)
2017-11-28 11:26:45.8063 Error Error when writing to database. Exception: System.Data.SqlServerCe.SqlCeException (0x80004005): A parameter is not allowed in this location. Ensure that the '@' sign is in a valid location or that parameters are valid at all in this SQL statement.
   at System.Data.SqlServerCe.SqlCeCommand.ProcessResults(Int32 hr)
   at System.Data.SqlServerCe.SqlCeCommand.CompileQueryPlan()
   at System.Data.SqlServerCe.SqlCeCommand.ExecuteCommand(CommandBehavior behavior, String method, ResultSetOptions options)
   at System.Data.SqlServerCe.SqlCeCommand.ExecuteNonQuery()
   at NLog.Targets.DatabaseTarget.WriteEventToDatabase(LogEventInfo logEvent)
   at NLog.Targets.DatabaseTarget.Write(LogEventInfo logEvent)

It appears that the parameter isn't getting replaced in the query before it's being run. I tried adding single quotes in the command text just in case that would help but it just resulted in the literal string '@message' being inserted into the database field.

I can't see anything that I've done differently to the examples, so any help would be appreciated.

Regards,

Alex


问:
Selecting meta tags with Selenium
I want to extract data from a meta tag but the tag is as follows

```<code><meta property="og:description" content="blah"/>
</code>```

Since there is no id/class/etc. I can't use

```<code>driver.FindElement(By.[id/class/etc.]);
</code>```

This meta tag has a unique property and content so I am wondering if there is any better way to locate and extract the content than selecting all "meta" tags and iterating through them.

答:
You can use this xpaths

```<code>driver.FindElement(By.XPath("//meta[contains(@property,'og:description']"));
</code>```

or

```<code>driver.FindElement(By.XPath("//meta[contains(@property,'og:description') and contains(@content,'blah')]"));
</code>```

Title: Selecting meta tags with Selenium

Body:
I want to extract data from a meta tag but the tag is as follows

<meta property="og:description" content="blah"/>

Since there is no id/class/etc. I can't use

driver.FindElement(By.[id/class/etc.]);

This meta tag has a unique property and content so I am wondering if there is any better way to locate and extract the content than selecting all "meta" tags and iterating through them.

Body:
You can use this xpaths

driver.FindElement(By.XPath("//meta[contains(@property,'og:description']"));

or

driver.FindElement(By.XPath("//meta[contains(@property,'og:description') and contains(@content,'blah')]"));


问:
How to get access to uiTableViewCell which are not selected in Swift 3?
So basically I know that I can get all the selected cells using "selectedIndexPathRows". But I want to change behavior of cells which are not selected. Also I want to know which cells are not selected on didSelect or didDeselect .
Basically, what I want to achieve is to get all the cells which are not selected and set their alpha to 0.5 and set 1.0 of only selected cells, how can I do that?
Any help would be appreciated.

答:
I'm giving hint for achieve that

Take one array, size of array = total row of table

Set initial value 0 at all index of array

in didSelectRowAtIndexPath method first check, array has 0 value then change value 0 to 1 at specific index of array.

Now array has 0 value that means this rows are not selected.


问:
Finfo_file on uploaded file to determine mime-type
Im trying to determine the mime-type of an uploaded file, i want to use fileinfo(), this is what ive been trying, it isnt working:

```<code>$uploadedfile = $_FILES['soup']['tmp_name'];
if(isset($uploadedfile))
{
    $uploadedname = $_FILES['soup']['name'];
    $file=$uploadedsong;
    $file.=$uploadedname;
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $file);
</code>```

Unfortunately the finfo_file doesnt seem to be running, Im assuming i have the following $file set incorrectly for this, is there a way i can do this properly with a newly uploaded file using $_FILE like this? or am i going at this problem the completely improper way. Using a file i have pre-set in another directly, and setting $file="folder/file.doc" works properly.

答:
I use the finfo() buffer() function as well as file_get_contents() from the php platform as below

```<code>$finfo = new finfo(FILEINFO_MIME);
$mimetype = $finfo->buffer(file_get_contents($filename)); #gives you mime type
</code>```

you need to be on php 5.3 or higher and make sure you have the finfo() extension installed. for linux extension=fileinfo. and in windows: php_fileinfo.dll

you can have an array of accepted mime types and then check if it exists in that array

```<code>$acceptedMime = [];
if(in_array($mimetype, $acceptedMime, true) === true){
  #mime type is valid. Proceed!
}
</code>```

Another alternative to avoid having to check mime types would be to store file uploads completely out of the document root folder.

Body:
Im trying to determine the mime-type of an uploaded file, i want to use fileinfo(), this is what ive been trying, it isnt working:

$uploadedfile = $_FILES['soup']['tmp_name'];
if(isset($uploadedfile))
{
    $uploadedname = $_FILES['soup']['name'];
    $file=$uploadedsong;
    $file.=$uploadedname;
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $file);

Unfortunately the finfo_file doesnt seem to be running, Im assuming i have the following $file set incorrectly for this, is there a way i can do this properly with a newly uploaded file using $_FILE like this? or am i going at this problem the completely improper way. Using a file i have pre-set in another directly, and setting $file="folder/file.doc" works properly.

Body:
I use the finfo() buffer() function as well as file_get_contents() from the php platform as below

$finfo = new finfo(FILEINFO_MIME);
$mimetype = $finfo->buffer(file_get_contents($filename)); #gives you mime type

you need to be on php 5.3 or higher and make sure you have the finfo() extension installed. for linux extension=fileinfo. and in windows: php_fileinfo.dll

you can have an array of accepted mime types and then check if it exists in that array

$acceptedMime = [];
if(in_array($mimetype, $acceptedMime, true) === true){
  #mime type is valid. Proceed!
}

Another alternative to avoid having to check mime types would be to store file uploads completely out of the document root folder.


问:
Django TemplateDoesNotExist in production server when it works in development
I get the following error. It's ONLY IN PRODUCTION where I deploy Django application using apache + mod_wsgi. IT WORKS PERFECTLY IN DEVELOPMENT server(my computer):

```<code>TemplateDoesNotExist at /
base.html
</code>```

postmortem. as you can see only one of my two folders from settings are being searched:

```<code>Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:
/home/bot_frontend/horses/templates/base.html (File does not exist)
/usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/base.html (File does not exist)
/usr/local/lib/python2.7/dist-packages/django/contrib/auth/templates/base.html (File does not exist)
/home/virtualenvs/bot_frontend/lib/python2.7/site-packages/django_extensions/templates/base.html (File does not exist)
</code>```

Here are my settings. The base.html template is in "templates" folder.:

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, "templates"),
            os.path.join(BASE_DIR, "horses/templates")
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
</code>```

Here I confirm that this template actually exists:

```<code>>>> from django.template.loader import get_template
>>> get_template("base.html")
<django.template.backends.django.Template object at 0x7f6af68d38d0>
</code>```

As you can see only one folder out of two in my template dirs are being searched while in development server it works just fine. Any ideas why this could be ? Is it possible it's some kind of permissions issue.

答:
Adding the second entry for DIRS in settings.py fixed this issue for me.</p>

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],'
        'DIRS': [BASE_DIR + "/templates", ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
</code>```

Body:
I get the following error. It's ONLY IN PRODUCTION where I deploy Django application using apache + mod_wsgi. IT WORKS PERFECTLY IN DEVELOPMENT server(my computer):

TemplateDoesNotExist at /
base.html

postmortem. as you can see only one of my two folders from settings are being searched:

Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:
/home/bot_frontend/horses/templates/base.html (File does not exist)
/usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/base.html (File does not exist)
/usr/local/lib/python2.7/dist-packages/django/contrib/auth/templates/base.html (File does not exist)
/home/virtualenvs/bot_frontend/lib/python2.7/site-packages/django_extensions/templates/base.html (File does not exist)

Here are my settings. The base.html template is in "templates" folder.:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, "templates"),
            os.path.join(BASE_DIR, "horses/templates")
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Here I confirm that this template actually exists:

>>> from django.template.loader import get_template
>>> get_template("base.html")
<django.template.backends.django.Template object at 0x7f6af68d38d0>

As you can see only one folder out of two in my template dirs are being searched while in development server it works just fine. Any ideas why this could be ? Is it possible it's some kind of permissions issue.

Body:
Adding the second entry for DIRS in settings.py fixed this issue for me.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],'
        'DIRS': [BASE_DIR + "/templates", ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [


问:
gmaven is not generating jar file for groovy code
I am writing my groovy code in maven using GMaven plugin. when I do mvn clean install it is showing build success but when I checked my target folder it is not generating any jar for me. I am refering this atlassian link in that

```<code><plugins>
  <plugin>
 <executions>
      <execution>
        <goals>
          <goal>generateStubs</goal>
          <goal>compile</goal>
          <goal>generateTestStubs</goal>
          <goal>testCompile</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
</plugins>
</code>```

but for this I am getting pom error on execution. please help me out here

Below is my pom file

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.myproject</groupId>
    <artifactId>mydata</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>mydata</name>
    <url>http://maven.apache.orgurl>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
         <gmaven.version>1.5</gmaven.version>
    <groovy.version>2.1.8</groovy.version>
    </properties>

<dependencies>

        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.11</version>
        </dependency>

</dependencies>
<build>
<!-- <pluginManagement> -->
<plugins>
   <plugin>
            <groupId>org.codehaus.gmaven</groupId>
            <artifactId>gmaven-plugin</artifactId>
            <version>${gmaven.version}</version>
            <configuration>
                <providerSelection>2.0</providerSelection>
            </configuration>
            <dependencies>

                <dependency>
                    <groupId>org.codehaus.gmaven.runtime</groupId>
                    <artifactId>gmaven-runtime-2.0</artifactId>
                    <version>${gmaven.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.codehaus.groovy</groupId>
                    <artifactId>groovy-all</artifactId>
                    <version>${groovy.version}</version>
                </dependency>
            </dependencies>
           <!--  <executions>
                <execution>
                    <goals>
                        <goal>generateStubs</goal>
                        <goal>compile</goal>
                        <goal>generateTestStubs</goal>
                        <goal>testCompile</goal>
                    </goals>
                </execution>
            </executions> -->
        </plugin>
        </plugins>
<!--         </pluginManagement> -->
        </build>

</project>
</code>```

UPDATE 1:

I am able to see the jar but it does not have my groovy code

答:
Can you please try the following:

```<code>  <plugin>
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.5</version>
    <executions>
      <execution>
        <goals>
          <goal>addSources</goal>
          <goal>compile</goal>
        </goals>
      </execution>
    </executions>
    <configuration>
      <sources>
        <source>
          <directory>${project.basedir}/src</directory>
          <includes>
            <include>**/*.groovy</include>
          </includes>
        </source>
      </sources>
    </configuration>
  </plugin>
</code>```

Actually that's what I'm using and jar is correctly generated

PS: Make sure that source.directory points to where your .groovy files exist

Body:
I am writing my groovy code in maven using GMaven plugin. when I do mvn clean install it is showing build success but when I checked my target folder it is not generating any jar for me. I am refering this atlassian link in that

<plugins>
  <plugin>
 <executions>
      <execution>
        <goals>
          <goal>generateStubs</goal>
          <goal>compile</goal>
          <goal>generateTestStubs</goal>
          <goal>testCompile</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
</plugins>

but for this I am getting pom error on execution. please help me out here

Below is my pom file

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.myproject</groupId>
    <artifactId>mydata</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>mydata</name>
    <url>http://maven.apache.orgurl>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
         <gmaven.version>1.5</gmaven.version>
    <groovy.version>2.1.8</groovy.version>
    </properties>

<dependencies>

        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.11</version>
        </dependency>

</dependencies>
<build>

<plugins>
   <plugin>
            <groupId>org.codehaus.gmaven</groupId>
            <artifactId>gmaven-plugin</artifactId>
            <version>${gmaven.version}</version>
            <configuration>
                <providerSelection>2.0</providerSelection>
            </configuration>
            <dependencies>

                <dependency>
                    <groupId>org.codehaus.gmaven.runtime</groupId>
                    <artifactId>gmaven-runtime-2.0</artifactId>
                    <version>${gmaven.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.codehaus.groovy</groupId>
                    <artifactId>groovy-all</artifactId>
                    <version>${groovy.version}</version>
                </dependency>
            </dependencies>

        </plugin>
        </plugins>

        </build>

</project>

UPDATE 1:

I am able to see the jar but it does not have my groovy code

Body:
Can you please try the following:

  <plugin>
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.5</version>
    <executions>
      <execution>
        <goals>
          <goal>addSources</goal>
          <goal>compile</goal>
        </goals>
      </execution>
    </executions>
    <configuration>
      <sources>
        <source>
          <directory>${project.basedir}/src</directory>
          <includes>
            <include>**/*.groovy</include>
          </includes>
        </source>
      </sources>
    </configuration>
  </plugin>

Actually that's what I'm using and jar is correctly generated

PS: Make sure that source.directory points to where your .groovy files exist


问:
intercept mouse events when creating a custom QGraphicsItem
I am using a standard QGraphicsView and QGraphicsScene, but I have subclassed a QGraphicsPixmapItem to my own ImagePixmapItem for the purposes of being able to use the mouse events on the ImagePixmapItem.

What do I need to do to be able to capture those events? I have overridden a couple of functions like so:

```<code>   void ImagePixmapItem::mousePressEvent(QGraphicsSceneMouseEvent *event){

       qDebug("hello");

   }

void ImagePixmapItem::wheelEvent ( QGraphicsSceneWheelEvent * event ){
    qDebug("Print this line if catch a wheelEvent");//this is never printing

}
</code>```

However, neither of those qDebug statements ever print to console. Do I need to change anything else about my scene or graphicsview? In the constructor for the ImagePixmapItem, i did add a couple of things:

```<code>setAcceptHoverEvents(true);
setFlag(QGraphicsItem::ItemIsSelectable,true);
</code>```

But it has done no good.

答:
You can use event filters.

http://cartan.cas.suffolk.edu/qtdocs/eventsandfilters.html

I would also add that for your original example, be sure to enable mouse tracking on the widgets in question.

ContentLicense: CC BY-SA 2.5

Body:
I am using a standard QGraphicsView and QGraphicsScene, but I have subclassed a QGraphicsPixmapItem to my own ImagePixmapItem for the purposes of being able to use the mouse events on the ImagePixmapItem.

What do I need to do to be able to capture those events? I have overridden a couple of functions like so:

   void ImagePixmapItem::mousePressEvent(QGraphicsSceneMouseEvent *event){

       qDebug("hello");

   }

void ImagePixmapItem::wheelEvent ( QGraphicsSceneWheelEvent * event ){
    qDebug("Print this line if catch a wheelEvent");//this is never printing

}

However, neither of those qDebug statements ever print to console. Do I need to change anything else about my scene or graphicsview? In the constructor for the ImagePixmapItem, i did add a couple of things:

setAcceptHoverEvents(true);
setFlag(QGraphicsItem::ItemIsSelectable,true);

But it has done no good.


问:
VSTS build fails but portal shows successful deployment
Sorry, less a code issue but a process issue in deploying through Microsoft VSTS. I'm deploying an ARM template via a VSTS build definition and it failed (complaining the storage account was not in the same RG as the VM ).. BUT in the azure portal against the RG it shows a successful deployment and the resources deployed as expected.

What would cause VSTS to report an issue this way? Obvious issue is my deployment technically fails as a VSTS job despite being fine in Azure.

答: with no changes is stopped erroring so i'm guessing something on the azure side. Thanks anyway</p>

ContentLicense: CC BY-SA 4.0


问:
I can't fetch data from the db with a Html.DropDownListFor, in MVC 4 (or 5)
I have read some pages regarding DDls, but I can't get my DDLF (DropDownListFor) to work. I have a model, and a db, but I don't know how I can in the view show one DDLF.

What I get to work, is this code:

```<code>@foreach (var item in Model)
{
@Html.DropDownListFor(m => item.Id,
    new SelectList(ViewBag.SjukhusDropDownList),
    "Choose something")
}
</code>```

But then I get several DDLs. And I don't know how to insert data into them, so the data to the user will get fetched from the db. Like sending an id with something to the action, to do something with it. But here, I can only click on anything in the list, but of course, nothing will happen since I haven't bound any data to any option in that select list.

答:
Here's an example for DropDownListFor in MVC 4

In the model create two properties, one for the list itself and one for identifying the list entries. In this example the vu-number identifies a merchant:

```<code>public class MyModel
{
    [Display(Name = "VU")]
    public string vu{ get; set; }
    public List<SelectListItem> merchantList{ get; set; }
}
</code>```

Initialize and load model data in the Http GET method of the controller:

```<code>public ActionResult ShowMerchants()
{
     MyModel model = new MyModel();
     model.merchantList = GetMerchants();
     model.vu = model.merchantList[0].Value;
     return View(model);
}
</code>```

Create the list items using some rows from database. I.e. you can use TableAdapter and DataTable to achieve it:

```<code>private List<SelectListItem> GetMerchants()
{
    List<SelectListItem> merchantList = new List<SelectListItem>();
    MyDataSet.viewVUDataTable myDataTable = new MyDataSet.viewVUDataTable();
    MyDataTableAdapters.VUListTableAdapter myTableAdapter = new MyDataTableAdapters.VUListTableAdapter();
    myTableAdapter.Fill(myDataTable);
    // iterate over rows in datatable
    for(int i=0; i< myDataTable.Rows.Count; i++)
    {
         // Text is shown in the dropdownlist
         // Value is used to identify the selected item
         merchantList.Add(
             new SelectListItem { Text = myDataTable[i].text, Value = myDataTable[i].vu});
    }
    return merchantList;
}
</code>```

and in the view:

```<code>@Html.DropDownListFor(
    model => model.vu,
    Model.merchantList,
    new { @class = "form-control" })
</code>```

Body:
I have read some pages regarding DDls, but I can't get my DDLF (DropDownListFor) to work. I have a model, and a db, but I don't know how I can in the view show one DDLF.

What I get to work, is this code:

@foreach (var item in Model)
{
@Html.DropDownListFor(m => item.Id,
    new SelectList(ViewBag.SjukhusDropDownList),
    "Choose something")
}

But then I get several DDLs. And I don't know how to insert data into them, so the data to the user will get fetched from the db. Like sending an id with something to the action, to do something with it. But here, I can only click on anything in the list, but of course, nothing will happen since I haven't bound any data to any option in that select list.

Body:
Here's an example for DropDownListFor in MVC 4

In the model create two properties, one for the list itself and one for identifying the list entries. In this example the vu-number identifies a merchant:

public class MyModel
{
    [Display(Name = "VU")]
    public string vu{ get; set; }
    public List<SelectListItem> merchantList{ get; set; }
}

Initialize and load model data in the Http GET method of the controller:

public ActionResult ShowMerchants()
{
     MyModel model = new MyModel();
     model.merchantList = GetMerchants();
     model.vu = model.merchantList[0].Value;
     return View(model);
}

Create the list items using some rows from database. I.e. you can use TableAdapter and DataTable to achieve it:

private List<SelectListItem> GetMerchants()
{
    List<SelectListItem> merchantList = new List<SelectListItem>();
    MyDataSet.viewVUDataTable myDataTable = new MyDataSet.viewVUDataTable();
    MyDataTableAdapters.VUListTableAdapter myTableAdapter = new MyDataTableAdapters.VUListTableAdapter();
    myTableAdapter.Fill(myDataTable);
    // iterate over rows in datatable
    for(int i=0; i< myDataTable.Rows.Count; i++)
    {
         // Text is shown in the dropdownlist
         // Value is used to identify the selected item
         merchantList.Add(
             new SelectListItem { Text = myDataTable[i].text, Value = myDataTable[i].vu});
    }
    return merchantList;
}

and in the view:

@Html.DropDownListFor(
    model => model.vu,
    Model.merchantList,
    new { @class = "form-control" })


问:
Async/Await Class Constructor
At the moment, I'm attempting to use async/await within a class constructor function.  This is so that I can get a custom e-mail tag for an Electron project I'm working on.

```<code>customElements.define('e-mail', class extends HTMLElement {
  async constructor() {
    super()

    let uid = this.getAttribute('data-uid')
    let message = await grabUID(uid)

    const shadowRoot = this.attachShadow({mode: 'open'})
    shadowRoot.innerHTML = `
      <div id="email">A random email message has appeared. ${message}</div>
    `
  }
})
</code>```

At the moment however, the project does not work, with the following error:

```<code>Class constructor may not be an async method
</code>```

Is there a way to circumvent this so that I can use async/await within this?  Instead of requiring callbacks or .then()?

答:
You should add then function to instance. Promise will recognize it as a thenable object with Promise.resolve automatically

```<code>const asyncSymbol = Symbol();
class MyClass {
    constructor() {
        this.asyncData = null
    }
    then(resolve, reject) {
        return (this[asyncSymbol] = this[asyncSymbol] || new Promise((innerResolve, innerReject) => {
            this.asyncData = { a: 1 }
            setTimeout(() => innerResolve(this.asyncData), 3000)
        })).then(resolve, reject)
    }
}

async function wait() {
    const asyncData = await new MyClass();
    alert('run 3s later')
    alert(asyncData.a)
}
</code>```

Title: Async/Await Class Constructor

Body:
At the moment, I'm attempting to use async/await within a class constructor function.  This is so that I can get a custom e-mail tag for an Electron project I'm working on.

customElements.define('e-mail', class extends HTMLElement {
  async constructor() {
    super()

    let uid = this.getAttribute('data-uid')
    let message = await grabUID(uid)

    const shadowRoot = this.attachShadow({mode: 'open'})
    shadowRoot.innerHTML = `

A random email message has appeared. ${message}

    `
  }
})

At the moment however, the project does not work, with the following error:

Class constructor may not be an async method

Is there a way to circumvent this so that I can use async/await within this?  Instead of requiring callbacks or .then()?

Body:
You should add then function to instance. Promise will recognize it as a thenable object with Promise.resolve automatically

const asyncSymbol = Symbol();
class MyClass {
    constructor() {
        this.asyncData = null
    }
    then(resolve, reject) {
        return (this[asyncSymbol] = this[asyncSymbol] || new Promise((innerResolve, innerReject) => {
            this.asyncData = { a: 1 }
            setTimeout(() => innerResolve(this.asyncData), 3000)
        })).then(resolve, reject)
    }
}

async function wait() {
    const asyncData = await new MyClass();
    alert('run 3s later')
    alert(asyncData.a)
}


问:
How can I send file from postman to node js?
I want to upload file from postman to node js but I have problem.
POSTMAN
Write url,check post method,check form-data,check file,write file name and choose file
This is my code
app.js

```<code>const express = require('express');
const bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');

app.use(fileUpload());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
</code>```

router.js

```<code>router.post('/schedule/entry', function(req,res){
   console.log(req.file.name);
});
</code>```

Console return me undefined name, if I write this code

```<code>router.post('/schedule/entry', function(req,res){
   console.log(req.file);
});
</code>```

Return 'undefined'
Why?

package.json

```<code>  {
   "name": "nodejs-rest-api-authentication",
   "version": "1.0.0",
   "description": "",
   "main": "app.js",
   "scripts": {
   "start": "node server.js",
   "test": "echo \"Error: no test specified\" && exit 1"
 },
 "author": "",
 "license": "ISC",
 "dependencies": {
  "bcryptjs": "^2.4.3",
  "body-parser": "^1.16.1",
  "csv-array": "0.0.22",
  "csv-write-stream": "^2.0.0",
  "express": "^4.14.1",
  "express-fileupload": "^0.3.0",
"fast-csv": "^2.4.1",
"formidable": "^1.1.1",
"json2csv": "^3.11.5",
"jsonwebtoken": "^8.1.0",
"mysql": "^2.15.0"
  }
 }
</code>```

server.js

```<code>const app = require('./app');
const port = process.env.PORT || 3000;

const server = app.listen(port, function() {
console.log('Server listening on port ' + port);
});
</code>```

screenshots
screenshots

codeGit

答:
Based on the discussion in the comment section:

```<code>const express = require('express')
const app = express()
const formidable = require('formidable')
const path = require('path')
const uploadDir = '' // uploading the file to the same path as app.js

app.post('/', (req, res) =>{
  var form = new formidable.IncomingForm()
  form.multiples = true
  form.keepExtensions = true
  form.uploadDir = uploadDir
  form.parse(req, (err, fields, files) => {
    if (err) return res.status(500).json({ error: err })
    res.status(200).json({ uploaded: true })
  })
  form.on('fileBegin', function (name, file) {
    const [fileName, fileExt] = file.name.split('.')
    file.path = path.join(uploadDir, `${fileName}_${new Date().getTime()}.${fileExt}`)
  })
});

app.listen(3000, () => console.log('Example app listening on port 3000!'))
</code>```

Attached Screenshots:

Body:
I want to upload file from postman to node js but I have problem.
POSTMAN
Write url,check post method,check form-data,check file,write file name and choose file
This is my code
app.js

const express = require('express');
const bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');

app.use(fileUpload());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

router.js

router.post('/schedule/entry', function(req,res){
   console.log(req.file.name);
});

Console return me undefined name, if I write this code

router.post('/schedule/entry', function(req,res){
   console.log(req.file);
});

Return 'undefined'
Why?

package.json

  {
   "name": "nodejs-rest-api-authentication",
   "version": "1.0.0",
   "description": "",
   "main": "app.js",
   "scripts": {
   "start": "node server.js",
   "test": "echo \"Error: no test specified\" && exit 1"
 },
 "author": "",
 "license": "ISC",
 "dependencies": {
  "bcryptjs": "^2.4.3",
  "body-parser": "^1.16.1",
  "csv-array": "0.0.22",
  "csv-write-stream": "^2.0.0",
  "express": "^4.14.1",
  "express-fileupload": "^0.3.0",
"fast-csv": "^2.4.1",
"formidable": "^1.1.1",
"json2csv": "^3.11.5",
"jsonwebtoken": "^8.1.0",
"mysql": "^2.15.0"
  }
 }

server.js

const app = require('./app');
const port = process.env.PORT || 3000;

const server = app.listen(port, function() {
console.log('Server listening on port ' + port);
});

screenshots
screenshots

codeGit

Body:
Based on the discussion in the comment section:

const express = require('express')
const app = express()
const formidable = require('formidable')
const path = require('path')
const uploadDir = '' // uploading the file to the same path as app.js

app.post('/', (req, res) =>{
  var form = new formidable.IncomingForm()
  form.multiples = true
  form.keepExtensions = true
  form.uploadDir = uploadDir
  form.parse(req, (err, fields, files) => {
    if (err) return res.status(500).json({ error: err })
    res.status(200).json({ uploaded: true })
  })
  form.on('fileBegin', function (name, file) {
    const [fileName, fileExt] = file.name.split('.')
    file.path = path.join(uploadDir, `${fileName}_${new Date().getTime()}.${fileExt}`)
  })
});

app.listen(3000, () => console.log('Example app listening on port 3000!'))

Attached Screenshots:


问:
Abstraction and bare-metalness with OSes?
If I have a CPU and I wrote a program and I wanted to store a value (copy a value from a register to memory (RAM)) then I would use an instrucction in the CPU's instruction set (lets say that this is an x86 CPU) to do so?

Second question, is the instruction in th x86 instruction set to set a value at a particular address in RAM called MOV?

Third question. BIOS, UEFI, kernels and bootloaders all use the MOV instruction in the x86 instruction set to do so (assign a value (like 10) to a specific address in RAM) right?

Fourth question. Programs that operate in the OS (with a kernel (like Linux)) environment do not use the MOV instruction to get a chunk of memory allocated when they request for it but rather ask the kernel to do it on their behalf?

Fifth question. Is what I described in the fourth question called a system call (when a program running in the OS environment asks the kernel to do something (in this case give it some memory) on its behalf)?

答:
0. I think you don't know enough about assembly language to even formulate a sensible question that really fills in whatever gap you're missing, but I've tried to answer your questions as they are.  I'm really not sure what you really want to know.

Perhaps check out Matt Godbolt's CppCon2017 talk: “What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid” for a beginner intro to x86 asm.

But I think you're missing some concepts more about stack / heap / static storage locations.  See Stack, Static, and Heap in C++

yes

yes, the most common x86 store instruction is mov.  e.g. mov dword [rdi], 10.  Or with an absolute address encoding into the instruction as well, mov dword [my_static_32_bit_location], 10

that's oddly specific.  You could write a bootloader without any static data.  All your mov-immediate instructions would use register destinations.

mov doesn't ever allocate or reserve memory.  Programs running under an OS can have static data.  e.g. consider this C function:

```<code>unsigned LCG_rand() {
    static unsigned seed = 0x1234;
    seed = seed * 0x5677 + 0x7723;  // Linear Congruential Generator with badly chosen coefficients I just made up
    return seed;                    // mod type-width is implicit
}
</code>```

gcc7.2 targeting x86-64 Linux compiles this to (Godbolt compiler explorer):

```<code>LCG_rand:
    imul    eax, DWORD PTR seed.2294[rip], 22135    # eax = load(seed) * 22135
    add     eax, 30499                              # eax += 30499
    mov     DWORD PTR seed.2294[rip], eax           # store the old value back to memory.
    ret

.data            # static read-write data goes in the .data section
.align 4
seed.2294:       # label which the compiler uses to refer to it.
    .long   4660
</code>```

The .data section holds static read-write data with non-zero initializers.  The initial values are stored literally in the executable.  It's linked into the data segment of the executable.  When you run it, the data segment of the executable is mapped into the process's memory space with read/write permissions, copy-on-write (private).  (So writing the data in memory doesn't update the data on disk, the way it would if you used mmap with MAP_SHARED.)

These addresses are link-time constants, so a program can use it directly.  (In the code above, the function is using PC-relative addressing, but absolute would be supported too.  You may have to use -no-pie on some gcc setups, though.)

Exactly the same machine code would work fine in a bare-metal environment, even with paging disabled so the addresses you're using are physical addresses, instead of the usual virtual addresses which let every process have its own view of memory.  (Err, but you'd probably have to be in 16 or 32-bit mode, I forget if x86-64 long mode even works with paging disabled.)

yes.  See What are the calling conventions for UNIX & Linux system calls on i386 and x86-64 for details on how user-space processes make system calls.

Body:
0. I think you don't know enough about assembly language to even formulate a sensible question that really fills in whatever gap you're missing, but I've tried to answer your questions as they are.  I'm really not sure what you really want to know.

Perhaps check out Matt Godbolt's CppCon2017 talk: “What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid” for a beginner intro to x86 asm.

But I think you're missing some concepts more about stack / heap / static storage locations.  See Stack, Static, and Heap in C++

yes

yes, the most common x86 store instruction is mov.  e.g. mov dword [rdi], 10.  Or with an absolute address encoding into the instruction as well, mov dword [my_static_32_bit_location], 10

that's oddly specific.  You could write a bootloader without any static data.  All your mov-immediate instructions would use register destinations.

mov doesn't ever allocate or reserve memory.  Programs running under an OS can have static data.  e.g. consider this C function:

unsigned LCG_rand() {
    static unsigned seed = 0x1234;
    seed = seed * 0x5677 + 0x7723;  // Linear Congruential Generator with badly chosen coefficients I just made up
    return seed;                    // mod type-width is implicit
}

gcc7.2 targeting x86-64 Linux compiles this to <a href="https://gcc.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,source:'unsigned+LCG_rand()+%7B%0A++++static+unsigned+seed+%3D+0x1234%3B%0A++++seed+%3D+seed+*+0x5677+%2B+0x7723%3B++//+LCG+with+badly+chosen+coefficients+I+just+made+up%0A++++return+seed%3B%0A%7D%0A%0A'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:44.63971880492091,l:'4',m:100,n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:g72,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'1',execute:'1',intel:'0',trim:'1'),libs:!(),options:'-xc+-O3+-march%3Dhaswell',source:1),l:'5',n:'0',o:'x86-64+gcc+7.2+(Editor+%231,+Compiler+%231)',t:'0')),header:(),k:55.360281195079075,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4" rel="nofollow noreferrer">(Godbolt compiler explorer):

LCG_rand:
    imul    eax, DWORD PTR seed.2294[rip], 22135    # eax = load(seed) * 22135
    add     eax, 30499                              # eax += 30499
    mov     DWORD PTR seed.2294[rip], eax           # store the old value back to memory.
    ret

.data            # static read-write data goes in the .data section
.align 4
seed.2294:       # label which the compiler uses to refer to it.
    .long   4660

The .data section holds static read-write data with non-zero initializers.  The initial values are stored literally in the executable.  It's linked into the data segment of the executable.  When you run it, the data segment of the executable is mapped into the process's memory space with read/write permissions, copy-on-write (private).  (So writing the data in memory doesn't update the data on disk, the way it would if you used mmap with MAP_SHARED.)

These addresses are link-time constants, so a program can use it directly.  (In the code above, the function is using PC-relative addressing, but absolute would be supported too.  You may have to use -no-pie on some gcc setups, though.)

Exactly the same machine code would work fine in a bare-metal environment, even with paging disabled so the addresses you're using are physical addresses, instead of the usual virtual addresses which let every process have its own view of memory.  (Err, but you'd probably have to be in 16 or 32-bit mode, I forget if x86-64 long mode even works with paging disabled.)

yes.  See What are the calling conventions for UNIX & Linux system calls on i386 and x86-64 for details on how user-space processes make system calls.


问:
globally declare $ or jQuery in angular 2/4
I am using jQuery in my angular 4 project. In every file I am declaring it on the top. I use this in most of my .ts files

```<code>declare const $: any;
</code>```

Is there any way I can declare it in a single place and use it in all files, instead of declaring in every file?

答:
The better way of using JQuery in Angular is importing its .d.ts file, and using declare const $: any; is not the a good way since your IDE won't give you auto-completion and can run into some problems

Steps to use JQuery in Angular:

1- Find JQuery (or any other package you want) from TypeSeach, then you will end up on this NPM package, install it:

```<code>npm install --save @types/jquery
</code>```

2- Install JQuery itself:

```<code>npm install --save jquery
</code>```

3- Anywhere you want to use JQuery, just Import type declaration file (.d.ts) into Angular app:

```<code>import * as $ from 'jquery';
</code>```

Read more on this article

When working with scripts that extend other libraries, for instance with JQuery plugins (e.g, $('.test').myPlugin();), since the installed @types/jquery may not include myPlugin, you would need to add an interface like the one below in src/typings.d.ts.

```<code>interface JQuery {
  myPlugin(options?: any): any;
}
</code>```

Body:
I am using jQuery in my angular 4 project. In every file I am declaring it on the top. I use this in most of my .ts files

declare const $: any;

Is there any way I can declare it in a single place and use it in all files, instead of declaring in every file?

Body:
The better way of using JQuery in Angular is importing its .d.ts file, and using declare const $: any; is not the a good way since your IDE won't give you auto-completion and can run into some problems

Steps to use JQuery in Angular:

1- Find JQuery (or any other package you want) from TypeSeach, then you will end up on this NPM package, install it:

npm install --save @types/jquery

2- Install JQuery itself:

npm install --save jquery

3- Anywhere you want to use JQuery, just Import type declaration file (.d.ts) into Angular app:

import * as $ from 'jquery';

Read more on this article

When working with scripts that extend other libraries, for instance with JQuery plugins (e.g, $('.test').myPlugin();), since the installed @types/jquery may not include myPlugin, you would need to add an interface like the one below in src/typings.d.ts.

interface JQuery {
  myPlugin(options?: any): any;
}


问:
iOS 11 - map cluster annotation icon size behaviour
Is there any way to resize the large annotation as same as the left ones.It is iOS11 behaviour and I want the unique size for all annotations like before.

Thanks in advance

答:
This is what I have done for my project

In delegate method

```<code>- (MKAnnotationView *) mapView:(MKMapView *)mapView1 viewForAnnotation:(id <MKAnnotation>) annotation
</code>```

1) create the annotation view

```<code>MKAnnotationView *annView = [[MKAnnotationView alloc] initWithAnnotation:currentAnnotation reuseIdentifier:@"Cluster"];
</code>```

2) set the frame and other properties

```<code>[annView setFrame:CGRectMake(0, 0,100,100)]; //(Important)
annView.canShowCallout = YES;
[annView setCenterOffset:CGPointMake(0, -18)];
</code>```

3) add image view as sub view with same frame size

```<code>UIImageView *homeImage = [[UIImageView alloc] initWithImage:[UIImage cachedImage:@"GroupPin"]];
[homeImage setFrame:CGRectMake(0, 0,100,100)]; //(Important)
[annView addSubview:homeImage];
return annView;
</code>```

and you are done.

Body:
This is what I have done for my project

In delegate method

- (MKAnnotationView *) mapView:(MKMapView *)mapView1 viewForAnnotation:(id <MKAnnotation>) annotation

1) create the annotation view

MKAnnotationView *annView = [[MKAnnotationView alloc] initWithAnnotation:currentAnnotation reuseIdentifier:@"Cluster"];

2) set the frame and other properties

[annView setFrame:CGRectMake(0, 0,100,100)]; //(Important)
annView.canShowCallout = YES;
[annView setCenterOffset:CGPointMake(0, -18)];

3) add image view as sub view with same frame size

UIImageView *homeImage = [[UIImageView alloc] initWithImage:[UIImage cachedImage:@"GroupPin"]];
[homeImage setFrame:CGRectMake(0, 0,100,100)]; //(Important)
[annView addSubview:homeImage];
return annView;

and you are done.


问:
Adding 'rayOrigin: mouse' to Aframe cursor component throwing error
I am trying to include a mouse click functionality to VR scene apart from focus cursor.  I am using it as below - </p>

```<code> <a-entity camera look-controls mouse-cursor>
    <a-entity position="0 0 -3" scale="0.2 0.2 0.2" geometry="primitive: ring; radiusOuter: 0.20;radiusInner: 0.10;" material="color: #990000; shader: flat" cursor=" fuse: true; rayOrigin: mouse">

    </a-entity>
</a-entity>
</code>```

<p>Below is the error while using this code. Please note that i am using Afrmae with Angular2 </p>

```<code> ERROR TypeError: Cannot read property 'count' of undefined
at Mesh.raycast (aframe-master.js:21938)
at intersectObject (aframe-master.js:45999)
at Raycaster.intersectObjects (aframe-master.js:46072)
at NewComponent.module.exports.Component.registerComponent.tick (aframe-master.js:69697)
at HTMLElement.value (aframe-master.js:76597)
at HTMLElement.value (aframe-master.js:76645)
at bound (aframe-master.js:79931)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:425)
at Object.onInvokeTask (core.es5.js:3881)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
</code>```

答:
If you want your mouse to act like a  You need to move the cursor bit to the  :

```<code><a-scene cursor="rayOrigin:mouse">
</code>```

Body:
I am trying to include a mouse click functionality to VR scene apart from focus cursor.  I am using it as below -

Below is the error while using this code. Please note that i am using Afrmae with Angular2

 ERROR TypeError: Cannot read property 'count' of undefined
at Mesh.raycast (aframe-master.js:21938)
at intersectObject (aframe-master.js:45999)
at Raycaster.intersectObjects (aframe-master.js:46072)
at NewComponent.module.exports.Component.registerComponent.tick (aframe-master.js:69697)
at HTMLElement.value (aframe-master.js:76597)
at HTMLElement.value (aframe-master.js:76645)
at bound (aframe-master.js:79931)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:425)
at Object.onInvokeTask (core.es5.js:3881)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)

Body:
If you want your mouse to act like a <a-cursor> You need to move the cursor bit to the <a-scene> :

<a-scene cursor="rayOrigin:mouse">


问:
Run Code On Application Close
This is a very common problem yet again, and yet again it seems there is no real support in E4 (but if I remember correctly, it did not work in E3 either).

I want to close my database connection when the application closes. Or more general: I want to do any kind of clean up on exit.

So the usual API for this is:

```<code>public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {

    public ApplicationWorkbenchWindowAdvisor(final IWorkbenchWindowConfigurer configurer) {
        super(configurer);
    }

    @Override
    public boolean preWindowShellClose() {
        if (PlatformUI.getWorkbench().getWorkbenchWindowCount() <= 1) {
            // the last window is about to close
            Datababase.close();
        }
        return super.preWindowShellClose();
    }
}
</code>```

The problem? It's not called every time the application closes, especially not on PlatformUI.getWorkbench().close(); (even though the JavaDoc claims this method closes the windows).

(If you want to test if this claim is correct, just use the ExitHandler to close your application - preWindowShellClose() is not called then.)

I could create my own handler and manually call the clean up methods yet again, but I was hoping there was a better way.

Another way you could react to a application shutdown is the Shutdown Hooks API:

```<code>Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    Datababase.close();
}));
</code>```

Problem: for an RCP application, this hook is called way, way, way too late, e.g. all plug-ins are already closed then.

I feel there must be a simple (and working) way, I just haven't found it yet. If it's important, we are using the Lesser Evil Eclipse (aka E3 compatibility).

How do I run code whenever an application closes?

答:
Use IWorkbench::addWindowListener or IWorkbench::addWorkbenchListener to get notified when a workbench window is closed or the workbench is shut down.

You may also consider running the clean up code from you bundle's stop method.

Title: Run Code On Application Close

Body:
This is a very common problem yet again, and yet again it seems there is no real support in E4 (but if I remember correctly, it did not work in E3 either).

I want to close my database connection when the application closes. Or more general: I want to do any kind of clean up on exit.

So the usual API for this is:

public class ApplicationWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {

    public ApplicationWorkbenchWindowAdvisor(final IWorkbenchWindowConfigurer configurer) {
        super(configurer);
    }

    @Override
    public boolean preWindowShellClose() {
        if (PlatformUI.getWorkbench().getWorkbenchWindowCount() <= 1) {
            // the last window is about to close
            Datababase.close();
        }
        return super.preWindowShellClose();
    }
}

The problem? It's not called every time the application closes, especially not on PlatformUI.getWorkbench().close(); (even though the JavaDoc claims this method closes the windows).

(If you want to test if this claim is correct, just use the ExitHandler to close your application - preWindowShellClose() is not called then.)

I could create my own handler and manually call the clean up methods yet again, but I was hoping there was a better way.

Another way you could react to a application shutdown is the Shutdown Hooks API:

Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    Datababase.close();
}));

Problem: for an RCP application, this hook is called way, way, way too late, e.g. all plug-ins are already closed then.

I feel there must be a simple (and working) way, I just haven't found it yet. If it's important, we are using the Lesser Evil Eclipse (aka E3 compatibility).

How do I run code whenever an application closes?


问:
jQuery prevent change for select
I want to prevent a select box from being changed if a certain condition applies.  Doing this doesn't seem to work:

```<code>$('#my_select').bind('change', function(ev) {
  if(my_condition)
  {
    ev.preventDefault();
    return false;
  }
});
</code>```

I'm guessing this is because by this point the selected option has already changed.

What are other ways of doing this?

答:
This worked for me, no need to keep a lastSelected if you know the optionIndex to select.

```<code>var optionIndex = ...
$(this)[0].options[optionIndex].selected = true;
</code>```

Title: jQuery prevent change for select

Body:
I want to prevent a select box from being changed if a certain condition applies.  Doing this doesn't seem to work:

$('#my_select').bind('change', function(ev) {
  if(my_condition)
  {
    ev.preventDefault();
    return false;
  }
});

I'm guessing this is because by this point the selected option has already changed.

What are other ways of doing this?

Body:
This worked for me, no need to keep a lastSelected if you know the optionIndex to select.

var optionIndex = ...
$(this)[0].options[optionIndex].selected = true;


问:
Recursive CTE to find all records SQL Server
I am having below table structure. I want to write a recursive cte to get the bottom most table result.
Highly appreciate your help.

```<code>CREATE TABLE Jobcard (
  jobcard_id INT NOT NULL PRIMARY KEY,
  jobcard_name varchar(20) NOT NULL,
);
CREATE TABLE Vehicle (
  vehicle_id INT NOT NULL PRIMARY KEY,
  vehicle_name varchar(20) NOT NULL
);

CREATE TABLE Jobacard_vehicle (
  jobcard_id INT NOT NULL,
  vehicle_id INT NOT NULL
);

INSERT INTO Jobcard (jobcard_id, jobcard_name) VALUES
(1, 'Job1'),(2, 'Job2'),(3, 'Job3'),
(4, 'Job4'),(5, 'Job5'),(6, 'Job6'),
(7, 'Job7'),(8, 'Job8'),(9, 'Job9');

INSERT INTO Vehicle (vehicle_id, vehicle_name) VALUES
(1, 'Vehicle1'),(2, 'Vehicle2'),(3, 'Vehicle3'),
(4, 'Vehicle4'),(5, 'Vehicle5'),(6, 'Vehicle6');

INSERT INTO Jobacard_vehicle (jobcard_id, vehicle_id) VALUES
(3, 1),(4, 2),(5, 3),
(9, 6),(7, 2),(5, 4),
(8, 4),(6, 1),(3, 5);
</code>```

jobcard_id, vehicle_id
--------------------------
3           1
4           2
5           3
9           6
7           2
5           4
8           4
6           1
3           5

I want to get this result from Jobacard_vehicle table when I pass the vehicle id as 3 as
```

<p>vehicle id 3 is having jobcard 5
jobcard 5 is having vehicle 4
again vehicle 4 referred to jobcard 8
means all the jobcard refered by 3 or its counter part jobcards vehicles</p>

```jobcard_id, vehicle_id
--------------------------
5           3
5           4
8           4
```

Thank you.

答:
Try to save full path and check it in the next recursion

```<code>DECLARE @startVehicleID int=3

;WITH vehCTE AS(
    SELECT jobcard_id,vehicle_id,CAST(CONCAT('(',jobcard_id,',',vehicle_id,')') AS varchar(MAX)) [path]
    FROM Jobacard_vehicle
    WHERE vehicle_id=@startVehicleID

    UNION ALL

    SELECT v.jobcard_id,v.vehicle_id,c.[path]+CONCAT('(',v.jobcard_id,',',v.vehicle_id,')')
    FROM Jobacard_vehicle v
    JOIN vehCTE c ON (v.jobcard_id=c.jobcard_id OR v.vehicle_id=c.vehicle_id) AND CHARINDEX(CONCAT('(',v.jobcard_id,',',v.vehicle_id,')'),c.[path])=0
)
SELECT *
FROM vehCTE
ORDER BY [path]
</code>```

If you need to check Job->Vehicle->Job->Vehicle->... then I think you can use the following

```<code>DECLARE @startVehicleID int=3

;WITH vehCTE AS(
    SELECT
        jobcard_id,
        vehicle_id,
        CAST(CONCAT('(',jobcard_id,',',vehicle_id,')') AS varchar(MAX)) [path],
        1 NextIsJob
    FROM Jobacard_vehicle
    WHERE vehicle_id=@startVehicleID

    UNION ALL

    SELECT
        v.jobcard_id,
        v.vehicle_id,
        c.[path]+CONCAT('(',v.jobcard_id,',',v.vehicle_id,')'),
        IIF(c.NextIsJob=1,0,1)
    FROM Jobacard_vehicle v
    JOIN vehCTE c ON ((c.NextIsJob=1 AND v.jobcard_id=c.jobcard_id) OR (c.NextIsJob=0 AND v.vehicle_id=c.vehicle_id)) AND CHARINDEX(CONCAT('(',v.jobcard_id,',',v.vehicle_id,')'),c.[path])=0
)
SELECT *
FROM vehCTE
ORDER BY [path]
</code>```

Body:
I am having below table structure. I want to write a recursive cte to get the bottom most table result.
Highly appreciate your help.

CREATE TABLE Jobcard (
  jobcard_id INT NOT NULL PRIMARY KEY,
  jobcard_name varchar(20) NOT NULL,
);
CREATE TABLE Vehicle (
  vehicle_id INT NOT NULL PRIMARY KEY,
  vehicle_name varchar(20) NOT NULL
);

CREATE TABLE Jobacard_vehicle (
  jobcard_id INT NOT NULL,
  vehicle_id INT NOT NULL
);

INSERT INTO Jobcard (jobcard_id, jobcard_name) VALUES
(1, 'Job1'),(2, 'Job2'),(3, 'Job3'),
(4, 'Job4'),(5, 'Job5'),(6, 'Job6'),
(7, 'Job7'),(8, 'Job8'),(9, 'Job9');

INSERT INTO Vehicle (vehicle_id, vehicle_name) VALUES
(1, 'Vehicle1'),(2, 'Vehicle2'),(3, 'Vehicle3'),
(4, 'Vehicle4'),(5, 'Vehicle5'),(6, 'Vehicle6');

INSERT INTO Jobacard_vehicle (jobcard_id, vehicle_id) VALUES
(3, 1),(4, 2),(5, 3),
(9, 6),(7, 2),(5, 4),
(8, 4),(6, 1),(3, 5);

jobcard_id, vehicle_id
--------------------------
3           1
4           2
5           3
9           6
7           2
5           4
8           4
6           1
3           5

I want to get this result from Jobacard_vehicle table when I pass the vehicle id as 3 as

vehicle id 3 is having jobcard 5
jobcard 5 is having vehicle 4
again vehicle 4 referred to jobcard 8
means all the jobcard refered by 3 or its counter part jobcards vehicles

jobcard_id, vehicle_id
--------------------------
5           3
5           4
8           4

Thank you.

Body:
Try to save full path and check it in the next recursion

DECLARE @startVehicleID int=3

;WITH vehCTE AS(
    SELECT jobcard_id,vehicle_id,CAST(CONCAT('(',jobcard_id,',',vehicle_id,')') AS varchar(MAX)) [path]
    FROM Jobacard_vehicle
    WHERE vehicle_id=@startVehicleID

    UNION ALL

    SELECT v.jobcard_id,v.vehicle_id,c.[path]+CONCAT('(',v.jobcard_id,',',v.vehicle_id,')')
    FROM Jobacard_vehicle v
    JOIN vehCTE c ON (v.jobcard_id=c.jobcard_id OR v.vehicle_id=c.vehicle_id) AND CHARINDEX(CONCAT('(',v.jobcard_id,',',v.vehicle_id,')'),c.[path])=0
)
SELECT *
FROM vehCTE
ORDER BY [path]

If you need to check Job->Vehicle->Job->Vehicle->... then I think you can use the following

DECLARE @startVehicleID int=3

;WITH vehCTE AS(
    SELECT
        jobcard_id,
        vehicle_id,
        CAST(CONCAT('(',jobcard_id,',',vehicle_id,')') AS varchar(MAX)) [path],
        1 NextIsJob
    FROM Jobacard_vehicle
    WHERE vehicle_id=@startVehicleID

    UNION ALL

    SELECT
        v.jobcard_id,
        v.vehicle_id,
        c.[path]+CONCAT('(',v.jobcard_id,',',v.vehicle_id,')'),
        IIF(c.NextIsJob=1,0,1)
    FROM Jobacard_vehicle v
    JOIN vehCTE c ON ((c.NextIsJob=1 AND v.jobcard_id=c.jobcard_id) OR (c.NextIsJob=0 AND v.vehicle_id=c.vehicle_id)) AND CHARINDEX(CONCAT('(',v.jobcard_id,',',v.vehicle_id,')'),c.[path])=0
)
SELECT *
FROM vehCTE
ORDER BY [path]


问:
pop up form data not insert in database
I'm trying to insert data  to my PHP using ajax post method.I have passed the first form data to hidden value in first script , but data is not inserted in database.Now I want to pass those variables (response.lastname, response.firstname ) into my database.Please help me to solve this issue. Any example will be very useful.. thank u in advance.

php ajax

```<code><div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            Confirm Submit
        </div>   <form role="form" id="add_name"  method="post"  enctype="multipart/form-data" action="">
        <div class="modal-body">
                          <table class="table">
                <tr>
                    <th>Last Name</th>
                    <td id="lname" name="lname" ></td>
                </tr>
                <tr>
                    <th>First Name</th>
                    <td id="fname" name="fname"></td>
                </tr>
                <tr><td>name</td>
                <td><input type="text" name="nam"></td>
                </tr>     </table>

        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal" >Cancel</button>
             <button    type="submit" class="btn btn-success" id="submit" name="submit"><i class="glyphicon glyphicon-inbox"></i> Submit</button>

        </div>
    </div>
  </form><div id="response"></div>

  <script>

   $(document).ready(function(){

        $('#submitBtn').click(function() {

            $('#lname').text($('#lastname').val());
        $('#fname').text($('#firstname').val());

            var fname = $('#firstname').val();
            $('#fname').val(fname);
            alert(fname);

            var laname = $('#lastname').val();
            $('#lname').val(laname);
            alert(laname);
        });

    });
</script>

 <script>
   $(document).ready(function(){
  $('#submit').click(function(){
       var lname = $('#lname').val();
       var fname = $('#fname').val();
     alert(lname);
            $.ajax({
                 url:"insert.php",
                 method:"POST",
                 data:$('#add_name').serialize(),
                 beforeSend:function(){
                      $('#response').html('<span class="text-info">Loading response...</span>');
                 },
                 success:function(data){
                      $('form').trigger("reset");
                      $('#response').fadeIn().html(data);
                      setTimeout(function(){
                           $('#response').fadeOut("slow");
                      }, 5000);
                 }
            });

  });
});
</code>```

```<code>  <?php
 //insert.php
 $connect = mysqli_connect("localhost", "root", "", "demoss");

  $name = mysqli_real_escape_string($connect, $_POST["lname"]);
  $message = mysqli_real_escape_string($connect, $_POST["fname"]);
  $query = "INSERT INTO tbl_form(name, message) VALUES ('".$name."', '".$message."')";
  if(mysqli_query($connect, $query))
  {
       echo '<p>You have entered</p>';
       echo '<p>Name:'.$name.'</p>';
       echo '<p>Message : '.$message.'</p>';
  }

 ?>
</code>```

答:
Try This:</p>

```<code><div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                Confirm Submit
            </div>
            <form role="form" id="add_name" method="post">
                <div class="modal-body">
                    <table class="table">
                        <tr>
                            <td>Last Name</td>
                            <td><input type="text" name="lname" id="lname"></td>
                        </tr>
                        <tr>
                            <td>First Name</td>
                            <td><input type="text" name="fname" id="fname"></td>
                        </tr>
                        <tr>
                            <td>name</td>
                            <td>
                                <input type="text" name="name" id="name">
                            </td>
                        </tr>
                    </table>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-success" id="submit">
                        <i class="glyphicon glyphicon-inbox"></i> Submit</button>

                </div>
        </div>
        </form>
        <div id="response"></div>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script>

               $(document).ready(function () {
                    $('#submit').click(function () {
                        var lname = $('#lname').val();
                        var fname = $('#fname').val();
                        alert(lname);
                        $.ajax({
                            method: "POST",
                            url: "insert.php",
                            data: $('#add_name').serialize(),
                            beforeSend: function () {
                                $('#response').html('<span class="text-info">Loading response...</span>');
                            },
                            success: function (data) {
                                $('form').trigger("reset");
                                $('#response').fadeIn().html(data);
                                setTimeout(function () {
                                    $('#response').fadeOut("slow");
                                }, 5000);
                            }
                        });

                    });
                });

            </script>
</code>```

Title: pop up form data not insert in database

Body:
I'm trying to insert data  to my PHP using ajax post method.I have passed the first form data to hidden value in first script , but data is not inserted in database.Now I want to pass those variables (response.lastname, response.firstname ) into my database.Please help me to solve this issue. Any example will be very useful.. thank u in advance.

php ajax

            Confirm Submit

   <form role="form" id="add_name"  method="post"  enctype="multipart/form-data" action="">

                    Last Name

                    First Name

name
                <input type="text" name="nam">

            <button type="button" class="btn btn-default" data-dismiss="modal" >Cancel</button>
             <button    type="submit" class="btn btn-success" id="submit" name="submit"> Submit</button>

  </form>

Body:
Try This:

<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                Confirm Submit
            </div>
            <form role="form" id="add_name" method="post">
                <div class="modal-body">
                    <table class="table">
                        <tr>
                            <td>Last Name</td>
                            <td><input type="text" name="lname" id="lname"></td>
                        </tr>
                        <tr>
                            <td>First Name</td>
                            <td><input type="text" name="fname" id="fname"></td>
                        </tr>
                        <tr>
                            <td>name</td>
                            <td>
                                <input type="text" name="name" id="name">
                            </td>
                        </tr>
                    </table>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-success" id="submit">
                        <i class="glyphicon glyphicon-inbox"></i> Submit</button>

                </div>
        </div>
        </form>
        <div id="response"></div>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script>

               $(document).ready(function () {
                    $('#submit').click(function () {
                        var lname = $('#lname').val();
                        var fname = $('#fname').val();
                        alert(lname);
                        $.ajax({
                            method: "POST",
                            url: "insert.php",
                            data: $('#add_name').serialize(),
                            beforeSend: function () {
                                $('#response').html('<span class="text-info">Loading response...</span>');
                            },
                            success: function (data) {
                                $('form').trigger("reset");
                                $('#response').fadeIn().html(data);
                                setTimeout(function () {
                                    $('#response').fadeOut("slow");
                                }, 5000);
                            }
                        });

                    });
                });

            </script>


问:
AOSP device node access permissions
This is a similar post as device-node-access-permissions-in-linux 6 years ago without an answer.

I have a device node at /dev/magic-i2c created using misc_register(), the problem is the default access permissions for this device node is for root, and cant be accessed by AOSP libraries. I tried adding .mode = S_IRWXUGO but no effect. How can I change the permission of this device node automatically during bootup?

答: You can add chmod 660 /dev/magic-i2c in "on boot" section or somewhere in init.rc file. You can add this in any section in init.rc depending on when you need the permission to be given.

Title: AOSP device node access permissions


问:
How to assign a variable in the WHERE clause of a sub-query in SQL Server
```<code>SELECT
    Total_Males, SETTLEMENT_ID, URI, _PARENT_AURI
FROM
    (SELECT
         COUNT(t2.SEX) as Total_Males, t1.SETTLEMENT_ID, t1.URI,
         t2._PARENT_AURI
     FROM
         PScData t1
     INNER JOIN
         PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
     WHERE
         t1.SETTLEMENT_ID = '11102002002001'
         AND t2.SEX = '1'
     GROUP BY
         t1.URI, t2._PARENT_AURI, t1.SETTLEMENT_ID) tmp
</code>```

This is the query that I have written. In the WHERE clause, where I have given the exact value - '11102002002001' - I want to compare with each SETTLEMENT_ID from t1. How can I do this? Please provide some solution.

Further, the query is returning count in two rows i.e: count against two different ids right now. How can I add the result of two different ids to get the sum of these two rows returned by the sub-query?

答:
I found the solution to the query the result can be retrieved and summed up like this:</p>

```<code>SELECT Total_Males, SETTLEMENT_ID
FROM (
    SELECT COUNT(t2.SEX) as Total_Males, t1.SETTLEMENT_ID
    FROM PScData t1
        INNER JOIN PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
    WHERE t1.SETTLEMENT_ID in (SELECT DISTINCT SETTLEMENT_ID FROM PScData)
      AND t2.SEX = '1'
    GROUP BY t1.SETTLEMENT_ID
) tmp
</code>```

Body:
SELECT
    Total_Males, SETTLEMENT_ID, URI, _PARENT_AURI
FROM
    (SELECT
         COUNT(t2.SEX) as Total_Males, t1.SETTLEMENT_ID, t1.URI,
         t2._PARENT_AURI
     FROM
         PScData t1
     INNER JOIN
         PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
     WHERE
         t1.SETTLEMENT_ID = '11102002002001'
         AND t2.SEX = '1'
     GROUP BY
         t1.URI, t2._PARENT_AURI, t1.SETTLEMENT_ID) tmp

This is the query that I have written. In the WHERE clause, where I have given the exact value - '11102002002001' - I want to compare with each SETTLEMENT_ID from t1. How can I do this? Please provide some solution.

Further, the query is returning count in two rows i.e: count against two different ids right now. How can I add the result of two different ids to get the sum of these two rows returned by the sub-query?

Body:
I found the solution to the query the result can be retrieved and summed up like this:

SELECT Total_Males, SETTLEMENT_ID
FROM (
    SELECT COUNT(t2.SEX) as Total_Males, t1.SETTLEMENT_ID
    FROM PScData t1
        INNER JOIN PscMemberData t2 ON t2._PARENT_AURI  = t1.URI
    WHERE t1.SETTLEMENT_ID in (SELECT DISTINCT SETTLEMENT_ID FROM PScData)
      AND t2.SEX = '1'
    GROUP BY t1.SETTLEMENT_ID
) tmp


问:
Strip leading dot from filenames bash script
I have some files in a bunch of directories that have a leading dot and thus are hidden. I would like to revert that and strip the leading dot.

I was unsuccessful with the following:

```<code>for file in `find files/ -type f`;
do
base=`basename $file`
if [ `$base | cut -c1-2` = "." ];
then newname=`$base | cut -c2-`;
dirs=`dirname $file`;
echo $dirs/$newname;
fi
done
</code>```

Which fails on the condition statement:

```<code>[: =: unary operator expected
</code>```

Furthermore, some files have a space in them and file returns them split.

Any help would be appreciated.

答:
The easiest way to delete something from the start of a variable is to use ${var#pattern}.

```<code>$ FILENAME=.bashrc;    echo "${FILENAME#.}"
bashrc
$ FILENAME=/etc/fstab; echo "${FILENAME#.}"
/etc/fstab
</code>```

See the bash man page:

${parameter#word}

  ${parameter##word}

The word is expanded to produce a pattern just as in pathname expansion.  If the pattern matches the beginning of the value of parameter, then the result of the expansion  is
                the  expanded  value  of parameter with the shortest matching pattern (the ‘‘#’’ case) or the longest matching pattern (the ‘‘##’’ case) deleted.

By the way, with a more selective find command you don't need to do all the hard work. You can have find only match files with a leading dot:

```<code>find files/ -type f -name '.*'
</code>```

Throwing that all together, then:

```<code>find files/ -type f -name '.*' -printf '%P\0' |
    while read -d $'\0' path; do
        dir=$(dirname "$path")
        file=$(basename "$path")
        mv "$dir/$file" "$dir/${file#.}"
    done
</code>```

Additional notes:

To handle file names with spaces properly you need to quote variable names when you reference them. Write "$file" instead of just $file.

For extra robustness the -printf '\0' and read -d $'\0' use NUL characters as delimiters so even file names with embedded newlines '\n' will work.

Body:
I have some files in a bunch of directories that have a leading dot and thus are hidden. I would like to revert that and strip the leading dot.

I was unsuccessful with the following:

for file in `find files/ -type f`;
do
base=`basename $file`
if [ `$base | cut -c1-2` = "." ];
then newname=`$base | cut -c2-`;
dirs=`dirname $file`;
echo $dirs/$newname;
fi
done

Which fails on the condition statement:

[: =: unary operator expected

Furthermore, some files have a space in them and file returns them split.

Any help would be appreciated.

Body:
The easiest way to delete something from the start of a variable is to use ${var#pattern}.

$ FILENAME=.bashrc;    echo "${FILENAME#.}"
bashrc
$ FILENAME=/etc/fstab; echo "${FILENAME#.}"
/etc/fstab

See the bash man page:

${parameter#word}

  ${parameter##word}

The word is expanded to produce a pattern just as in pathname expansion.  If the pattern matches the beginning of the value of parameter, then the result of the expansion  is
                the  expanded  value  of parameter with the shortest matching pattern (the ‘‘#’’ case) or the longest matching pattern (the ‘‘##’’ case) deleted.

By the way, with a more selective find command you don't need to do all the hard work. You can have find only match files with a leading dot:

find files/ -type f -name '.*'

Throwing that all together, then:

find files/ -type f -name '.*' -printf '%P\0' |
    while read -d $'\0' path; do
        dir=$(dirname "$path")
        file=$(basename "$path")
        mv "$dir/$file" "$dir/${file#.}"
    done

Additional notes:

To handle file names with spaces properly you need to quote variable names when you reference them. Write "$file" instead of just $file.

For extra robustness the -printf '\0' and read -d $'\0' use NUL characters as delimiters so even file names with embedded newlines '\n' will work.


问:
Detect when my webpage send pageview request with javascripts ga function before deploy my webpage
Over my webpage I use the google-provided ga function in order to send pageviews to my panel.

But how I will detect during development of the webpage's javascript when the javascript send pageview?

I am asking because it may sends more pageviews that requested especially on infinite scrolling pages and single-page applications.

I am not asking how to debug javascript but I am asking on how you can gen an indication when the page's javascript sends a pageview into the google analytics WITHOUT/BEFORE the need of deployment. In other words how I will detect over the tools that browser provides to me in order to detect when my webpage sends a pageview.

答:
Go to the browser's developer tools (either by pressing the F12 key or via your browsers menu) and go to Network tab.

Afterwards on the page network filter for https://www.google-analytics.com/collect each time you see that entry over the network a new pageview gets sent to the google's servers.

An alternative approach is to put console.log before or after ga function.


问:
Dynamic class in react.js
All:

I wonder if I made a signin/signup toggle tab component, how can I dynamically add a selected class to according component(like ngclass)?

```<code>render(){
return (
            <div>
                <span className="tab" className={{"selected": this.state.signin}}>Sign In</span>
                <span className="tab" className={{"selected": !this.state.signin}}>Sign Up</span>
            </div>
    )
}
</code>```

答:
Though John's answer does the Job. That library lacks function support for determining the value.

You can use this npm package. It handles everything and has options for static and dynamic classes based on a variable or a function.

```<code>// Support for string arguments
getClassNames('class1', 'class2');

// support for Object
getClassNames({class1: true, class2 : false});

// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], {
    class5 : function() { return false; },
    class6 : function() { return true; }
});

<div className={getClassNames({class1: true, class2 : false})} />
</code>```

Title: Dynamic class in react.js

Body:
All:

I wonder if I made a signin/signup toggle tab component, how can I dynamically add a selected class to according component(like ngclass)?

render(){
return (

                Sign In
                Sign Up

    )
}

Body:
Though John's answer does the Job. That library lacks function support for determining the value.

You can use this npm package. It handles everything and has options for static and dynamic classes based on a variable or a function.

// Support for string arguments
getClassNames('class1', 'class2');

// support for Object
getClassNames({class1: true, class2 : false});

// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], {
    class5 : function() { return false; },
    class6 : function() { return true; }
});

<div className={getClassNames({class1: true, class2 : false})} />


问:
OOP - inheritance [Java]
bb refers Derived  class, when i call show() method,  but when i print bb.b  - is prints Base class property .
Why is this happening?

```<code>class Base {
    int b=10;
    public void show() {

        System.out.println("Base show() called");

    }
}

class Derived extends Base {

    int b=20;
    public void show() {

        System.out.println("Derived show() called");

    }

}

public class MainClass {

    public static void main(String[] args) {

        Base bb = new Derived();;

        bb.show();
        System.out.println(bb.b);

    }

}
</code>```

output :

Derived show() called

10

答:
While you declare your variable as a Base obj (i.e. Base bb = new Derived();), that does not mean your b object is no longer an instance of Derived (verify this with b instanceof Derived).

This is called hiding and is similar to what people usually do when declaring variables that might later change implementation for example private List<String> someList = new ArrayList<>();. In more technical terms: it's a way of decoupling your code from a specific implementation.

As to why b is 10 (the Base class's value) and not 20: that is because you are explicitly referring to b value in Base class (as mentioned by Timothy Truckle's answer). If you were to explicitly cast your b object back to Derived type, you will see 20 being printed instead:

```<code>System.out.println(((Derived)b).b);
</code>```

Title: OOP - inheritance [Java]

Body:
bb refers Derived  class, when i call show() method,  but when i print bb.b  - is prints Base class property .
Why is this happening?

class Base {
    int b=10;
    public void show() {

        System.out.println("Base show() called");

    }
}

class Derived extends Base {

    int b=20;
    public void show() {

        System.out.println("Derived show() called");

    }

}

public class MainClass {

    public static void main(String[] args) {

        Base bb = new Derived();;

        bb.show();
        System.out.println(bb.b);

    }

}

output :

Derived show() called

10

Body:
While you declare your variable as a Base obj (i.e. Base bb = new Derived();), that does not mean your b object is no longer an instance of Derived (verify this with b instanceof Derived).

This is called hiding and is similar to what people usually do when declaring variables that might later change implementation for example private List<String> someList = new ArrayList<>();. In more technical terms: it's a way of decoupling your code from a specific implementation.

As to why b is 10 (the Base class's value) and not 20: that is because you are explicitly referring to b value in Base class (as mentioned by Timothy Truckle's answer). If you were to explicitly cast your b object back to Derived type, you will see 20 being printed instead:

System.out.println(((Derived)b).b);


问:
Ravendb memory leak on query
I'm having a hard problem solving an issue with RavenDB.
At my work we have a process to trying to identify potential duplicates in our database on a specified collection (let's call it users collection).

That means, I'm iterating through the collection and for each document there is a query that is trying to find similar entities. So just imagine, it's quite a long task to run.

My problem is, when the task starts running, the memory consumption for RavenDB is going higher and higher, it's literally just growing and growing, and it seems to continue until it reaches the maximum memory of the system.

But it doesn't really makes sense, since I'm only doing query, I'm using one single index and take a default page size when querying (128).

Anybody meet a similar problem like this? I really have no idea what is going on in ravendb. but it seems like a memory leak.

RavenDB version: 3.0.179

答:
When i need to do massive operations on large collections i work following this steps to prevent problems on memory usage:

I use Query Streaming to extract all the ids of the documents that i want to process (with a dedicated session)

I open a new session for each id, i load the document and then i do what i need

Title: Ravendb memory leak on query


问:
Do all voice-to-text algorithms operate in real-time?
Do all voice-to-text algorithms of current technology operate in real-time? I don't mean with a person sitting at a computer with a microphone, but rather inputing a pre-recorded audio file.

i.e. If you have a 30 minute voice recording, will it always take 30 minutes to be transcribed?

Are there different approaches out there?

答: There is no reason why speech recognition must take as long as the length of audio to be performed. However, due to the computation required I don't think that you won't get a hugely faster than real time algorithm. See this section of the Wikipedia article for more detailed information (it doesn't seem to give any times, though it does give a decent overview of performance).</p>

OwnerDisplayName: frou

OwnerDisplayName: Noldorin

LastEditorDisplayName: Noldorin