问:
Why can I start a given application using a Windows Service in interactive mode, but not as a service? (Process.Start)

Hello! I am currently writing a simple C#.NET service that stops a given process when a PC loses its wireless connection for 30 seconds. Once the wireless connection returns, it re-starts the process. All of the logic in the service seems sound, and it works perfectly when I run the service on in my Visual Studio dev environment with the target application running from the same directory that exists on the PC where the service will run. However, when I run the service on the remote PC, the application is never restarted upon re-connection to the network. No errors are encountered in the try-catch, either. I have read quite a bit on SO about working directories being an issue, but that doesn't explain why it is working on my machine and not the other. Here is the code I am currently using:

```<code>try
{
    ProcessStartInfo processInfo = new ProcessStartInfo();
    processInfo.FileName = @"C:\Path\Application\Application.exe";
    processInfo.WorkingDirectory = Path.GetDirectoryName(@"C:\Path\Application\Application.exe");
    processInfo.ErrorDialog = true;
    processInfo.UseShellExecute = false;
    processInfo.RedirectStandardOutput = true;
    processInfo.RedirectStandardError = true;
    Process proc = Process.Start(processInfo);
}
catch (Exception ex)
{
    LogTrace.TraceLine("Error re-starting process " + startInfo.FileName + ": " + ex, false);
}
</code>```

Some other notes:

-I have tried are running the service with different users of varying permission levels. Running the service as an Administrator makes no difference.

-UAC is completely off.

-I have tried running the service in interactive mode in Session 0 on target PC using FireDaemon.

Anybody have any ideas on anything to look into?

答:
snippet of a service starter to get you started

```<code>{
using System.ServiceProcess;
using...

namespace myServicenamespace
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] {
                new myService()
            };
            ServiceBase.Run(ServicesToRun);
        }
    }
}
</code>```

myService defined elsewhere as the code you want to have running, including the

```<code>{
protected override void OnStart() {...}
protected override void OnStop {...}
}
</code>```

Deployment of the service also differs, as mentioned check the rest of the documentation on ServiceProcess to see more.

Body:
Hello! I am currently writing a simple C#.NET service that stops a given process when a PC loses its wireless connection for 30 seconds. Once the wireless connection returns, it re-starts the process. All of the logic in the service seems sound, and it works perfectly when I run the service on in my Visual Studio dev environment with the target application running from the same directory that exists on the PC where the service will run. However, when I run the service on the remote PC, the application is never restarted upon re-connection to the network. No errors are encountered in the try-catch, either. I have read quite a bit on SO about working directories being an issue, but that doesn't explain why it is working on my machine and not the other. Here is the code I am currently using:

try
{
    ProcessStartInfo processInfo = new ProcessStartInfo();
    processInfo.FileName = @"C:\Path\Application\Application.exe";
    processInfo.WorkingDirectory = Path.GetDirectoryName(@"C:\Path\Application\Application.exe");
    processInfo.ErrorDialog = true;
    processInfo.UseShellExecute = false;
    processInfo.RedirectStandardOutput = true;
    processInfo.RedirectStandardError = true;
    Process proc = Process.Start(processInfo);
}
catch (Exception ex)
{
    LogTrace.TraceLine("Error re-starting process " + startInfo.FileName + ": " + ex, false);
}

Some other notes:

-I have tried are running the service with different users of varying permission levels. Running the service as an Administrator makes no difference.

-UAC is completely off.

-I have tried running the service in interactive mode in Session 0 on target PC using FireDaemon.

Anybody have any ideas on anything to look into?

Body:
snippet of a service starter to get you started

{
using System.ServiceProcess;
using...

namespace myServicenamespace
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] {
                new myService()
            };
            ServiceBase.Run(ServicesToRun);
        }
    }
}

myService defined elsewhere as the code you want to have running, including the

{
protected override void OnStart() {...}
protected override void OnStop {...}
}

Deployment of the service also differs, as mentioned check the rest of the documentation on ServiceProcess to see more.


来源: stackexchange

问:
Does minified JavaScript code improve performance?
I'm making an AIR application (so the download time doesn't have a huge impact). Does combining and minifing all the JavaScript files affect the performance? How would obfuscating affect the performance?</p>

答:
I'd like to post this as a separate answer as it somewhat contrasts the accepted one:

Yes, it does make a performance difference as it reduces parsing time - and that's often the critical thing. For me, it was even just simply linear in the size and I could get it from 12 seconds to 4 seconds parse time by minifying from 3 MB to 1 MB.

It's not a big application either. It just has a couple of reasonable dependencies.

So the moral of the story here is: Yes, minifying is important for performance - and not because of bandwidth, but because of parsing.

ContentLicense: CC BY-SA 4.0


问:
Create column based on condition in SQLite
I am trying to create a new column in a SQLite database from Python. I would like the column to be either 1 or 0 if a criteria is met. I have tried the following without success:

```<code>query = 'SELECT codes CASE WHEN codes LIKE 'X10' THEN 1 ELSE 0 END as I10X FROM processed_data'

cur.execute(query)
</code>```

Example data:

```<code>+--------------+
| codes   |    |
+--------------+
| X10, X11|    |
| x11, X9 |    |
| x10     |    |
| x13     |    |
+-------+------+
</code>```

Example target data:

```<code>+----------+-----+
| codes    | X10 |
+----------+-----+
| X10, X11 |   1 |
| x11, X9  |   0 |
| x10      |   0 |
| x13      |   0 |
| x10      |   1 |
+-------+--------+
</code>```

Can anyone suggest how to do this?

答:
do you want to project the data as you expecting or do you want actually create new column with the data itself.

first loop the rows and create the mapping column_codes,X10 mapping based on your criteria.
create the new column x10 when there is no such a column.
c.execute("alter table processed_data add column 'x10' 'INTEGER' default 0 ")

execute an update query for  column_codes,X10.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a new column in a SQLite database from Python. I would like the column to be either 1 or 0 if a criteria is met. I have tried the following without success:

query = 'SELECT codes CASE WHEN codes LIKE 'X10' THEN 1 ELSE 0 END as I10X FROM processed_data'

cur.execute(query)

Example data:

+--------------+
| codes   |    |
+--------------+
| X10, X11|    |
| x11, X9 |    |
| x10     |    |
| x13     |    |
+-------+------+

Example target data:

+----------+-----+
| codes    | X10 |
+----------+-----+
| X10, X11 |   1 |
| x11, X9  |   0 |
| x10      |   0 |
| x13      |   0 |
| x10      |   1 |
+-------+--------+

Can anyone suggest how to do this?


问:
Is consumer key and consumer secret Key dynamic?
I am trying to connect to twitter using RNTwitterSignIn (react-native).
But it always gives "internal server error orccured".

Access Token and Access Token Secret are generating, i would like to know, are consumer and consumer secret key dynamic or not?

答: No.  The Consumer Key and Consumer Key Secret are intended to be static.  You can re-generate them through the developer tools if you need new keys (during development or if the keys are compromised), but they are intended to be static.</p>


问:
change format of a column in a element of a list with lapply
I have a list of data.frames and I want to change the class of one column of the data.frame (from factor to date). I was trying to use lapply but then, the original list only contains that column (not the whole data.frame). I don't understand this behaviour..to solve this I use a common loop, but I was wondering if anyone could have any suggestion.
Let's say, as an example, I have this simple data:

```<code>       m1 <- data.frame("date"=c("2010-02-03","2010-01-05"),"value"=c(5,3))
       m2 <- data.frame("date"=c("2010-02-03","2010-01-05"),"value"=c(1,3))
       mylist <- list(m1,m2)
       #change date
       newlist <- lapply(mylist, function(x) as.Date(x$date))
</code>```

newlist will have only the date..
Is there any way to use lapply for that..I am working with large dataset, and usually lapply works fine, but in this case, I don't know what I'm doing wrong.

Many thanks.

答:
In your function you have to first change the date column and then return x

```<code>newlist <- lapply(mylist, function(x) {
    x$date <- as.Date(x$date)
    x
})
newlist
# [[1]]
#         date value
# 1 2010-02-03     5
# 2 2010-01-05     3
#
# [[2]]
#         date value
# 1 2010-02-03     1
# 2 2010-01-05     3
</code>```

Body:
I have a list of data.frames and I want to change the class of one column of the data.frame (from factor to date). I was trying to use lapply but then, the original list only contains that column (not the whole data.frame). I don't understand this behaviour..to solve this I use a common loop, but I was wondering if anyone could have any suggestion.
Let's say, as an example, I have this simple data:

       m1 <- data.frame("date"=c("2010-02-03","2010-01-05"),"value"=c(5,3))
       m2 <- data.frame("date"=c("2010-02-03","2010-01-05"),"value"=c(1,3))
       mylist <- list(m1,m2)
       #change date
       newlist <- lapply(mylist, function(x) as.Date(x$date))

newlist will have only the date..
Is there any way to use lapply for that..I am working with large dataset, and usually lapply works fine, but in this case, I don't know what I'm doing wrong.

Many thanks.

Body:
In your function you have to first change the date column and then return x

newlist <- lapply(mylist, function(x) {
    x$date <- as.Date(x$date)
    x
})
newlist
# [[1]]
#         date value
# 1 2010-02-03     5
# 2 2010-01-05     3
#
# [[2]]
#         date value
# 1 2010-02-03     1
# 2 2010-01-05     3


问:
Bash interpreting increment operation as command
I'm trying to batch modify some images using a bash script, and to print out the progress. It looks to me like bash is interpreting the increment to counter as a command and is giving the following error:

```<code>augment_data.sh: line 20: 0: command not found
</code>```

Here is the code:

```<code>for file in *.jpg
do
    convert $file -rotate 90 rotated_"$file"
    ((counter++))
    if $((counter % 10 == 0)); then
            echo "Rotated $counter files out of $num_files"
    fi
done
</code>```

with line 20 being the one with the counter increment operation.

How can I fix this so that I don't get the error message?

答:
In an arithmetic substitution, the result of an arithmetic operation is substituted in the position of the operation itself.

In this case, $(( 1 == 0 )) has an arithmetic result of 0, and $(( 1 == 1 )) has a result of 1.

Thus, if you use $(( ... )), then this 0 or 1 is substituted in that position, and so gets run as a command. Since you don't have commands named 0 or 1 (probably), either of these will result in a command not found error.

If you use (( ... )), then the arithmetic result directly sets return value, but no expansion takes place.

Body:
I'm trying to batch modify some images using a bash script, and to print out the progress. It looks to me like bash is interpreting the increment to counter as a command and is giving the following error:

augment_data.sh: line 20: 0: command not found

Here is the code:

for file in *.jpg
do
    convert $file -rotate 90 rotated_"$file"
    ((counter++))
    if $((counter % 10 == 0)); then
            echo "Rotated $counter files out of $num_files"
    fi
done

with line 20 being the one with the counter increment operation.

How can I fix this so that I don't get the error message?


问:
Explanation of BASE terminology
The BASE acronym is used to describe the properties of certain databases, usually NoSQL databases. It's often referred to as the opposite of ACID.

There are only few articles that touch upon the details of BASE, whereas ACID has plenty of articles that elaborate on each of the atomicity, consistency, isolation and durability properties. Wikipedia only devotes a few lines to the term.

This leaves me with some questions about the definition:

Basically Available, Soft state, Eventual consistency

I have interpreted these properties as follows, using this article and my imagination:

Basically available could refer to the perceived availability of the data. If a single node fails, part of the data won't be available, but the entire data layer stays operational.

Is this interpretation correct, or does it refer to something else?

Update: deducing from Mau's answer, could it mean the entire data layer is always accepting new data, i.e. there are no locking scenarios that prevent data from being inserted immediately?

Soft state: All I could find was the concept of data needing a period refresh. Without a refresh, the data will expire or be deleted.

Automatic deletion of data in a database seems strange to me.

Expired or stale data makes more sense. But this concept would apply to any type of redundant data storage, not just NoSQL. Does it describe something else then?

Eventual consistency means that updates will eventually ripple through to all servers, given enough time.

This property is clear to me.

Can someone explain these properties in detail?

Or is it just a far-fetched and meaningless acronym that refers to the concepts of acids and bases as found in chemistry?

答: It could just be because ACID is one set of properties that substances show( in Chemistry) and BASE is a complement set of them.So it could be just to show the contrast between the two that the acronym was made up and then 'Basically Available Soft State Eventual Consistency' was decided as it's full-form.</p>

ContentLicense: CC BY-SA 2.5

Title: Explanation of BASE terminology


答:
We can use transform

```<code>lapply(mylist, transform, date = as.Date(date))
</code>```

Title: change format of a column in a element of a list with lapply

Body:
We can use transform

lapply(mylist, transform, date = as.Date(date))


问:
C# Why do i keep getting an error exception in inserting a data in a database?
I created a table named as BUDGET_FINALTEST, and it just keeps on having an exception error whenever i run it in my button?

```<code>    SqlCommand cmd = new SqlCommand("insert into BUDGET_FINALTEST values (@EMPLOYEE_ID,@LAST_NAME,@FIRST_NAME,@DIVISION,@DATE_OF_BUDGET,@BUDGET)", con);
    cmd.Parameters.AddWithValue("@EMPLOYEE_ID", tbEmployeeID.Text);
    cmd.Parameters.AddWithValue("@LAST_NAME", tbLName.Text);
    cmd.Parameters.AddWithValue("@FIRST_NAME", tbFName.Text);
    cmd.Parameters.AddWithValue("@DIVISION", tbDivision.Text);
    cmd.Parameters.AddWithValue("@DATE_OF_BUDGET", dateTimePicker2.Value.Date);
    cmd.Parameters.AddWithValue("@BUDGET", tbBudget.Text);
    cmd.ExecuteNonQuery();
</code>```

An unhandled exception of type 'System.Data.SqlClient.SqlException'
  occured in System.Data.dll

Additional information: Column name or number of supplied values does
  not match table definition

答:
You have the wrong number of parameters, or they are on the wrong order.
Always specify the columns list in your insert statement.

That will prevent you from making mistakes like this, as well as keep your code valid even if new columns are added to the table.

```<code>"insert into BUDGET_FINALTEST values (@EMPLOYEE_ID,@LAST_NAME,@FIRST_NAME,@DIVISION,@DATE_OF_BUDGET,@BUDGET)"
</code>```

Should be

```<code>"insert into BUDGET_FINALTEST (EMPLOYEE_ID, LAST_NAME, FIRST_NAME, DIVISION, DATE_OF_BUDGET, BUDGET) values (@EMPLOYEE_ID,@LAST_NAME,@FIRST_NAME,@DIVISION,@DATE_OF_BUDGET,@BUDGET)"
</code>```

Body:
I created a table named as BUDGET_FINALTEST, and it just keeps on having an exception error whenever i run it in my button?

    SqlCommand cmd = new SqlCommand("insert into BUDGET_FINALTEST values (@EMPLOYEE_ID,@LAST_NAME,@FIRST_NAME,@DIVISION,@DATE_OF_BUDGET,@BUDGET)", con);
    cmd.Parameters.AddWithValue("@EMPLOYEE_ID", tbEmployeeID.Text);
    cmd.Parameters.AddWithValue("@LAST_NAME", tbLName.Text);
    cmd.Parameters.AddWithValue("@FIRST_NAME", tbFName.Text);
    cmd.Parameters.AddWithValue("@DIVISION", tbDivision.Text);
    cmd.Parameters.AddWithValue("@DATE_OF_BUDGET", dateTimePicker2.Value.Date);
    cmd.Parameters.AddWithValue("@BUDGET", tbBudget.Text);
    cmd.ExecuteNonQuery();

An unhandled exception of type 'System.Data.SqlClient.SqlException'
  occured in System.Data.dll

Additional information: Column name or number of supplied values does
  not match table definition

Body:
You have the wrong number of parameters, or they are on the wrong order.
Always specify the columns list in your insert statement.

That will prevent you from making mistakes like this, as well as keep your code valid even if new columns are added to the table.

"insert into BUDGET_FINALTEST values (@EMPLOYEE_ID,@LAST_NAME,@FIRST_NAME,@DIVISION,@DATE_OF_BUDGET,@BUDGET)"

Should be

"insert into BUDGET_FINALTEST (EMPLOYEE_ID, LAST_NAME, FIRST_NAME, DIVISION, DATE_OF_BUDGET, BUDGET) values (@EMPLOYEE_ID,@LAST_NAME,@FIRST_NAME,@DIVISION,@DATE_OF_BUDGET,@BUDGET)"


问:
22003 8115 error with overflow bigint id
My code runs fine in a single test. The id starts with 1 and increments by 1. However when I test the whole run in django, I've got this error.

For example, an id 601193234094856941 was inserted. In the whole run I have not more than 10000 inserts. This problem occurs in our development environment.

We have a work-around but we want to understand how it works and find a solution.

('22003', '[22003] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Arithmetic overflow error converting expression to data type int. (8115) (SQLExecDirectW)')",

All variables are bigint. The id above has been correctly inserted in the database but apparently the id reached a value above the max of a bigint with later inserts.

答:
Based on the information you've provided this seems to be what would be expected. the reference id 601193234094856941 exceeds the value for an INT type. The code below throws an error of "Arithmetic overflow error converting expression to data type int.". Do you have additional information to provide that might help address your issue?</p>

```<code>DECLARE @big       BIGINT = 601193234094856941
        , @regular INT;

SET @regular = @big;
</code>```

Body:
Based on the information you've provided this seems to be what would be expected. the reference id 601193234094856941 exceeds the value for an INT type. The code below throws an error of "Arithmetic overflow error converting expression to data type int.". Do you have additional information to provide that might help address your issue?

DECLARE @big       BIGINT = 601193234094856941
        , @regular INT;

SET @regular = @big;


问:
Urls with special characters are not converted correctly by SendGrid
I have a url in one of my emails for twitter share that looks like:

http://twitter.com/share?text=Praneeta%27s%20test&url=http%3A%2F%2Fwww.mydomain.com%3Fparam1%3D303%26param2%3Dtest&related=praneeta&via=Praneeta

However SendGrid converts only the part before the '  (encoded as %27)

So the url I have in the emails sent is broken and looks like

http://email.mydomain.com/wf/click?upn=<long_encoded_key>%27s%27s%20test&url=http%3A%2F%2Fwww.mydomain.com%3Fparam1%3D303%26param2%3Dtest&related=praneeta&via=Praneeta

Is there a work around for this?

note: If I copy the email html and send it to myself via putsmail, it works fine, it breaks only when it goes via Sendgrid.

答:
Just a heads up on this issue incase if people stumble on this.  The method should be escape for example:

CGI::escape('\'')


问:
Error when defining my own module as a virtual field in Ecto
Why can't I do this:

```<code>  defmodule M1 do
    defstruct [:a, :b, :c, :d]
    # other stuff
  end

  # ...............

  schema "my_model" do
    # .................
    field :my_field, M1, virtual: true
</code>```

Error

```<code>      ** (ArgumentError) invalid or unknown type MyApp.M1 for field :my_field
</code>```

The module M1 is resolved but why is it disallowed to use it?

答:
If you want to store an M1 struct in the field, you can disable Ecto's type checking by specifying the type to be :any, which will let you store anything at all in the field:

```<code>field :my_field, :any, virtual: true
</code>```

There's no way that I see to make Ecto check that the field is a struct of module M1 unless you implement Ecto.Type behaviour for that module.

Body:
Why can't I do this:

  defmodule M1 do
    defstruct [:a, :b, :c, :d]
    # other stuff
  end

  # ...............

  schema "my_model" do
    # .................
    field :my_field, M1, virtual: true

Error

      ** (ArgumentError) invalid or unknown type MyApp.M1 for field :my_field

The module M1 is resolved but why is it disallowed to use it?

Body:
If you want to store an M1 struct in the field, you can disable Ecto's type checking by specifying the type to be :any, which will let you store anything at all in the field:

field :my_field, :any, virtual: true

There's no way that I see to make Ecto check that the field is a struct of module M1 unless you implement Ecto.Type behaviour for that module.


问:
In c# how to prevent a class from being modified
Let's say I have an interface:

```<code>interface IPerson
{
   int Age { get; set; }
   string Name { get; set; }
   bool Alive { get; set; }
}
</code>```

and a Class:

```<code>public class Person : IPerson
{
   public int Age { get; set; }
   public string Name { get; set; }
}
</code>```

That would not compile since Person does not implement the Alive Property.

What I would like to know is if there is a way to have the same behaviour, if Person adds an extra property that is not found in its interface.

```<code>interface IPerson
{
   int Age { get; set; }
   string Name { get; set; }
}
</code>```

and a Class:

```<code>public class Person : IPerson
{
   public int Age { get; set; }
   public string Name { get; set; }
   public bool Alive { get; set; }  <---- This should prevent it from compiling as well.
}
</code>```

I would want it to not compile as well, or at the very least give me a compile warning.

答: There is a way to do this, but not within the object and its a bit silly to use in construction of the object.  Using Reflection, you can check the type of an instance of your object and iterate through its properties, throwing an exception if the count or names of properties do not match your desired instance.  Please note that if you just check against the interface, implementing objects will pass, so you would check against the desired concrete type.  I am on my phone or I'd add some sample code, will try to return to this later.

Body:
Let's say I have an interface:

interface IPerson
{
   int Age { get; set; }
   string Name { get; set; }
   bool Alive { get; set; }
}

and a Class:

public class Person : IPerson
{
   public int Age { get; set; }
   public string Name { get; set; }
}

That would not compile since Person does not implement the Alive Property.

What I would like to know is if there is a way to have the same behaviour, if Person adds an extra property that is not found in its interface.

interface IPerson
{
   int Age { get; set; }
   string Name { get; set; }
}

and a Class:

public class Person : IPerson
{
   public int Age { get; set; }
   public string Name { get; set; }
   public bool Alive { get; set; }  <---- This should prevent it from compiling as well.
}

I would want it to not compile as well, or at the very least give me a compile warning.


问:
UNION and LIMIT alone operations in MySQL one query?
I need to get these results

```<code>id   details
-----------------
 6   I am old car
 7   I am old car
 8   I am old car
 9   I am old car
10   I am old car
 6   I am New car
 7   I am New car
 8   I am New car
 9   I am New car
10   I am New car
</code>```

I use the MySQL query

```<code>SELECT Cars.details FROM Cars WHERE Old = 'Old'
LIMIT 5, 5
UNION
SELECT Cars.details FROM Cars WHERE New = 'New'
LIMIT 5, 5
</code>```

But I get the results from the new cars only.

The result starts from 1-5
Is it possible to get the desired result in groups of five, in both of these groups

Is there a possibility to split the query LIMIT but stay in one query?

答:
```<code>mysql> drop table if exists Cars;
Query OK, 0 rows affected (0.21 sec)

mysql> create table Cars (id int , details varchar(20),old varchar(3), new varchar(3));
Query OK, 0 rows affected (0.38 sec)

mysql> insert into Cars values
    -> ( 6 ,  'I am old car','old', null),
    -> (7  , 'I am old car','old', null),
    ->  (8  , 'I am old car','old', null),
    ->  (9 ,  'I am old car','old', null),
    -> (10  , 'I am old car','old', null),
    -> ( 6 ,  'I am New car',null, 'new'),
    -> ( 7  , 'I am New car',null, 'new'),
    -> (8  , 'I am New car',null, 'new'),
    -> ( 9 ,  'I am New car',null, 'new'),
    -> (10 ,  'I am New car',null, 'new');
Query OK, 10 rows affected (0.22 sec)
Records: 10  Duplicates: 0  Warnings: 0

mysql>
mysql> select * from
    -> (
    -> SELECT Cars.details FROM Cars WHERE Old = 'Old'
    -> LIMIT 0, 5
    -> ) a
    -> UNION all
    -> (
    -> SELECT Cars.details FROM Cars WHERE New = 'New'
    -> LIMIT 0, 5
    -> )
    -> ;
+--------------+
| details      |
+--------------+
| I am old car |
| I am old car |
| I am old car |
| I am old car |
| I am old car |
| I am New car |
| I am New car |
| I am New car |
| I am New car |
| I am New car |
+--------------+
10 rows in set (0.03 sec)
</code>```

Body:
I need to get these results

id   details
-----------------
 6   I am old car
 7   I am old car
 8   I am old car
 9   I am old car
10   I am old car
 6   I am New car
 7   I am New car
 8   I am New car
 9   I am New car
10   I am New car

I use the MySQL query

SELECT Cars.details FROM Cars WHERE Old = 'Old'
LIMIT 5, 5
UNION
SELECT Cars.details FROM Cars WHERE New = 'New'
LIMIT 5, 5

But I get the results from the new cars only.

The result starts from 1-5
Is it possible to get the desired result in groups of five, in both of these groups

Is there a possibility to split the query LIMIT but stay in one query?


问:
What is the rationale for limitations on pointer arithmetic or comparison?
In C/C++, addition or subtraction on pointer is defined only if the resulting pointer lies within the original pointed complete object. Moreover, comparison of two pointers can only be performed if the two pointed objects are subobjects of a unique complete object.

What are the reasons of such limitations?

I supposed that segmented memory model (see here §1.2.1) could be one of the reasons but since compilers can actually define a total order on all pointers as demonstrated by this answer, I am doubting this.

答:
The rationale is that some architectures have segmented memory, and pointers to different objects may point at different memory segments. The difference between the two pointers would then not necessarily be something meaningful.

This goes back all the way to pre-standard C. The C rationale doesn't mention this explicitly, but it hints at this being the reason, if we look where it explains the rationale why using a negative array index is undefined behavior (C99 rationale 5.10 6.5.6, emphasis mine):

In the case of p-1, on the other hand, an entire object would have to be allocated prior to the
  array of objects that p traverses, so decrement loops that run off the bottom of an array can fail.
  This restriction allows segmented architectures, for instance, to place objects at the start of a
  range of addressable memory.


问:
Adding variables in query the right way
Why do this..

```<code>$fruit_type = "banana";
mysql_real_escape_string($fruit_type);

$query = "SELECT * FROM posts WHERE fruit = " . $fruit_type . ";
</code>```

when you can do this..

```<code>$fruit_type = "banana";
mysql_real_escape_string($fruit_type);

$query = "SELECT * FROM posts WHERE fruit = $fruit_type;
</code>```

I know that integers should be encapsulated in single quotes but is it fine to add a variable that contains a string directly?

答:
To late but it will help others
`

```<code>$table ="table_Name";
$idx="value";
$sql="SELECT * FROM $table WHERE row_name= '$idx'";
</code>```

`
execute your query .

Title: Adding variables in query the right way

Body:
Why do this..

$fruit_type = "banana";
mysql_real_escape_string($fruit_type);

$query = "SELECT * FROM posts WHERE fruit = " . $fruit_type . ";

when you can do this..

$fruit_type = "banana";
mysql_real_escape_string($fruit_type);

$query = "SELECT * FROM posts WHERE fruit = $fruit_type;

I know that integers should be encapsulated in single quotes but is it fine to add a variable that contains a string directly?

Body:
To late but it will help others
`

$table ="table_Name";
$idx="value";
$sql="SELECT * FROM $table WHERE row_name= '$idx'";

`
execute your query .


问:
what is equivalent of Postgresql to dbms_stats.gather_table_stats in Oracle?
I have some question about Postgres, I have used dbms_stats.gather_table_stats for performance optimization in Oracle. I would like to switch our database from Oracle to Postgres, therefore, I want to achieve same feature on Postgres also. I searched internet whether there is some equivalent feature existing in Postgres with dbms_stats.gather_table_stats in Oracle. The only I found was EXPLAIN, VACUUM something like that. I think these are already existing in Oracle with same name. but I can't find proper ones for dbms_stats.gather_table_stats. I am spedning a lot time on it, if you guys have some advice, could I get some?</p>

答:
The GATHER_TABLE_STATS procedure of DBMS_STATS package collects statistics of the specified table in Oracle.

In Postgres, we use ANALYZE for the same purpose.

ANALYZE collects statistics about the contents of tables in the database, and stores the results in the pg_statistic system catalog. Subsequently, the query planner uses these statistics to help determine the most efficient execution plans for queries.


问:
R Dataframe : Date range Operations - Subset those rows which falls under a certain date range
If you see my profile, all my questions are on dataframes and here is another!

I have a certain dataframe which is a result of a merge between Debit and Credit transactions

```<code>>head(allTxns)
   Cust_no    CreditDate   Credit     DebitDate   Debit
 1  12345     2014-10-01    200      2014-10-03    400
 2  12345     2014-10-01    200      2014-10-04    150
 3  12345     2014-10-01    200      2014-10-15    800
 4  33344     2014-10-03    500      2014-10-04    50
 5  33344     2014-10-03    500      2014-10-05    504
 6  33344     2014-10-03    500      2014-10-06    332
 7  33344     2014-10-03    500      2014-10-08    56
 8  66554     2014-10-10    660      2014-10-04    150
 9  66554     2014-10-10    660      2014-10-05    800
10  66554     2014-10-10    660      2014-10-11    400
11  66554     2014-10-10    660      2014-10-12    150
12  66554     2014-10-10    660      2014-10-13    800
</code>```

My aim is to get those rows, where the DebitDate lies between 5 days of the CreditDate and hence I tried to subset the data, where I put the date range using the : operator

```<code>FiveDays <- allTxns$CreditDate+5 #Results in a vector which has date + 5 days

allTxns <- cbind(allTxns[1:2],FiveDays,allTxns[4:6]) #Adding the vector as a column of dataframe

newDf <- allTxns[allTxns$DebitDate %in% allTxns$CreditDate:allTxns$FiveDays]
</code>```

In the above code, I'm getting the following logical error where only the first element is being used

```<code>Warning messages:
  1: In mer32$DepositDate:mer32$FiveDays2 :
      numerical expression has 3994 elements: only the first used
  2: In mer32$DepositDate:mer32$FiveDays2 :
      numerical expression has 3994 elements: only the first used
</code>```

Hence my required output is getting limited only to the first Cust_no (12345) and not being applied to other rows. How do I make sure that the range condition gets applied to ALL the rows??

Incorrect Output

```<code> >head(newDf)
 row.names  Cust_no    CreditDate   Credit     DebitDate   Debit
     1      12345     2014-10-01    200      2014-10-03    400
     2      12345     2014-10-01    200      2014-10-04    150
     4      33344     2014-10-03    500      2014-10-04    50
     5      33344     2014-10-03    500      2014-10-05    504
     6      33344     2014-10-03    500      2014-10-06    332
     7      33344     2014-10-03    500      2014-10-08    56
     8      66554     2014-10-10    660      2014-10-04    150
     9      66554     2014-10-10    660      2014-10-05    800
    10      66554     2014-10-10    660      2014-10-11    400
    11      66554     2014-10-10    660      2014-10-12    150
    12      66554     2014-10-10    660      2014-10-13    800
</code>```

Correct Output

```<code> >head(newDf)
 row.names  Cust_no    CreditDate   Credit     DebitDate   Debit
     1      12345     2014-10-01    200      2014-10-03    400
     2      12345     2014-10-01    200      2014-10-04    150
     4      33344     2014-10-03    500      2014-10-04    50
     5      33344     2014-10-03    500      2014-10-05    504
     6      33344     2014-10-03    500      2014-10-06    332
     7      33344     2014-10-03    500      2014-10-08    56
    10      66554     2014-10-10    660      2014-10-11    400
    11      66554     2014-10-10    660      2014-10-12    150
    12      66554     2014-10-10    660      2014-10-13    800
</code>```

Body:
If you see my profile, all my questions are on dataframes and here is another!

I have a certain dataframe which is a result of a merge between Debit and Credit transactions

>head(allTxns)
   Cust_no    CreditDate   Credit     DebitDate   Debit
 1  12345     2014-10-01    200      2014-10-03    400
 2  12345     2014-10-01    200      2014-10-04    150
 3  12345     2014-10-01    200      2014-10-15    800
 4  33344     2014-10-03    500      2014-10-04    50
 5  33344     2014-10-03    500      2014-10-05    504
 6  33344     2014-10-03    500      2014-10-06    332
 7  33344     2014-10-03    500      2014-10-08    56
 8  66554     2014-10-10    660      2014-10-04    150
 9  66554     2014-10-10    660      2014-10-05    800
10  66554     2014-10-10    660      2014-10-11    400
11  66554     2014-10-10    660      2014-10-12    150
12  66554     2014-10-10    660      2014-10-13    800

My aim is to get those rows, where the DebitDate lies between 5 days of the CreditDate and hence I tried to subset the data, where I put the date range using the : operator

FiveDays <- allTxns$CreditDate+5 #Results in a vector which has date + 5 days

allTxns <- cbind(allTxns[1:2],FiveDays,allTxns[4:6]) #Adding the vector as a column of dataframe

newDf <- allTxns[allTxns$DebitDate %in% allTxns$CreditDate:allTxns$FiveDays]

In the above code, I'm getting the following logical error where only the first element is being used

Warning messages:
  1: In mer32$DepositDate:mer32$FiveDays2 :
      numerical expression has 3994 elements: only the first used
  2: In mer32$DepositDate:mer32$FiveDays2 :
      numerical expression has 3994 elements: only the first used

Hence my required output is getting limited only to the first Cust_no (12345) and not being applied to other rows. How do I make sure that the range condition gets applied to ALL the rows??

Incorrect Output

 >head(newDf)
 row.names  Cust_no    CreditDate   Credit     DebitDate   Debit
     1      12345     2014-10-01    200      2014-10-03    400
     2      12345     2014-10-01    200      2014-10-04    150
     4      33344     2014-10-03    500      2014-10-04    50
     5      33344     2014-10-03    500      2014-10-05    504
     6      33344     2014-10-03    500      2014-10-06    332
     7      33344     2014-10-03    500      2014-10-08    56
     8      66554     2014-10-10    660      2014-10-04    150
     9      66554     2014-10-10    660      2014-10-05    800
    10      66554     2014-10-10    660      2014-10-11    400
    11      66554     2014-10-10    660      2014-10-12    150
    12      66554     2014-10-10    660      2014-10-13    800

Correct Output

 >head(newDf)
 row.names  Cust_no    CreditDate   Credit     DebitDate   Debit
     1      12345     2014-10-01    200      2014-10-03    400
     2      12345     2014-10-01    200      2014-10-04    150
     4      33344     2014-10-03    500      2014-10-04    50
     5      33344     2014-10-03    500      2014-10-05    504
     6      33344     2014-10-03    500      2014-10-06    332
     7      33344     2014-10-03    500      2014-10-08    56
    10      66554     2014-10-10    660      2014-10-11    400
    11      66554     2014-10-10    660      2014-10-12    150
    12      66554     2014-10-10    660      2014-10-13    800

Body:
This old questions already has an accepted answer. However, I noted that question and answer can be streamlined as it is not necessary to create the additional FiveDays column:

allTxns[with(allTxns, CreditDate <= DebitDate & DebitDate <= CreditDate + 5L), ]

   Cust_no CreditDate Credit  DebitDate Debit
1    12345 2014-10-01    200 2014-10-03   400
2    12345 2014-10-01    200 2014-10-04   150
4    33344 2014-10-03    500 2014-10-04    50
5    33344 2014-10-03    500 2014-10-05   504
6    33344 2014-10-03    500 2014-10-06   332
7    33344 2014-10-03    500 2014-10-08    56
10   66554 2014-10-10    660 2014-10-11   400
11   66554 2014-10-10    660 2014-10-12   150
12   66554 2014-10-10    660 2014-10-13   800


问:
How to serve another repos built files from NodeJS?
I have two repos:

A Vue client interface;

A NodeJS socket and web server.

I need to serve the built files of the Vue interface with the server and don't know how to proceed...

I have two ideas of how to solve this:

Create a script that would clone the Vue repo, build it and move the
builded files in a folder server by the server.

Declare the Vue repo as a dependency of the server and find a way to
build and access to the dependency files.

The second one seems cleaner but I don't know how to begin approaching this. Could someone please provide some thoughts on the better approach and how I might get started?

答:
Here's how I do it with Express:

```<code>const express = require("express"),
      path = require("path"),
      app = express()

const DIST_DIR = path.normalize(__dirname + "/../../VueOutputDir")

app.use(express.static(DIST_DIR))
</code>```

This will automatically serve the index.html and the assets from the VueOutputDir directory.

Body:
Here's how I do it with Express:

const express = require("express"),
      path = require("path"),
      app = express()

const DIST_DIR = path.normalize(__dirname + "/../../VueOutputDir")

app.use(express.static(DIST_DIR))

This will automatically serve the index.html and the assets from the VueOutputDir directory.


问:
Are the unit test classes in ASP.NET MVC web project a good example?
I'm learning TDD. I know about dependency injection whereby you place the class's dependencies in the constructor's parameters and have them passed in, passing in default implementations from the default constructor eg;

```<code>public AccountController() : this( RepositoryFactory.Users())
{
}

public AccountController( IUserRepository oUserRepository)
{
 m_oUserRepository = oUserRepository;
}
</code>```

RepositoryFactory is a simple static class that returns the chosen implementations for the current build

But the default ASP.NET MVC web app project doesn't do this, instead the DI takes the form of public properties that are assigned in the object initializer in the test class eg; from AccountController.cs :

```<code>protected override void Initialize(RequestContext requestContext)
{
 if (FormsService == null)
  { FormsService = new FormsAuthenticationService(); }
 if (MembershipService == null)
  { MembershipService = new AccountMembershipService(); }

 base.Initialize(requestContext);
}
</code>```

And in the test class AccountControllerTest.cs :

```<code>private static AccountController GetAccountController()
{
 AccountController controller = new AccountController()
 {
  FormsService = new MockFormsAuthenticationService(),
  MembershipService = new MockMembershipService(),
  Url = new UrlHelper(requestContext),
 };
 //snip
}
</code>```

So now my AccountController class has two approaches to dependency injection. Which one should I use? Constructor injection or public properties?

Am thinking constructor injection...

Is the ASP.NET MVC use of public properties like that because you need to provide a specific way of injecting into the constructor, and the basic "create new" web app needs to be generic as a starting point?

答: Take a look at structuremap.  You are correct...constructor injection is the preferred method of DI/IoC.  Check out this article by Martin Fowler.  Hope this helps you.</p>

Body:
I'm learning TDD. I know about dependency injection whereby you place the class's dependencies in the constructor's parameters and have them passed in, passing in default implementations from the default constructor eg;

public AccountController() : this( RepositoryFactory.Users())
{
}

public AccountController( IUserRepository oUserRepository)
{
 m_oUserRepository = oUserRepository;
}

RepositoryFactory is a simple static class that returns the chosen implementations for the current build

But the default ASP.NET MVC web app project doesn't do this, instead the DI takes the form of public properties that are assigned in the object initializer in the test class eg; from AccountController.cs :

protected override void Initialize(RequestContext requestContext)
{
 if (FormsService == null)
  { FormsService = new FormsAuthenticationService(); }
 if (MembershipService == null)
  { MembershipService = new AccountMembershipService(); }

 base.Initialize(requestContext);
}

And in the test class AccountControllerTest.cs :

private static AccountController GetAccountController()
{
 AccountController controller = new AccountController()
 {
  FormsService = new MockFormsAuthenticationService(),
  MembershipService = new MockMembershipService(),
  Url = new UrlHelper(requestContext),
 };
 //snip
}

So now my AccountController class has two approaches to dependency injection. Which one should I use? Constructor injection or public properties?

Am thinking constructor injection...

Is the ASP.NET MVC use of public properties like that because you need to provide a specific way of injecting into the constructor, and the basic "create new" web app needs to be generic as a starting point?


问:
Extracting data from documents stored in HDFS to index in Elasticsearch
I have a HDFS archive to store variety of documents like pdf,ms word file,ppt,csv etc. I would like to build a platform using elasticsearch to search the file or text contents. I know I can use the es-hadoop plugin to index data to from HDFS to ES. I want to know the best ways that I can extract out the textual data from the docs stored in HDFS and index the same.

Any help would be appreciated.

答:
I did a lot of searching, and this is the list of methods I've found so far.

Here's the overall integrations/plugins page:
https://www.elastic.co/guide/en/elasticsearch/plugins/master/integrations.html

Here's the new replacement for mapper attachment, Injest plugin:
https://www.elastic.co/guide/en/elasticsearch/plugins/current/ingest-attachment.html
A posting on how to use it:  https://qbox.io/blog/index-attachments-files-elasticsearch-mapper
Here's a discussion on pros and cons of using Injest vs fs-crawler (dadoonet is an Elastic developer):
https://discuss.elastic.co/t/mapper-attachment-plugin-vs-pre-parsing-and-extracting-content-from-binary-files/73764/10

Here is the file system crawler (FS crawler) plugin:
https://github.com/dadoonet/fscrawler

Here is Ambar document search system - they have a community github with open source code:
https://ambar.cloud/
https://github.com/RD17/ambar
https://blog.ambar.cloud/ingesting-documents-pdf-word-txt-etc-into-elasticsearch/
They seem to use two database server types (MongoDB and Redis), not sure why yet.

Here is Apache Tika, which Injest and Ambar both use (and which also offers OCR through the use of Tesseract, which I have heard Injest does not support):
http://tika.apache.org/1.16/

Also, in Injest's usage of Tika, only a subset of file types are supported:
https://discuss.elastic.co/t/full-list-of-supported-document-formats-by-es/81149

I hope that the above saves other developers time and if people find more that they will comment below.

Thanks!


答: There is a way to do this, but not within the object and its a bit silly to use in construction of the object.  Using Reflection, you can check the type of an instance of your object and iterate through its properties, throwing an exception if the count or names of properties do not match your desired instance.  Please note that if you just check against the interface, implementing objects will pass, so you would check against the desired concrete type.   I'm on my phone so no sample code.  Will try to return to this later.

Title: In c# how to prevent a class from being modified


问:
How to set the variables as integers in a Genetic Algorithm Function in GA package in R
Have a look at documentation of GA package in R

ftp://cran.r-project.org/pub/R/web/packages/GA/GA.pdf

答:
The only solution I have found so far is to use a ceiling, floor, or round function in order to convert the decimal value to an integer within the fitness function--before passing it to the actual function being optimized.

This, however, slows down the GA function greatly.

There is another genetic algorithm that might be useful if you only wish to use integers. It is called GeneticAlg.int from the gramEvol package.


问:
display data js from datebase sql
I would like to push my value of textbox to sql and then display it.
I read a lot topics but still nothing. I have always problem to explain my problems but I hope u will see what i want to do escpecialy when u look at db2.php

```<code>    $("#send").click(function(){

    var username = "<span class ='username' = >Klient: </span>";
    var newMessage = $("#textbox").val();
    nw = newMessage;
    $.ajax({
    type: "POST",
    url: "db2.php",
    data: {'name': nw },
    success: function (json) {
        jss = json.PYT;
        oss = json.ODP;
        console.log(jss);
    }

});
    $("#textbox").val("");

    var prevState = $("#container").html();

    if( prevState.length > 3){
        prevState = prevState + "<br>";
        }

        $("#container").html(prevState + username + newMessage);

        $("#container").scrollTop($("#container").prop("scrollHeight"));

        ai(newMessage);

    });
</code>```

and my db2.php .

```<code><?php
header('Content-type: application/json');
include 'connect.php';

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

$name = $_POST['name'];
$queryResult = $connect->query("select * from Chatbot where '$name' LIKE
CONCAT('%',PYT,'%')");
$result = array();
while($pomoc = $queryResult->fetch_assoc()){
    $result[] = $pomoc;
}
}

echo json_encode($result);
</code>```

Now my result is {}, echo is null.

console.log(nw)
VM289:1 dsasa
undefined
I know how to get just output from ajax but if i want to push this data everything goes wrong. Best regards

UPDATE. Now I would like to get jss value out of this function to the other one.

```<code>   var jss = {}; //(first line code)

    $("#send").click(function(){

    var username = "<span class ='username' = >Klient: </span>";
    var newMessage = $("#textbox").val();
    nw = newMessage;
$.ajax({
type: 'POST',
url: 'db2.php',
data: {
    'name': nw,
},
success: function(data){
   jss = data[0].PYT;

}
});
</code>```

UPDATE 2

```<code>var jss2 = {};
var nw;

$(function(){

username();

$("#textbox").keypress(function(event){
if ( event.which == 13) {
    if ( $("#enter").prop("checked") ){

        $("#send").click();
        event.preventDefault();
        }
    }
});
$("#send").click(function(){

    var username = "<span class ='username' = >Klient: </span>";
    var newMessage = $("#textbox").val();

    $("#textbox").val("");

    var prevState = $("#container").html();

    if( prevState.length > 3){
        prevState = prevState + "<br>";
        }

        $("#container").html(prevState + username + newMessage);

        $("#container").scrollTop($("#container").prop("scrollHeight"));

        ai(newMessage);

    });

})

function send_message(message){

    var prevState = $("#container").html();

    if(prevState.length > 3){
    prevState = prevState + "<br>";
    }

    $("#container").html(prevState + "<span class = 'bot'>Chatbot: </span>" + message);
}
function username(){
    $("#container").html("<span class = 'bot'>Chatbot: </span>Hi!");
}
function myFunction() {
var x = document.getElementById("textbox").value;

}

function ai(message){
    var jss;
    message = message.toLowerCase();
    nw = message;

    $.ajax({
type: 'POST',
url: 'db2.php',
data: {
    'name': nw,
},
success: function(data){
   jss = data[0].PYT;

}
});

console.log(jss);
    if ((message.indexOf(jss)>=0) || (message.indexOf("?")>=0)){
    send_message(Answer);
    return;
    }

    else{
    send_message("Nope ");
    }

}
</code>```

答:
I think this is what you need to do with your function so that you can use the jss variable properly, once the ajax request has completed:

```<code>function ai(message){
  var jss;
  message = message.toLowerCase();
  nw = message;

  $.ajax({
    type: 'POST',
    url: 'db2.php',
    data: {
      'name': nw,
    },
    success: function(data){
      jss = data[0].PYT;
      console.log(jss);
      if ((message.indexOf(jss)>=0) || (message.indexOf("?")>=0)){
        send_message(Answer);
        return;
      }
      else{
        send_message("Nope ");
      }
    }
  });
}
</code>```

Any code which relies on the jss variable must not be executed until after the ajax call has completed. Since ajax calls run asynchronously, the only way to guarantee this is for that code to be included in (or triggered from) the "success" callback function in your ajax request.

Title: display data js from datebase sql

Body:
I would like to push my value of textbox to sql and then display it.
I read a lot topics but still nothing. I have always problem to explain my problems but I hope u will see what i want to do escpecialy when u look at db2.php

    $("#send").click(function(){

    var username = "Klient: ";
    var newMessage = $("#textbox").val();
    nw = newMessage;
    $.ajax({
    type: "POST",
    url: "db2.php",
    data: {'name': nw },
    success: function (json) {
        jss = json.PYT;
        oss = json.ODP;
        console.log(jss);
    }

});
    $("#textbox").val("");

    var prevState = $("#container").html();

    if( prevState.length > 3){
        prevState = prevState + "
";
        }

        $("#container").html(prevState + username + newMessage);

        $("#container").scrollTop($("#container").prop("scrollHeight"));

        ai(newMessage);

    });

and my db2.php .

<?php
header('Content-type: application/json');
include 'connect.php';

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

$name = $_POST['name'];
$queryResult = $connect->query("select * from Chatbot where '$name' LIKE
CONCAT('%',PYT,'%')");
$result = array();
while($pomoc = $queryResult->fetch_assoc()){
    $result[] = $pomoc;
}
}

echo json_encode($result);

Now my result is {}, echo is null.

console.log(nw)
VM289:1 dsasa
undefined
I know how to get just output from ajax but if i want to push this data everything goes wrong. Best regards

UPDATE. Now I would like to get jss value out of this function to the other one.

   var jss = {}; //(first line code)

    $("#send").click(function(){

    var username = "Klient: ";
    var newMessage = $("#textbox").val();
    nw = newMessage;
$.ajax({
type: 'POST',
url: 'db2.php',
data: {
    'name': nw,
},
success: function(data){
   jss = data[0].PYT;

}
});

UPDATE 2

var jss2 = {};
var nw;

$(function(){

username();

$("#textbox").keypress(function(event){
if ( event.which == 13) {
    if ( $("#enter").prop("checked") ){

        $("#send").click();
        event.preventDefault();
        }
    }
});
$("#send").click(function(){

    var username = "Klient: ";
    var newMessage = $("#textbox").val();

    $("#textbox").val("");

    var prevState = $("#container").html();

    if( prevState.length > 3){
        prevState = prevState + "
";
        }

        $("#container").html(prevState + username + newMessage);

        $("#container").scrollTop($("#container").prop("scrollHeight"));

        ai(newMessage);

    });

})

function send_message(message){

    var prevState = $("#container").html();

    if(prevState.length > 3){
    prevState = prevState + "
";
    }

    $("#container").html(prevState + "Chatbot: " + message);
}
function username(){
    $("#container").html("Chatbot: Hi!");
}
function myFunction() {
var x = document.getElementById("textbox").value;

}

function ai(message){
    var jss;
    message = message.toLowerCase();
    nw = message;

    $.ajax({
type: 'POST',
url: 'db2.php',
data: {
    'name': nw,
},
success: function(data){
   jss = data[0].PYT;

}
});

console.log(jss);
    if ((message.indexOf(jss)>=0) || (message.indexOf("?")>=0)){
    send_message(Answer);
    return;
    }

    else{
    send_message("Nope ");
    }

}

Body:
I think this is what you need to do with your function so that you can use the jss variable properly, once the ajax request has completed:

function ai(message){
  var jss;
  message = message.toLowerCase();
  nw = message;

  $.ajax({
    type: 'POST',
    url: 'db2.php',
    data: {
      'name': nw,
    },
    success: function(data){
      jss = data[0].PYT;
      console.log(jss);
      if ((message.indexOf(jss)>=0) || (message.indexOf("?")>=0)){
        send_message(Answer);
        return;
      }
      else{
        send_message("Nope ");
      }
    }
  });
}

Any code which relies on the jss variable must not be executed until after the ajax call has completed. Since ajax calls run asynchronously, the only way to guarantee this is for that code to be included in (or triggered from) the "success" callback function in your ajax request.


问:
Multilocale computation on bigint array

I'm using Chapel and I'm trying to perform a computation on a bigint array in a multilocale setup. A file containing one integer per line is read. Each line is converted to a bigint record which is then inserted to a single array. I have 4 locales and I therefore ask each locale to read only 1/4th of the input file and process only that part.

I have reduced my problem to the following minimal example which is also affected:

```<code>module Hello {

use BigInteger;
use Math;
use Time;

config const inputPath = "/path/to/file";
config const inputSize = 10000000;
config const power = 2000;

proc dwriteln(args ...?n) {
        var curr = getCurrentTime(unit=TimeUnits.seconds);
        writeln("[ ", here.id, ": ", here.name, " ] [ ", curr, " ] ", (...args));
}

proc main() throws {
    writeln("Input path: ", inputPath);
    writeln("numLocales: ", numLocales);

    var elementsPerLocale = divceil(inputSize, numLocales);
    writeln("elementsPerLocale: ", elementsPerLocale);

    coforall loc in Locales {
        on loc {
            dwriteln("hello");
            var inputFile = open(inputPath, iomode.r, hints=IOHINT_CACHED);
            var reader = inputFile.reader();
            var startI = here.id * elementsPerLocale;
            var endI = startI+elementsPerLocale;
            dwriteln("startI = ", startI, " endI= ", endI);

            var a: [1..0] bigint;
            var i = 0;
            for line in reader.lines() {
                    // i in [startI;endI[
                    if i >= startI && i < endI {
                        a.push_back(new bigint(line, 16));
                    }
                    i +=1;
            }

            reader.close();
            inputFile.close();

            dwriteln("created array of size: ", a.size);

            forall elem in a {
                // perform some computation
                elem = elem ** power;
            }
            dwriteln("Computed.");
        }
    }

}

}
</code>```

I expect locales to perform the operations in parallel but this is not the case.

However when running the code it appears that each locale does its processing sequentially. In other words, locale 0 reads the file, does its processing, then locale 1 reads the file and does its processing, and so on. What could be the cause of this?

答:
Chapel grants concurrent & parallel I/O-operations:

I/O Overview

A file in Chapel identifies a file in the underlying operating system. Reads and writes to a file are done via one or more channels associated with the file. Each channel uses a buffer to provide sequential read or write access to its file, optionally starting at an offset.

Design Rationale

Since channels operate independently, concurrent I/O to the same open file is possible without contending for locks. Furthermore, since the channel (and not the file) stores the current file offset, it is straightforward to create programs that access the same open file in parallel. Note that such parallel access is not possible in C when multiple threads are using the same FILE* to write to different regions of a file because of the race condition between fseek and fwrite. Because of these issues, Chapel programmers wishing to perform I/O will need to know how to open files as well as create channels.

Yet, IO module details may help to better arrange resources:

As documented,

The default value of the iohints type is undefined.

  ...

  proc open( out
                error: syserr,
                path:  string = "",
                mode:  iomode,
                hints: iohints = IOHINT_NONE,
                style: iostyle = defaultIOStyle(),
                url:   string  = ""
                ): file

Re-run the experiment with non-default, rather explicit setups, where I/O hints better reflect the intended multi-locale processing with ~ IOHINT_PARALLEL.

Due to the nature of for line in reader.lines() {...} ad-hoc iterator, also might be interested in reviewing the experiment's throughput with tweaked IO intents with IOHINT_CACHED and IOHINT_SEQUENTIAL settings or the openreader() channel specific instrumentation.

A value of the iohints type defines a set of hints about the I/O that the file or channel will perform. These hints may be used by the implementation to select optimized versions of the I/O operations.

The  iohints type is implementation-defined. The following  iohints constants are provided:

```<code>  *  IOHINT_NONE       defines an empty set, which provides no hints.
  *  IOHINT_RANDOM     suggests to expect random access.
  *  IOHINT_SEQUENTIAL suggests to expect sequential access.
  *  IOHINT_CACHED     suggests that the file data is or should be cached
                       in memory, possibly all at once.
  *  IOHINT_PARALLEL   suggests to expect many channels working with this file
                       in parallel.
</code>```

Title: Multilocale computation on bigint array

Body:
I'm using Chapel and I'm trying to perform a computation on a bigint array in a multilocale setup. A file containing one integer per line is read. Each line is converted to a bigint record which is then inserted to a single array. I have 4 locales and I therefore ask each locale to read only 1/4th of the input file and process only that part.

I have reduced my problem to the following minimal example which is also affected:

module Hello {

use BigInteger;
use Math;
use Time;

config const inputPath = "/path/to/file";
config const inputSize = 10000000;
config const power = 2000;

proc dwriteln(args ...?n) {
        var curr = getCurrentTime(unit=TimeUnits.seconds);
        writeln("[ ", here.id, ": ", here.name, " ] [ ", curr, " ] ", (...args));
}

proc main() throws {
    writeln("Input path: ", inputPath);
    writeln("numLocales: ", numLocales);

    var elementsPerLocale = divceil(inputSize, numLocales);
    writeln("elementsPerLocale: ", elementsPerLocale);

    coforall loc in Locales {
        on loc {
            dwriteln("hello");
            var inputFile = open(inputPath, iomode.r, hints=IOHINT_CACHED);
            var reader = inputFile.reader();
            var startI = here.id * elementsPerLocale;
            var endI = startI+elementsPerLocale;
            dwriteln("startI = ", startI, " endI= ", endI);

            var a: [1..0] bigint;
            var i = 0;
            for line in reader.lines() {
                    // i in [startI;endI[
                    if i >= startI && i < endI {
                        a.push_back(new bigint(line, 16));
                    }
                    i +=1;
            }

            reader.close();
            inputFile.close();

            dwriteln("created array of size: ", a.size);

            forall elem in a {
                // perform some computation
                elem = elem ** power;
            }
            dwriteln("Computed.");
        }
    }

}

}

I expect locales to perform the operations in parallel but this is not the case.

However when running the code it appears that each locale does its processing sequentially. In other words, locale 0 reads the file, does its processing, then locale 1 reads the file and does its processing, and so on. What could be the cause of this?

Body:
Chapel grants concurrent & parallel I/O-operations:

I/O Overview

A file in Chapel identifies a file in the underlying operating system. Reads and writes to a file are done via one or more channels associated with the file. Each channel uses a buffer to provide sequential read or write access to its file, optionally starting at an offset.

Design Rationale

Since channels operate independently, concurrent I/O to the same open file is possible without contending for locks. Furthermore, since the channel (and not the file) stores the current file offset, it is straightforward to create programs that access the same open file in parallel. Note that such parallel access is not possible in C when multiple threads are using the same FILE* to write to different regions of a file because of the race condition between fseek and fwrite. Because of these issues, Chapel programmers wishing to perform I/O will need to know how to open files as well as create channels.

Yet, IO module details may help to better arrange resources:

As documented,

The default value of the iohints type is undefined.

  ...

  proc open( out
                error: syserr,
                path:  string = "",
                mode:  iomode,
                hints: iohints = IOHINT_NONE,
                style: iostyle = defaultIOStyle(),
                url:   string  = ""
                ): file

Re-run the experiment with non-default, rather explicit setups, where I/O hints better reflect the intended multi-locale processing with ~ IOHINT_PARALLEL.

Due to the nature of for line in reader.lines() {...} ad-hoc iterator, also might be interested in reviewing the experiment's throughput with tweaked IO intents with IOHINT_CACHED and IOHINT_SEQUENTIAL settings or the openreader() channel specific instrumentation.

A value of the iohints type defines a set of hints about the I/O that the file or channel will perform. These hints may be used by the implementation to select optimized versions of the I/O operations.

The  iohints type is implementation-defined. The following  iohints constants are provided:

  *  IOHINT_NONE       defines an empty set, which provides no hints.
  *  IOHINT_RANDOM     suggests to expect random access.
  *  IOHINT_SEQUENTIAL suggests to expect sequential access.
  *  IOHINT_CACHED     suggests that the file data is or should be cached
                       in memory, possibly all at once.
  *  IOHINT_PARALLEL   suggests to expect many channels working with this file
                       in parallel.


问:
Download large file with node.js avoiding high memory consumption
I`m trying to create a file downloader as a background service but when a large file is scheduled, it's first put in memory and then, at the end of the download the file is written to disk.

How can I make the file be wrote gradually to the disk preserving memory considering that I may have lots of files being downloaded at the same time?

Here's the code I`m using:

```<code>var sys = require("sys"),
    http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs"),
    events = require("events");

var downloadfile = "http://nodejs.org/dist/node-v0.2.6.tar.gz";

var host = url.parse(downloadfile).hostname
var filename = url.parse(downloadfile).pathname.split("/").pop()

var theurl = http.createClient(80, host);
var requestUrl = downloadfile;
sys.puts("Downloading file: " + filename);
sys.puts("Before download request");
var request = theurl.request('GET', requestUrl, {"host": host});
request.end();

var dlprogress = 0;

setInterval(function () {
   sys.puts("Download progress: " + dlprogress + " bytes");
}, 1000);

request.addListener('response', function (response) {
    response.setEncoding('binary')
    sys.puts("File size: " + response.headers['content-length'] + " bytes.")
    var body = '';
    response.addListener('data', function (chunk) {
        dlprogress += chunk.length;
        body += chunk;
    });
    response.addListener("end", function() {
        fs.writeFileSync(filename, body, 'binary');
        sys.puts("After download finished");
    });

});
</code>```

答: Instead of holding the content into memory in the "data" event listener you should write to the file in append mode.

Body:
I`m trying to create a file downloader as a background service but when a large file is scheduled, it's first put in memory and then, at the end of the download the file is written to disk.

How can I make the file be wrote gradually to the disk preserving memory considering that I may have lots of files being downloaded at the same time?

Here's the code I`m using:

var sys = require("sys"),
    http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs"),
    events = require("events");

var downloadfile = "http://nodejs.org/dist/node-v0.2.6.tar.gz";

var host = url.parse(downloadfile).hostname
var filename = url.parse(downloadfile).pathname.split("/").pop()

var theurl = http.createClient(80, host);
var requestUrl = downloadfile;
sys.puts("Downloading file: " + filename);
sys.puts("Before download request");
var request = theurl.request('GET', requestUrl, {"host": host});
request.end();

var dlprogress = 0;

setInterval(function () {
   sys.puts("Download progress: " + dlprogress + " bytes");
}, 1000);

request.addListener('response', function (response) {
    response.setEncoding('binary')
    sys.puts("File size: " + response.headers['content-length'] + " bytes.")
    var body = '';
    response.addListener('data', function (chunk) {
        dlprogress += chunk.length;
        body += chunk;
    });
    response.addListener("end", function() {
        fs.writeFileSync(filename, body, 'binary');
        sys.puts("After download finished");
    });

});


问:
Custom Soundcloud Widget (api) Player
I'm trying to create a custom player for some Soundcloud tracks. The idea is to hide the Iframe and create a few players to play different tracks. The loading and playing all works fine but I have two challenges.

How do I create a progressbar (SC.Widget.Events.PLAY_PROGRESS)

How do I create a download link?

A snippet from the way I'm coding this:

```<code>    (function(){
    var widgetIframe = document.getElementById('sc-widget'),
        widget       = SC.Widget(widgetIframe);

    widget.bind(SC.Widget.Events.READY, function() {

    $('#play').click(function(){
        widget.play();
    });
});  }());
</code>```

To bad the OPEN API is closed..

答:
If you are trying to stream tracks using a custom player, I recommend you do not use the widget at all. Rather, use the streaming SDK directly. There are methods there that can do everything you need to load, play, pause, seek, get the current time of the song and more.

To initialize the streaming player, you can do something like:

SC.initialize({
  client_id: "<client id>"
});

SC.stream("/tracks/" + song_id).then(function (player) {
  player.play();
}```
</div>
</div>
</p>

<p>To build the actual progress bar, you can do something inside your stream function like the following (this example uses JQuery but you don't need to):</p>

<pre class="lang-js prettyprint-override"><code>player.on("time", function () {
    var current_time = player.currentTime();
    var current_duration = player.options.duration;
    $(".scrubber .scrubber_fill").css("width", ((current_time / current_duration) * 100) + "%");
});
</code>```

Title: Custom Soundcloud Widget (api) Player

Body:
I'm trying to create a custom player for some Soundcloud tracks. The idea is to hide the Iframe and create a few players to play different tracks. The loading and playing all works fine but I have two challenges.

How do I create a progressbar (SC.Widget.Events.PLAY_PROGRESS)

How do I create a download link?

A snippet from the way I'm coding this:

    (function(){
    var widgetIframe = document.getElementById('sc-widget'),
        widget       = SC.Widget(widgetIframe);

    widget.bind(SC.Widget.Events.READY, function() {

    $('#play').click(function(){
        widget.play();
    });
});  }());

To bad the OPEN API is closed..

Body:
If you are trying to stream tracks using a custom player, I recommend you do not use the widget at all. Rather, use the streaming SDK directly. There are methods there that can do everything you need to load, play, pause, seek, get the current time of the song and more.

To initialize the streaming player, you can do something like:

SC.initialize({
  client_id: "<client id>"
});

SC.stream("/tracks/" + song_id).then(function (player) {
  player.play();
}

To build the actual progress bar, you can do something inside your stream function like the following (this example uses JQuery but you don't need to):

player.on("time", function () {
    var current_time = player.currentTime();
    var current_duration = player.options.duration;
    $(".scrubber .scrubber_fill").css("width", ((current_time / current_duration) * 100) + "%");
});


问:
Inconsistent results from R-part package
I am running R part on the same data set but the order of the columns are different and I am getting different results.

This is my dataset

```<code>   Home.Owner Marital.Status Annual.Income Default
1         Yes         Single           125      No
2          No        Married           100      No
3          No         Single            70      No
4         Yes        Married           120      No
5          No       Divorced            95     Yes
6          No        Married            60      No
7         Yes       Divorced           220      No
8          No         Single            85     Yes
9          No        Married            75      No
10         No         Single            90     Yes
</code>```

This is the code

```<code>a<-read.csv("ab.csv")
library(rpart)
library(rpart.plot)
model1<-rpart(Default ~.,data =a,method = "class",minsplit = 1,minbucket = 1
              ,parms=list(split=c("information") ))

rpart.plot(model1)
</code>```

results:

```<code>#changing column order
b<-a[,c(4,3,2,1)]

# running same process
model2<-rpart(Default ~.,data =b,method = "class",minsplit = 1,minbucket = 1
              ,parms=list(split=c("information") ))

rpart.plot(model2)
</code>```

The only thing that has changed is the order of the columns.

答:
Nothing is wrong here. This happens and I can explain why.

Notice that the two trees are different from the very first split. That is what we must understand.  rpart uses Gini Impurity to decide which variable to use to split the data. One time it used Marital Status and the other it used Annual Income. Look carefully at what happened in each split.  When it split on Marital Status, it created two nodes one with 40% of the data and no errors. The other node had 60% of the data and 50% errors. When it split on annual income,  it produced exactly the same distribution: one node with 40% of the data and no errors; the other node with 60% of the data and 50% errors.   Both of these two splits produce the same Gini impurity. It is a tie between the two attributes. So rpart makes an arbitrary choice between the two.  It picks the first one, hence the dependence on the attribute order.

Body:
I am running R part on the same data set but the order of the columns are different and I am getting different results.

This is my dataset

   Home.Owner Marital.Status Annual.Income Default
1         Yes         Single           125      No
2          No        Married           100      No
3          No         Single            70      No
4         Yes        Married           120      No
5          No       Divorced            95     Yes
6          No        Married            60      No
7         Yes       Divorced           220      No
8          No         Single            85     Yes
9          No        Married            75      No
10         No         Single            90     Yes

This is the code

a<-read.csv("ab.csv")
library(rpart)
library(rpart.plot)
model1<-rpart(Default ~.,data =a,method = "class",minsplit = 1,minbucket = 1
              ,parms=list(split=c("information") ))

rpart.plot(model1)

results:

#changing column order
b<-a[,c(4,3,2,1)]

# running same process
model2<-rpart(Default ~.,data =b,method = "class",minsplit = 1,minbucket = 1
              ,parms=list(split=c("information") ))

rpart.plot(model2)

The only thing that has changed is the order of the columns.


问:
Why Am I Not Able To Embed My Custom Framework?
I have a very simple framework project, MyFramework, that builds successfully. The framework defines a single, global function, myFunction.
The framework also defines 2 global variables: MyFrameworkVersionNumber and MyFrameworkVersionString (These 2 variables were created for me by Xcode)

I have a very simple application project, MyApplication. I am adding the framework to the application project by dragging and dropping the framework package (i.e. the MyFramework.framework in DerivedData that was produced by building the framework) onto the Xcode Navigator and then selecting the framework in the Embedded Binaries section of the project's General tab.

If I add code to MyApplication that references the variable MyFrameworkVersionNumber then I am able to successfully build and run MyApplication.

If I add code to MyApplication that references the function myFunction then I am not able to build MyApplication.

First Update

I suddenly remembered that Carthage does exactly what I am trying to do. So, I used Carthage to build MyFramework and Voila! - I can drag/drop the Carthage build of the framework into the application project and successfully use it. So now my inquiry has become: What does Carthage know that I do not?

答:
Oh for heaven's sake! It turned out to be so simple. MyFramework was being built for a Generic iOS Device (arm64 architecture). MyApplication was being built for a simulator (x86_64 architecture). As soon as I matched those two up all was well. The reason that the Carthage build worked so well is that it produces a universal binary (i.e. one that contains both architectures).

I still do not understand why the MyFrameworkVersionNumber global variable was able to be accessed regardless of the architecture. But I am okay with deferring that little mystery as some arcane bit of information that will be revealed in the goodness of time (perhaps something such as that it is in a header that is structured the same for both architectures).


问:
Using Asp.Net Core 2 Injection for Serilog with Multiple Projects
I have Serilog configured for Asp.Net Core 2.0 and it works great via .Net Core dependency injection in my startup web project (if I use it through Microsoft.Extensions.Logging), but I can't access it from any other project.

Here's what I have:

Program.cs

```<code>using System;
using System.IO;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Serilog;

namespace ObApp.Web.Mvc
{
    public class Program
    {
        public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
            .Build();

        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(Configuration)
                .CreateLogger();

            try
            {
                Log.Warning("Starting BuildWebHost");

                BuildWebHost(args).Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseSerilog()
                .Build();
    }
}
</code>```

Startup.cs

Startup .cs is pure default. I haven't altered it in any way from the original template for the new Asp.Net Core MVC project.

I have thought that I might need to add Serilog in the IServiceCollection services, but the article Leaner, meaner ASP.NET Core 2 logging at https://nblumhardt.com/2017/08/use-serilog/ tells me it's unnecessary.

You can then go ahead and delete any other logger configuration that’s
  hanging around: there’s no need for a "Logging" section in
  appsettings.json, no AddLogging() anywhere, and no configuration
  through ILoggerFactory in Startup.cs.

UseSerilog() replaces the built-in ILoggerFactory so that every logger
  in your application, whether it’s Serilog’s Log class, Serilog’s
  ILogger, or Microsoft.Extensions.Logging.ILogger, will be backed
  with the same Serilog implementation, and controlled through the same
  configuration.

What I Expected

The ability to simply inject a logger via a constructor in any class in any project in the solution. For example:

```<code>using Serilog;
public MyTestClass(ILogger logger) { ... }
</code>```

What I Got - Web (Startup) Project

Injection works in the HomeController if I use the Microsoft.Extensions.Logging wrapper:

```<code>using Microsoft.Extensions.Logging;

public class HomeController : Controller
{
    ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
        _logger.LogDebug("Controller instantiated.");
    }
}
</code>```

Injection fails in any project/class if I try to inject Serilog.ILogger

```<code>using Serilog;
using Serilog.Extensions.Logging; // Not sure if this would help.

public class HomeController : Controller
{
    ILogger _logger;

    public HomeController(ILogger logger)
    {
        _logger = logger;
        _logger.Debug("Controller instantiated.");
    }
}
</code>```

InvalidOperationException: Unable to resolve service
  for type 'Serilog.ILogger' while attempting to activate
  'ObApp2.Web.Mvc.Controllers.HomeController'.

My Bigger Issue - OtherProjects

My bigger issue is that I can't get a logger via DI through any method I've tried if I'm working in another project in the solution.

When I try to inject either using Microsoft.Extensions.Logging or using Serilog I get a missing parameter exception at build time.

```<code>using Microsoft.Extensions.Logging;
namespace ObApp.Domain
{
    public class MyTestClass(ILogger<MyTestClass> logger) { ... }

- or -

using Serilog;
namespace ObApp.Domain
{
    public class MyTestClass(ILogger logger) { ... }
</code>```

Both generate build error similar to:

There is no argument given that corresponds to the required formal
  parameter 'logger' of 'MyTestClass.MyTestClass(ILogger)'

Questions

When injecting with this type of Serilog configuration, is it recommended that I reference Microsoft.Extensions.Logging or Serilog in the class files where I'm doing the injection?

How can I get DI to work through all projects?

答:
One method that worked for me:

I added an instance of Serilog.Core.Logger using the AddSingleton() method in the ConfigureServices method. This resolved the DI issue. This step replaces the step of assigning a Logger instance to Log.Logger in the StartUp constructor.

```<code>services.AddSingleton((ILogger)new LoggerConfiguration()
            .MinimumLevel.Information()
            .WriteTo.File(<...>)
            .CreateLogger());
</code>```

Also change references in your class files to point to Serilog.Ilogger

Body:
I have Serilog configured for Asp.Net Core 2.0 and it works great via .Net Core dependency injection in my startup web project (if I use it through Microsoft.Extensions.Logging), but I can't access it from any other project.

Here's what I have:

Program.cs

using System;
using System.IO;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Serilog;

namespace ObApp.Web.Mvc
{
    public class Program
    {
        public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
            .Build();

        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(Configuration)
                .CreateLogger();

            try
            {
                Log.Warning("Starting BuildWebHost");

                BuildWebHost(args).Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseSerilog()
                .Build();
    }
}

Startup.cs

Startup .cs is pure default. I haven't altered it in any way from the original template for the new Asp.Net Core MVC project.

I have thought that I might need to add Serilog in the IServiceCollection services, but the article Leaner, meaner ASP.NET Core 2 logging at https://nblumhardt.com/2017/08/use-serilog/ tells me it's unnecessary.

You can then go ahead and delete any other logger configuration that’s
  hanging around: there’s no need for a "Logging" section in
  appsettings.json, no AddLogging() anywhere, and no configuration
  through ILoggerFactory in Startup.cs.

UseSerilog() replaces the built-in ILoggerFactory so that every logger
  in your application, whether it’s Serilog’s Log class, Serilog’s
  ILogger, or Microsoft.Extensions.Logging.ILogger, will be backed
  with the same Serilog implementation, and controlled through the same
  configuration.

What I Expected

The ability to simply inject a logger via a constructor in any class in any project in the solution. For example:

using Serilog;
public MyTestClass(ILogger logger) { ... }

What I Got - Web (Startup) Project

Injection works in the HomeController if I use the Microsoft.Extensions.Logging wrapper:

using Microsoft.Extensions.Logging;

public class HomeController : Controller
{
    ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
        _logger.LogDebug("Controller instantiated.");
    }
}

Injection fails in any project/class if I try to inject Serilog.ILogger

using Serilog;
using Serilog.Extensions.Logging; // Not sure if this would help.

public class HomeController : Controller
{
    ILogger _logger;

    public HomeController(ILogger logger)
    {
        _logger = logger;
        _logger.Debug("Controller instantiated.");
    }
}

InvalidOperationException: Unable to resolve service
  for type 'Serilog.ILogger' while attempting to activate
  'ObApp2.Web.Mvc.Controllers.HomeController'.

My Bigger Issue - OtherProjects

My bigger issue is that I can't get a logger via DI through any method I've tried if I'm working in another project in the solution.

When I try to inject either using Microsoft.Extensions.Logging or using Serilog I get a missing parameter exception at build time.

using Microsoft.Extensions.Logging;
namespace ObApp.Domain
{
    public class MyTestClass(ILogger<MyTestClass> logger) { ... }

- or -

using Serilog;
namespace ObApp.Domain
{
    public class MyTestClass(ILogger logger) { ... }

Both generate build error similar to:

There is no argument given that corresponds to the required formal
  parameter 'logger' of 'MyTestClass.MyTestClass(ILogger)'

Questions

When injecting with this type of Serilog configuration, is it recommended that I reference Microsoft.Extensions.Logging or Serilog in the class files where I'm doing the injection?

How can I get DI to work through all projects?

Body:
One method that worked for me:

I added an instance of Serilog.Core.Logger using the AddSingleton() method in the ConfigureServices method. This resolved the DI issue. This step replaces the step of assigning a Logger instance to Log.Logger in the StartUp constructor.

services.AddSingleton((ILogger)new LoggerConfiguration()
            .MinimumLevel.Information()
            .WriteTo.File(<...>)
            .CreateLogger());

Also change references in your class files to point to Serilog.Ilogger


问:
toggle div to move right/left
this is my first question on this website! :)
I am working on a website for a restaurant. The problem is that the following part of my code is malfunctioning. When clicked on the button, #menu expands towards right and stops after width=225px. But when I click the same button again, #menu contracts (width=50) and again expands (width=225)!
Please help!

```<code>$("#menu").toggle(

     function(){
           $("#menu").animate({width:225},"slow");
    },
    function(){
           $("#menu").animate({width:50},"slow");
    });
        });
});
</code>```

```<code><!--following is the code for menu-->
<div id="menu" style="position:absolute; width:50;

opacity:.4; height:75%; background-color:#000000; left:80%; top:20%;">
<button>Cart</button>
</div>
</code>```

答:
I think that jquery is having trouble with the integers use a string with px in it</p>

```<code>$('#menu').toggle('click', function(){
    $(this).animate({width:'225px'},500);
},function(){
    $(this).animate({width:'50px'},500);
});
</code>```

Title: toggle div to move right/left

Body:
this is my first question on this website! :)
I am working on a website for a restaurant. The problem is that the following part of my code is malfunctioning. When clicked on the button, #menu expands towards right and stops after width=225px. But when I click the same button again, #menu contracts (width=50) and again expands (width=225)!
Please help!

$("#menu").toggle(

     function(){
           $("#menu").animate({width:225},"slow");
    },
    function(){
           $("#menu").animate({width:50},"slow");
    });
        });
});

<button>Cart</button>

Body:
I think that jquery is having trouble with the integers use a string with px in it

$('#menu').toggle('click', function(){
    $(this).animate({width:'225px'},500);
},function(){
    $(this).animate({width:'50px'},500);
});


问:
how to reload the Table view data when tap on UILabel(UITapGestureRecognizer)
I am new to objective c, and i am very interested in learn new technologies.

I have a UITapGestureRecognizer on a label. I am using 2 label ,when i tap on label1 load some data Tableview and when I tap on label 2 i want to change the Tableview.

I didn't find any solution for my requirement. so anyone help me .

suggest me guy's how to change the TableView data when tap on UILabel.

答:
Welcome to Stack Overflow!

This answer should help clear things up for you nicely and give you a stronger understanding of how to use table view's and buttons to do what you need.

FIRST

To Alladinian's comment, I highly recommend switching over to the UIButton object instead of using UILabel objects. This way your elements can still display your text (as you were with labels) but you are able to make use of the built-in target capabilities of the button class.

```<code>- (void)addTarget:(nullable id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
</code>```

SECOND

Regarding your question, again, simply make use of an already built-in method that is designed for this very situation:

```<code>- (void)reloadData;
</code>```

This method is available by using / setting UITableViewDelegate and the UITableViewDataSource. Like such: here is an example of a generic UIViewController class that conforms (can use properly) the convenient UITableView delegates.

Header File (SomeClassController.h)

```<code>// SomeClassController.h
#import <UIKit/UIKit.h>

@interface SomeClassController : UIViewController <UITableViewDelegate, UITableViewDataSource>

// do anything here. properties, methods, etc :)
@property (nonatomic, ...) UITableView *tableView;

@end
</code>```

Implementation File (SomeClassController.m)

```<code>// ...
- (void)viewDidLoad {

    self.tableView.delegate = self;
    self.tableView.dataSource = self;

}
</code>```

Now by using UIButton objects you can set a method that will handle the user touching the screen by performing a method. Like here:

```<code>- (void)viewDidLoad {

    ...

    [someButton addTarget:self action:@selector(didTouchButton:) forControlEvents:UIControlEventTouchUpInside];

}

- (void)didTouchButton:(__kindof UIButton *)button {

    // Here you received the users touch event on the button, do what you like!
    // As your question asked how to reload table data, simply add this line
    // after following my other steps.

    [self.tableView reloadData];    // Here the magic is done!

    // This method will automatically reload the table view to display the
    // most recently updated data you have given it.

}
</code>```

Make sure you change your data before reloading, otherwise it may not change both visually or content-wise.

Happy coding!

Body:
Welcome to Stack Overflow!

This answer should help clear things up for you nicely and give you a stronger understanding of how to use table view's and buttons to do what you need.

FIRST

To Alladinian's comment, I highly recommend switching over to the UIButton object instead of using UILabel objects. This way your elements can still display your text (as you were with labels) but you are able to make use of the built-in target capabilities of the button class.

- (void)addTarget:(nullable id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;

SECOND

Regarding your question, again, simply make use of an already built-in method that is designed for this very situation:

- (void)reloadData;

This method is available by using / setting UITableViewDelegate and the UITableViewDataSource. Like such: here is an example of a generic UIViewController class that conforms (can use properly) the convenient UITableView delegates.

Header File (SomeClassController.h)

// SomeClassController.h
#import <UIKit/UIKit.h>

@interface SomeClassController : UIViewController <UITableViewDelegate, UITableViewDataSource>

// do anything here. properties, methods, etc :)
@property (nonatomic, ...) UITableView *tableView;

@end

Implementation File (SomeClassController.m)

// ...
- (void)viewDidLoad {

    self.tableView.delegate = self;
    self.tableView.dataSource = self;

}

Now by using UIButton objects you can set a method that will handle the user touching the screen by performing a method. Like here:

- (void)viewDidLoad {

    ...

    [someButton addTarget:self action:@selector(didTouchButton:) forControlEvents:UIControlEventTouchUpInside];

}

- (void)didTouchButton:(__kindof UIButton *)button {

    // Here you received the users touch event on the button, do what you like!
    // As your question asked how to reload table data, simply add this line
    // after following my other steps.

    [self.tableView reloadData];    // Here the magic is done!

    // This method will automatically reload the table view to display the
    // most recently updated data you have given it.

}

Make sure you change your data before reloading, otherwise it may not change both visually or content-wise.

Happy coding!


问:
Apache mod_security: test common attacks
I installed mod_security 2.8.0 on Apache 2.4.7 and I loaded the basic rules proposed by SpiderLabs-OWASP. My httpd.conf:

```<code>LoadModule unique_id_module modules/mod_unique_id.so
LoadModule security2_module modules/mod_security2.so

<IfModule security2_module>
    SecRuleEngine On

    # You can download the CRS from the GitHub Repo:
    # https://github.com/SpiderLabs/owasp-modsecurity-crs
    Include conf/crs/modsecurity_crs_10_setup.conf
    Include conf/crs/base_rules/*.conf

    # My basic (stupid) TEST rule
    SecRule ARGS "mod_security_test" "t:normalisePathWin,id:99999,severity:4,msg:'Drive Access'"
</IfModule>
</code>```

If call url: http://www.mysecuresite.com/?test=mod_security_test

```<code>Error 403 Forbidden
</code>```

My Rule Work!!

Now I want to test the most common attacks (and bad bot activity) to verify that everything is working fine.

Do you have tools or scripts that you would recommend to test the safety of the site?

答:
Just download KALI Linux (or similar) and run a few Web-based attacks against your server (you can easily Google a few how-to videos). Your error log should lit-up with mod security records. Analyze the logs. i.e.: (analyze the logs)

1) Make sure to run the test-attack against your server only

2) Run it from different IP than your's. Some hosting companies trying to prevent their users from pentesting their own servers/sites (which makes no sense to me)

Body:
I installed mod_security 2.8.0 on Apache 2.4.7 and I loaded the basic rules proposed by SpiderLabs-OWASP. My httpd.conf:

LoadModule unique_id_module modules/mod_unique_id.so
LoadModule security2_module modules/mod_security2.so

<IfModule security2_module>
    SecRuleEngine On

    # You can download the CRS from the GitHub Repo:
    # https://github.com/SpiderLabs/owasp-modsecurity-crs
    Include conf/crs/modsecurity_crs_10_setup.conf
    Include conf/crs/base_rules/*.conf

    # My basic (stupid) TEST rule
    SecRule ARGS "mod_security_test" "t:normalisePathWin,id:99999,severity:4,msg:'Drive Access'"
</IfModule>

If call url: http://www.mysecuresite.com/?test=mod_security_test

Error 403 Forbidden

My Rule Work!!

Now I want to test the most common attacks (and bad bot activity) to verify that everything is working fine.

Do you have tools or scripts that you would recommend to test the safety of the site?


问:
Check if for multiple values BUT one needs an extra line
My first question..!
Hi all, as a guy trying to learn programming/Python to be exact I have an issue that I would like to address. I have written some code that works as expected.

```<code>for i in range(81):
    if i in (30, 60, 80):
        if i == 80:
            ab += str(a) + '*' + str(b) + '<>'
        ab = ab.rstrip('<>')
        my_list += my_func(ab)
        ab = ''
    ab += str(a) + '*' + str(b) + '<>'
</code>```

Yet I don't think this part is the pythonic way to go:

```<code>if i in (30, 60, 80):
    if i == 80:
</code>```

There should be a way for me to say if i == 80 then do the standard 'if' conditions AFTER this extra code.

I hope I explained the issue properly. Thanks!

PS: This is an example code. I'm trying to find the proper logic only. Dont get stuck with the results.

Edit: I forgot to enter this line when posting my question (that's why some didn't understand the code):

```<code>my_list += my_func(ab)
</code>```

Also For extra points  :)  I'd love it if there was a way that this line doesn't have to be written twice!

```<code>ab += str(a) + '*' + str(b) + '<>'
</code>```

答:
Why don't you do two statements in the for loop?
Like :</p>

```<code>for i in range(81):
    if i == 80:
        <your code>
    if i in [30, 60, 80]:
        <your code>
    <code for every i>
</code>```

Body:
My first question..!
Hi all, as a guy trying to learn programming/Python to be exact I have an issue that I would like to address. I have written some code that works as expected.

for i in range(81):
    if i in (30, 60, 80):
        if i == 80:
            ab += str(a) + '*' + str(b) + '<>'
        ab = ab.rstrip('<>')
        my_list += my_func(ab)
        ab = ''
    ab += str(a) + '*' + str(b) + '<>'

Yet I don't think this part is the pythonic way to go:

if i in (30, 60, 80):
    if i == 80:

There should be a way for me to say if i == 80 then do the standard 'if' conditions AFTER this extra code.

I hope I explained the issue properly. Thanks!

PS: This is an example code. I'm trying to find the proper logic only. Dont get stuck with the results.

Edit: I forgot to enter this line when posting my question (that's why some didn't understand the code):

my_list += my_func(ab)

Also For extra points  :)  I'd love it if there was a way that this line doesn't have to be written twice!

ab += str(a) + '*' + str(b) + '<>'

Body:
Why don't you do two statements in the for loop?
Like :

for i in range(81):
    if i == 80:
        <your code>
    if i in [30, 60, 80]:
        <your code>
    <code for every i>