答:
maps variables are pointers to a map so assume that your row map is in 0x50 memory address, then your values array would be some like this

```<code>values := {{0x50}, {0x50}}
</code>```

so both will change by changing row.
a simple way to do that is to repeat making row again after first println or change the name of second map

Title: Append for array of maps raplaces all previous array items on the latest one

Body:
The question may sound very stupid but I really don't understand what's wrong.

I want to create an array of maps like this:

values := make([]map[string]string, 0)

Then I create some map:

row := make(map[string]string)
row["item1"] = "value1"
row["item2"] = "value2"

Then append it to the array:

values = append(values, row)

Printing values now gives:

[map[item1:value1 item2:value2]]

Do the same using some other values:

row["item1"] = "value3"
row["item2"] = "value4"
values = append(values, row)

Now printing values gives:

[map[item1:value3 item2:value4] map[item1:value3 item2:value4]]

So the first array item = the second one.
What can cause this?

Full code:

package main

import "fmt"

func main() {
  values := make([]map[string]string, 0)
  row := make(map[string]string)
  row["item1"] = "value1"
  row["item2"] = "value2"
  values = append(values, row)
  fmt.Println(values)
  row["item1"] = "value3"
  row["item2"] = "value4"
  values = append(values, row)
  fmt.Println(values)
}

Body:
maps variables are pointers to a map so assume that your row map is in 0x50 memory address, then your values array would be some like this

values := {{0x50}, {0x50}}

so both will change by changing row.
a simple way to do that is to repeat making row again after first println or change the name of second map


来源: stackexchange

问:
Why is spring batch looking for hsqldb
I am writing a spring batch application where I am using Oracle as the data store. When running the build and spring loads up, it is looking for hsqldb although I have defined ORACLE as the databaseType. Here is the error in the logs:
Cannot load JDBC driver class org.hsqldb.jdbcDriver

I do not want to use a separate database to store the spring batch meta-data.
Please advise why is spring batch looking for hsqldb.

```<code> <bean id="jobRepository" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
    <property name="transactionManager" ref="transactionManager"/>
    <property name="dataSource" ref="paymentDataSource"/>
    <property name="databaseType" value="ORACLE" />
 </bean>

<bean id="paymentDataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver">
    </property>
    <property name="url" value="jdbc:oracle:thin:@boxxxx:1521:xxxxx">
    </property>
    <property name="username" value="xxx"></property>
    <property name="password" value="xxx"></property>
</bean>

<bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" xmlns="http://www.springframework.org/schema/beans" />

[java] org.springframework.beans.factory.access.BootstrapException: Unable to initialize group definition. Group resource name [classpath*:beanRefContext.xml], factory key [applicationContext-main]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'baseContext' defined in URL : Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.context.support.GenericXmlApplicationContext]: Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'org.hsqldb.jdbcDriver'
     [java]     at org.springframework.beans.factory.access.SingletonBeanFactoryLocator.useBeanFactory(SingletonBeanFactoryLocator.java:388)
     [java]     at org.springframework.web.context.ContextLoader.loadParentContext(ContextLoader.java:563)
     [java]     at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
     [java]     at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
</code>```

答:
Have you already defined the corresponding property in application.properties ?

For example:

```<code>spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
</code>```

And the dependency of Oracle JAR in your pom.xml ?

ContentLicense: CC BY-SA 3.0

Title: Why is spring batch looking for hsqldb

Body:
I am writing a spring batch application where I am using Oracle as the data store. When running the build and spring loads up, it is looking for hsqldb although I have defined ORACLE as the databaseType. Here is the error in the logs:
Cannot load JDBC driver class org.hsqldb.jdbcDriver

I do not want to use a separate database to store the spring batch meta-data.
Please advise why is spring batch looking for hsqldb.

 <bean id="jobRepository" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
    <property name="transactionManager" ref="transactionManager"/>
    <property name="dataSource" ref="paymentDataSource"/>
    <property name="databaseType" value="ORACLE" />
 </bean>

<bean id="paymentDataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver">
    </property>
    <property name="url" value="jdbc:oracle:thin:@boxxxx:1521:xxxxx">
    </property>
    <property name="username" value="xxx"></property>
    <property name="password" value="xxx"></property>
</bean>

<bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" xmlns="http://www.springframework.org/schema/beans" />

[java] org.springframework.beans.factory.access.BootstrapException: Unable to initialize group definition. Group resource name [classpath*:beanRefContext.xml], factory key [applicationContext-main]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'baseContext' defined in URL : Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.context.support.GenericXmlApplicationContext]: Constructor threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jobRepository': Invocation of init method failed; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'org.hsqldb.jdbcDriver'
     [java]     at org.springframework.beans.factory.access.SingletonBeanFactoryLocator.useBeanFactory(SingletonBeanFactoryLocator.java:388)
     [java]     at org.springframework.web.context.ContextLoader.loadParentContext(ContextLoader.java:563)
     [java]     at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
     [java]     at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)

Body:
Have you already defined the corresponding property in application.properties ?

For example:

spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

And the dependency of Oracle JAR in your pom.xml ?


问:
android - download file with retrofit 2.0
I am using retrofit 2.0 for download a file.the problem is enqueue method not called. there is no error and no catch. nothing happen, where is my mistake?

this is my interface:

```<code>public interface ApiService {

    @GET("uploads/{file_name}")
    Call<ServerResponse> downloadFile(@Path("file_name") String fileName);
}
</code>```

and this is my downloading code :

```<code>private void downloadFile() {
        progressDialog.show();

        // Map is used to multipart the file using okhttp3.RequestBody
        File file = new File(mediaPath);

        // Parsing any Media type file
        RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
        ApiService getResponse = ApiClient.getClient().create(ApiService.class);
        Call<ServerResponse> call = getResponse.downloadFile(file.getName());
        call.enqueue(new Callback<ServerResponse>() {
            @Override
            public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
                ServerResponse serverResponse = response.body();
                if (serverResponse != null) {
                    if (serverResponse.getSuccess()) {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                } else {
                    assert serverResponse != null;
                    Log.v("Response", serverResponse.toString());
                }
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<ServerResponse> call, Throwable t) {

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

答:
```<code>@POST("uploads/{file_name}")
    Observable<Document> getDocumentsList(@Path("file_name") String fileName);
</code>```

and the code webservice call should be

```<code> Observable<Document> listObservable = mApiService.getDocumentsList(path);
    subscribe(listObservable, new Consumer<Document>() {
        @Override
        public void accept(Document resourceDtos) throws Exception {
            fillDocs(resourceDtos.getData());
        }
    }, new Consumer<Throwable>() {
        @Override
        public void accept(Throwable throwable) throws Exception {
            fillDocs(throwable.getMessage());
        }
    });
</code>```

Body:
I am using retrofit 2.0 for download a file.the problem is enqueue method not called. there is no error and no catch. nothing happen, where is my mistake?

this is my interface:

public interface ApiService {

    @GET("uploads/{file_name}")
    Call<ServerResponse> downloadFile(@Path("file_name") String fileName);
}

and this is my downloading code :

private void downloadFile() {
        progressDialog.show();

        // Map is used to multipart the file using okhttp3.RequestBody
        File file = new File(mediaPath);

        // Parsing any Media type file
        RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
        ApiService getResponse = ApiClient.getClient().create(ApiService.class);
        Call<ServerResponse> call = getResponse.downloadFile(file.getName());
        call.enqueue(new Callback<ServerResponse>() {
            @Override
            public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
                ServerResponse serverResponse = response.body();
                if (serverResponse != null) {
                    if (serverResponse.getSuccess()) {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                } else {
                    assert serverResponse != null;
                    Log.v("Response", serverResponse.toString());
                }
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<ServerResponse> call, Throwable t) {

            }
        });
    }

Body:
@POST("uploads/{file_name}")
    Observable<Document> getDocumentsList(@Path("file_name") String fileName);

and the code webservice call should be

 Observable<Document> listObservable = mApiService.getDocumentsList(path);
    subscribe(listObservable, new Consumer<Document>() {
        @Override
        public void accept(Document resourceDtos) throws Exception {
            fillDocs(resourceDtos.getData());
        }
    }, new Consumer<Throwable>() {
        @Override
        public void accept(Throwable throwable) throws Exception {
            fillDocs(throwable.getMessage());
        }
    });


问:
How to edit application configuration settings? App.config best way to go?
For my project I have settings that I added through the Settings in the project properties.

I quickly discovered that editing the app.config file directly seems to no really update the settings value.  Seems I have to view the project properties when I make a change and then recompile.

I'm wondering ... what is the best
and easiest way to handle customizable settings
for a project -- thought this would
be a no-brainer with how .Net
handles it ... shame on me.

Is it possible to use one of the
settings, AppSettings,
ApplicationSettings, or UserSettings to handle this?

Is it better to just write my settings to custom config file and handle things myself?

Right now ... I am looking for the quickest solution!

My environment is C#, .Net 3.5 and Visual Studio 2008.

Update

I am trying to do the following:

```<code>    protected override void Save()
    {
        Properties.Settings.Default.EmailDisplayName = this.ddEmailDisplayName.Text;
        Properties.Settings.Default.Save();
    }
</code>```

Gives me a read-only error when I compile.

答:
Your answer is probably here:
Simplest way to have a configuration file in a Windows Forms C# Application</p>

OwnerDisplayName: MattRuma

ContentLicense: CC BY-SA 2.5

Body:
For my project I have settings that I added through the Settings in the project properties.

I quickly discovered that editing the app.config file directly seems to no really update the settings value.  Seems I have to view the project properties when I make a change and then recompile.

I'm wondering ... what is the best
and easiest way to handle customizable settings
for a project -- thought this would
be a no-brainer with how .Net
handles it ... shame on me.

Is it possible to use one of the
settings, AppSettings,
ApplicationSettings, or UserSettings to handle this?

Is it better to just write my settings to custom config file and handle things myself?

Right now ... I am looking for the quickest solution!

My environment is C#, .Net 3.5 and Visual Studio 2008.

Update

I am trying to do the following:

    protected override void Save()
    {
        Properties.Settings.Default.EmailDisplayName = this.ddEmailDisplayName.Text;
        Properties.Settings.Default.Save();
    }

Gives me a read-only error when I compile.

LastEditorDisplayName: MattRuma

OwnerDisplayName: thijs


问:
NGINX--Connect to UNIX sock failed
Checked out a few other similar issues here, but can't diagnose the issue.

My site has been occasionally going down with a 502 Bad Gateway Error.

I found the following in my error log.  Note i'm using a VPS server on Ubuntu 16.04 using Gunicorn/NGINX.

2017/02/21 01:08:29 [crit] 1247#1247: *1 connect() to unix:/home/django/chrisblog/chrisblog.sock failed (2: No such file or directory) while connecting to upstream, client: 173.48.32.62, server: 45.32.201.31, request: "GET /redditclone/ HTTP/1.1", upstream: "http://unix:/home/django/chrisblog/chrisblog.sock:/redditclone/", host: "pythoncreate.com"
2017/02/21 01:10:36 [crit] 1575#1575: *1 connect() to unix:/home/django/chrisblog/chrisblog.sock failed (2: No such file or directory) while connecting to upstream, client: 173.48.32.62, server: 45.32.201.31, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/chrisblog/chrisblog.sock:/", host: "pythoncreate.com"
2017/02/21 01:48:04 [crit] 2342#2342: *2 connect() to unix:/home/django/chrisblog/chrisblog.sock failed (2: No such file or directory) while connecting to upstream, client: 173.48.32.62, server: 45.32.201.31, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/chrisblog/chrisblog.sock:/", host: "pythoncreate.com"```
</div>
</div>
</p>

<p>When i go to check the gunicorn status i get the following so it looks like maybe it is failing for some reason?:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> gunicorn.service - gunicorn daemon
   Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Tue 2017-02-21 01:46:08 UTC; 7min ago
 Main PID: 2245 (code=exited, status=203/EXEC)

Feb 21 01:46:08 mydjangoblog systemd[1]: Started gunicorn daemon.
Feb 21 01:46:08 mydjangoblog systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC
Feb 21 01:46:08 mydjangoblog systemd[1]: gunicorn.service: Unit entered failed state.
Feb 21 01:46:08 mydjangoblog systemd[1]: gunicorn.service: Failed with result 'exit-code'.</code>```

And here is a shot of output of ps aux | grep nginx

root      2341  0.0  0.1 125104  1480 ?        Ss   01:47   0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
www-data  2342  0.0  0.4 125444  3152 ?        S    01:47   0:00 nginx: worker process
django    2461  0.0  0.2  16576  2000 pts/0    S+   01:57   0:00 grep --color=auto nginx```

any help here is hugely appreciated

答: You just need to check whether "/home/django/chrisblog/chrisblog.sock" exists.</p>

Title: NGINX--Connect to UNIX sock failed

Body:
Checked out a few other similar issues here, but can't diagnose the issue.

My site has been occasionally going down with a 502 Bad Gateway Error.

I found the following in my error log.  Note i'm using a VPS server on Ubuntu 16.04 using Gunicorn/NGINX.

2017/02/21 01:08:29 [crit] 1247#1247: *1 connect() to unix:/home/django/chrisblog/chrisblog.sock failed (2: No such file or directory) while connecting to upstream, client: 173.48.32.62, server: 45.32.201.31, request: "GET /redditclone/ HTTP/1.1", upstream: "http://unix:/home/django/chrisblog/chrisblog.sock:/redditclone/", host: "pythoncreate.com"
2017/02/21 01:10:36 [crit] 1575#1575: *1 connect() to unix:/home/django/chrisblog/chrisblog.sock failed (2: No such file or directory) while connecting to upstream, client: 173.48.32.62, server: 45.32.201.31, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/chrisblog/chrisblog.sock:/", host: "pythoncreate.com"
2017/02/21 01:48:04 [crit] 2342#2342: *2 connect() to unix:/home/django/chrisblog/chrisblog.sock failed (2: No such file or directory) while connecting to upstream, client: 173.48.32.62, server: 45.32.201.31, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/chrisblog/chrisblog.sock:/", host: "pythoncreate.com"

When i go to check the gunicorn status i get the following so it looks like maybe it is failing for some reason?:

 gunicorn.service - gunicorn daemon
   Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Tue 2017-02-21 01:46:08 UTC; 7min ago
 Main PID: 2245 (code=exited, status=203/EXEC)

Feb 21 01:46:08 mydjangoblog systemd[1]: Started gunicorn daemon.
Feb 21 01:46:08 mydjangoblog systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC
Feb 21 01:46:08 mydjangoblog systemd[1]: gunicorn.service: Unit entered failed state.
Feb 21 01:46:08 mydjangoblog systemd[1]: gunicorn.service: Failed with result 'exit-code'.

And here is a shot of output of ps aux | grep nginx

root      2341  0.0  0.1 125104  1480 ?        Ss   01:47   0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
www-data  2342  0.0  0.4 125444  3152 ?        S    01:47   0:00 nginx: worker process
django    2461  0.0  0.2  16576  2000 pts/0    S+   01:57   0:00 grep --color=auto nginx

any help here is hugely appreciated


问:
Export constant in Typescript and import it in another module
I'm starting to try some TypeScript features and I want to export two constants in one module and import them and use it in another module like this:

```<code>// module1.ts
export const CAMPUS = 'campus';
export const TOKIO = 'tokio';

// module2.ts
import * as ThemeNameEnum from './module1';

export type IState = ThemeNameEnum.CAMPUS | ThemeNameEnum.TOKIO;
</code>```

The VSCode is not recognizing the exported members and the compiler is giving me this error:

```<code>ERROR in /Users/elias/Documents/agora-binaria/crm-front/src/app/redux/theme/theme-reducer.ts (4,36): Namespace '"/Users/elias/Documents/agora-binaria/crm-front/src/app/redux/theme/theme-name-enum"' has no exported member 'CAMPUS'.
ERROR in /Users/elias/Documents/agora-binaria/crm-front/src/app/redux/theme/theme-reducer.ts (4,59): Namespace '"/Users/elias/Documents/agora-binaria/crm-front/src/app/redux/theme/theme-name-enum"' has no exported member 'TOKIO'.
</code>```

What am I doing wrong? Thanks.

PS: This is my tsconfig.json file:

```<code>{
  "compilerOptions": {
    "baseUrl": "",
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
    "dom",
      "es2017"
    ],
    "mapRoot": "./",
    "module": "es6",
    "moduleResolution": "node",
    "removeComments": true,
    "outDir": "../dist/client",
    "sourceMap": true,
    "target": "es5",
    "typeRoots": [
      "../node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}
</code>```

答:
Whereas the error message is somewhat misleading, it makes some sense. By export const A = 'foo'; you're exporting a variable, but type C = A; tries to treat A as a type. And there isn't one. The example can be condensed further:

```<code>const A = 'foo';
const B = 'bar';

type C = A | B;
</code>```

That will fail with "cannot find A and B" message (similarly to your code), because A and B are variables, not types. To solve your problem you need to get type of A and B:

```<code>type C = typeof A | typeof B;
</code>```

Body:
I'm starting to try some TypeScript features and I want to export two constants in one module and import them and use it in another module like this:

// module1.ts
export const CAMPUS = 'campus';
export const TOKIO = 'tokio';

// module2.ts
import * as ThemeNameEnum from './module1';

export type IState = ThemeNameEnum.CAMPUS | ThemeNameEnum.TOKIO;

The VSCode is not recognizing the exported members and the compiler is giving me this error:

ERROR in /Users/elias/Documents/agora-binaria/crm-front/src/app/redux/theme/theme-reducer.ts (4,36): Namespace '"/Users/elias/Documents/agora-binaria/crm-front/src/app/redux/theme/theme-name-enum"' has no exported member 'CAMPUS'.
ERROR in /Users/elias/Documents/agora-binaria/crm-front/src/app/redux/theme/theme-reducer.ts (4,59): Namespace '"/Users/elias/Documents/agora-binaria/crm-front/src/app/redux/theme/theme-name-enum"' has no exported member 'TOKIO'.

What am I doing wrong? Thanks.

PS: This is my tsconfig.json file:

{
  "compilerOptions": {
    "baseUrl": "",
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
    "dom",
      "es2017"
    ],
    "mapRoot": "./",
    "module": "es6",
    "moduleResolution": "node",
    "removeComments": true,
    "outDir": "../dist/client",
    "sourceMap": true,
    "target": "es5",
    "typeRoots": [
      "../node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}

Body:
Whereas the error message is somewhat misleading, it makes some sense. By export const A = 'foo'; you're exporting a variable, but type C = A; tries to treat A as a type. And there isn't one. The example can be condensed further:

const A = 'foo';
const B = 'bar';

type C = A | B;

That will fail with "cannot find A and B" message (similarly to your code), because A and B are variables, not types. To solve your problem you need to get type of A and B:

type C = typeof A | typeof B;


问:
ASP.NET WindowsAuthentication custom 401 Unauthorized error page
I have an ASP.NET web-site with authentication using ActiveDirectory.

Now, when an authenticated user opens a page - he is automatically authenticated. I have faced a problem - when a non-authenticated user (for example, a Mozilla Firefox user with not defined network.automatic-ntlm-auth.trusted-uris property) opens a page, IIS sends 401 response and prompts for a login \ password.

What I want is not to prompt him for a login \ password - just show a custom error page. It sounds pretty simple - authenticated users get the requested page, non-authenticated are redirected to a custom error page. It would work fine for FormsAuthentication.

However, I have tried so many ways by now. Any Web.config redirects are not working. Even if I clear a Response and put there a redirect - I will get a loop because this custom page (*e.g., /Error/AccessDenied) also requires authentication. Marking a controller as AllowAnonymous does nothing.

However, if I enable Anonymous authentication in IIS Manager, real authenticated domain users are not being authorized when they open a web-site.

How can I solve this problem?

答:
Important addition to Yeldar's comment:

When altering the response message for remote requests (read: non-localhost) you will need to add the following to your config file:

```<code><system.webServer>
    <httpErrors existingResponse="PassThrough"></httpErrors>
</system.webServer>
</code>```

If you do not allow the response to "pass through" remote clients will get the default "You do not have permission to view this directory or page".

I got this info from: https://stackoverflow.com/a/17324195/3310441

Body:
Important addition to Yeldar's comment:

When altering the response message for remote requests (read: non-localhost) you will need to add the following to your config file:

<system.webServer>
    <httpErrors existingResponse="PassThrough"></httpErrors>
</system.webServer>

If you do not allow the response to "pass through" remote clients will get the default "You do not have permission to view this directory or page".

I got this info from: https://stackoverflow.com/a/17324195/3310441


问:
What steps are required to create a custom Android version?

Background

We are handing out phones for people to use while visiting our exhibition, and in those phones we are running a j2me app. The people will be using the device on their own while walking around, and returning it when leaving.

Problem

While our app is made specifically to be easy to use and understand for someone who has never used it before, the phone OS is not... (Currently HTCs with Brew MP)

People are accidentally pressing the front buttons and are thrown back into the menus, or the screen locks and they dont know how to get back.

Solution?

The only solution I can think of is to create a custom Android version that we can use in our phones.

The thing I would like to change is to disable all hardware buttons and special swipes. So people are essentially locked into our app when it is launched.

A few questions comes to mind:

How hard it is to get a custom built android version up and running on a device?

Does disabling buttons mean I have to dig deep into the kernel, or is it easily accessible?

Are some handsets better suited for running custom android? (We are currently planning on using ZTE Blade)

Does android come with drivers for GSM/camera/GPS etc for most chipsets, or will that be a problem?

Am I over-complicating things? Perhaps regular apps can override what the buttons do already?

答:
Unless this is a Symbian handset, in which case you cannot block the red key and menu key, you should be able to respond to all the softkeys to prevent it going back even in J2ME, the softkeys are most likely to be mapped to -6 and -7

heres some example code which should help get you started, some phones notably some Samsungs have a third softkey and getGameAction can throw an exception (Sony K700 certainly does) so should be be try caught

```<code>   public static boolean isKnownKey(Canvas canvas, int keyCode)
   {
      return (keyCode >= KEY_NUM0 && keyCode <= KEY_NUM9) ||
         keyCode == KEY_POUND || keyCode == KEY_STAR ||
         canvas.getGameAction(keyCode) != 0;
   }

   public static int KEY_SOFT_LEFT = -6;

   protected void keyPressed(int keyCode)
   {
      if (!isKnownKey(this, keyCode))
      {
         if (keyCode == KEY_SOFT_LEFT)
            leftSoftCommand();
         else
            rightSoftCommand();
      }
      else
         super.keyPressed(keyCode);
   }
</code>```

Body:
Unless this is a Symbian handset, in which case you cannot block the red key and menu key, you should be able to respond to all the softkeys to prevent it going back even in J2ME, the softkeys are most likely to be mapped to -6 and -7

heres some example code which should help get you started, some phones notably some Samsungs have a third softkey and getGameAction can throw an exception (Sony K700 certainly does) so should be be try caught

   public static boolean isKnownKey(Canvas canvas, int keyCode)
   {
      return (keyCode >= KEY_NUM0 && keyCode <= KEY_NUM9) ||
         keyCode == KEY_POUND || keyCode == KEY_STAR ||
         canvas.getGameAction(keyCode) != 0;
   }

   public static int KEY_SOFT_LEFT = -6;

   protected void keyPressed(int keyCode)
   {
      if (!isKnownKey(this, keyCode))
      {
         if (keyCode == KEY_SOFT_LEFT)
            leftSoftCommand();
         else
            rightSoftCommand();
      }
      else
         super.keyPressed(keyCode);
   }


问:
how to get the first splited part of each index in an array
we have an array like below, length of the array is not constant(may increase/decrease).

```<code>[255028AD_ABC_DE_2057,261830AD_ABC_FG_2876,.......]
</code>```

My aim is to achieve only the first part of each index like below.

```<code>[255028AD,261830AD,.........]
</code>```

Please help.

答:
Just use map https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/map

with

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/split

like

```<code>var array = ["12_bla","13_ble"].map(function (el) { return el.split('_',1)[0]; });
</code>```

Body:
we have an array like below, length of the array is not constant(may increase/decrease).

[255028AD_ABC_DE_2057,261830AD_ABC_FG_2876,.......]

My aim is to achieve only the first part of each index like below.

[255028AD,261830AD,.........]

Please help.

Body:
Just use map https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/map

with

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/split

like

var array = ["12_bla","13_ble"].map(function (el) { return el.split('_',1)[0]; });


问:
Implement Count inversion using merge sort algorithm in c++
I need to implement the count inversion algorithm for a homework but i couldn't figure out what is the problem in my code.Our professor asked us to implement count inversion in c++(Which i didn't work with it much) without using any C++ libraries only i could include <iostream> and use std only for output (cout<<) and that's it, also he gave us this piece here :

```<code> void count_inversion(int a[],int n){
    count_inversion(a, n / 2);
    count_inversion(a + (n / 2), n / 2);
    count_inversion_merge(a, n / 2, n);
  }
</code>```

and said we should implement the count_inversion_merge function and use this piece as a hint.
So i tried to adapt the code a little to work but still have no luck.

Here is my code :

```<code> int count_inversion_merge(int array[], int mid, int n) {
        for (k = 0; k < n; k++) {
            if (j == n || (i < mid && array[i] < array[j])) {
                b[k] = array[i];
                i++;
            } else {
                b[k] = array[j];
                j++;
                inversion++;
            }
        }

    }
</code>```

My First input int a[] ={ 2, 4, 1, 3, 5 }; should return 3 but it returns 5
and my second output should be 5 and i get 5. I hope that someone could point out where is my error.

答:
Your basic idea is right, but there 2 problems in your code. One is conceptual, another is in code.

In the else block of merge step, you are increasing the inversion by one. Instead, you should increase it by how many values you have in the left part. So in else block you should use, inversion += mid-i; instead of inversion++; Because, you need to actually count the number of swaps required. At this point, for the value  of array[j], you have mid - i (rest of left array) number of elements which were actually needed to swap corresponding to array[j]. That means, if you would use bubble sort, you would need to swap all the rest elements in left array (mid-i) with this single value (array[j]). So, for this array[j] you should increase number of elements rest in the left sub-array.

In the recursive calling of count_inversion, you are missing some values in every call. e.g. lets say n=5. Then you are using 5/2 = 2 at left and 5/2 = 2 at right. But you are missing the last element at the right side. You can solve it by using as following in your second recursive call. Here, you should use the rest of the length you used from first call.

count_inversion(a + (n / 2), n - n / 2);

A little modified code from yours with fixes: https://ideone.com/raKD7T

Body:
I need to implement the count inversion algorithm for a homework but i couldn't figure out what is the problem in my code.Our professor asked us to implement count inversion in c++(Which i didn't work with it much) without using any C++ libraries only i could include <iostream> and use std only for output (cout<<) and that's it, also he gave us this piece here :

 void count_inversion(int a[],int n){
    count_inversion(a, n / 2);
    count_inversion(a + (n / 2), n / 2);
    count_inversion_merge(a, n / 2, n);
  }

and said we should implement the count_inversion_merge function and use this piece as a hint.
So i tried to adapt the code a little to work but still have no luck.

Here is my code :

 int count_inversion_merge(int array[], int mid, int n) {
        for (k = 0; k < n; k++) {
            if (j == n || (i < mid && array[i] < array[j])) {
                b[k] = array[i];
                i++;
            } else {
                b[k] = array[j];
                j++;
                inversion++;
            }
        }

    }

My First input int a[] ={ 2, 4, 1, 3, 5 }; should return 3 but it returns 5
and my second output should be 5 and i get 5. I hope that someone could point out where is my error.


问:
Why does Subversion fail to flag a modified Microsoft Excel spreadsheet file?
I have encountered some behaviour I didn't expect from Subversion, and discovered this almost accidentally: A modified file is not being flagged as modified.

I have a unit test involving a Microsoft Excel spreadsheet as an input file. The unit test calculates a CRC checksum; my test started failing due to the checksum changing.

The test file is stored in SVN, and has MIME type "application/octet-stream", and is therefore considered as binary by SVN.

I get the same behaviour from TortoiseSVN and the SVN command line client, in this case both based on SVN 1.6: When the file is opened in Excel, the fact that it is open must be encoded in the file itself; SVN shows that the file is modified. However, when the file is closed again (without saving), it seems to return to its unmodified state: that is, svn status does not list the Excel file; svn diff produces no output anyway due to the data being binary.

The catch is that the file does not now binary compare with the file stored in the repository. (If a fresh copy is exported, it does not binary compare with the opened-and-closed copy.) The file is apparently unchanged from the user's point of view, so in a semantic sense, the SVN response is reasonable. But not syntactically; and SVN is essentially syntactic.

The part for which I can't find a reason is why SVN does not flag the file as modified. I can't imagine SVN has any special handling for Excel files (and in any case the MIME type is not specifically one associated with MS Excel); there is no SNV keyword property defined. Likewise, I can imagine Excel knows anything about the contents of the hidden .svn subdirectory in which the SVN working copy information is stored.

Do you have any clues as to what is going on here?

Thanks, Rob.

答:
Excel always locks files on open, setting the timestamp to the current date. When you close without saving, Excel will revert the timestamp back. This causes SVN to ignore the file.

As for the changed contents, I'm not sure. Can you reproduce the problem?


问:
Eclipse: key binding for getting a list of attributes of a class
In Eclipse, Ctrl + O gives a list of all methods available in the class. Do you know any key binding that gives a list of all attributes of a certain class? </p>

答:
Press the Alt + Shift + Q , V.

If you want more eclipse shortcut keys, press

ctrl + shift + L


问:
Error: Not allowed to return a result set from a trigger
```<code>DROP TRIGGER IF EXISTS `examcnpm`.`users_BEFORE_DELETE`;

DELIMITER $$
USE `examcnpm`$$
CREATE DEFINER = CURRENT_USER TRIGGER `examcnpm`.`users_BEFORE_DELETE` BEFORE DELETE ON `users` FOR EACH ROW
BEGIN
    declare id int;

    select id= (select userid from deleted);
    delete from Result where Result.userid=id;

    delete u from Users as u inner join deleted as r on u.userid=r.userid
    where u.userid=id;
END$$

DELIMITER ;
</code>```

答:
I am not clear why you could want to delete from users in the trigger or why a before rather than an after query. But here's how to use OLD. to delete from result.

```<code>DROP TRIGGER IF EXISTS `users_BEFORE_DELETE`;
DELIMITER $$
CREATE DEFINER = CURRENT_USER TRIGGER `users_BEFORE_DELETE` after DELETE ON `u` FOR EACH ROW
BEGIN
        delete from Result where Result.id=old.id;
END$$
DELIMITER ;
</code>```

For example

```<code>ariaDB [sandbox]> select id,username from u order by id limit 5;
+----+----------+
| id | username |
+----+----------+
|  2 | Jane     |
|  3 | Ali      |
|  6 | Bruce    |
|  7 | Martha   |
|  8 | Sidney   |
+----+----------+
5 rows in set (0.00 sec)

MariaDB [sandbox]> select * from result order by id limit 10;
+----+
| id |
+----+
|  2 |
|  2 |
|  3 |
|  3 |
|  6 |
|  6 |
|  7 |
|  7 |
|  8 |
|  8 |
+----+
10 rows in set (0.00 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> delete from u where id = 2;
Query OK, 1 row affected (0.04 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> select id,username from u order by id limit 5;
+----+----------+
| id | username |
+----+----------+
|  3 | Ali      |
|  6 | Bruce    |
|  7 | Martha   |
|  8 | Sidney   |
| 10 | charlie  |
+----+----------+
5 rows in set (0.00 sec)

MariaDB [sandbox]> select * from result order by id limit 10;
+----+
| id |
+----+
|  3 |
|  3 |
|  6 |
|  6 |
|  7 |
|  7 |
|  8 |
|  8 |
| 10 |
| 10 |
+----+
10 rows in set (0.00 sec)
</code>```

Body:
I am not clear why you could want to delete from users in the trigger or why a before rather than an after query. But here's how to use OLD. to delete from result.

DROP TRIGGER IF EXISTS `users_BEFORE_DELETE`;
DELIMITER $$
CREATE DEFINER = CURRENT_USER TRIGGER `users_BEFORE_DELETE` after DELETE ON `u` FOR EACH ROW
BEGIN
        delete from Result where Result.id=old.id;
END$$
DELIMITER ;

For example

ariaDB [sandbox]> select id,username from u order by id limit 5;
+----+----------+
| id | username |
+----+----------+
|  2 | Jane     |
|  3 | Ali      |
|  6 | Bruce    |
|  7 | Martha   |
|  8 | Sidney   |
+----+----------+
5 rows in set (0.00 sec)

MariaDB [sandbox]> select * from result order by id limit 10;
+----+
| id |
+----+
|  2 |
|  2 |
|  3 |
|  3 |
|  6 |
|  6 |
|  7 |
|  7 |
|  8 |
|  8 |
+----+
10 rows in set (0.00 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> delete from u where id = 2;
Query OK, 1 row affected (0.04 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> select id,username from u order by id limit 5;
+----+----------+
| id | username |
+----+----------+
|  3 | Ali      |
|  6 | Bruce    |
|  7 | Martha   |
|  8 | Sidney   |
| 10 | charlie  |
+----+----------+
5 rows in set (0.00 sec)

MariaDB [sandbox]> select * from result order by id limit 10;
+----+
| id |
+----+
|  3 |
|  3 |
|  6 |
|  6 |
|  7 |
|  7 |
|  8 |
|  8 |
| 10 |
| 10 |
+----+
10 rows in set (0.00 sec)


问:
Include custom content in ASP.NET Windows Authentication 401 response
We have an internal system where users can authenticate using Windows authentication but we want to include some custom content in the 401 repsonse that takes the user to a custom username/password authentication page if the cancel off the Windows authentication dialog.

When an unauthenticated user accesses a page, Windows authentication responds with a 401 Unauthorized response, with the headers

```<code>WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
</code>```

This prompts the browser to show a dialog asking for Windows credentials. If the user enters their credentials, there is another handshake request-response, and then the user is authenticated and the requested page is shown.

If the user cancels the dialog, the browser displays the content of the original 401 Unauthorized reponse.
We use Application_EndRequest in the Global.asax to return some custom content here which takes the user to our custom login system.

```<code>    /// <summary>
    /// If we are about to send the NTLM authenticate headers, include this content. Then, if the user cancels off the
    /// windows auth dialog, they will be presented with this page and redirected to the username / password login screen
    /// </summary>
    void Application_EndRequest(object sender, EventArgs e)
    {
        Logger.DebugFormat("in Application_EndRequest. Response.StatusCode: {0}", Response.StatusCode);

        if (Response.StatusCode == 401)
        {
            Response.ContentType = "text/html";

            var redirectUrl = string.Format("https://mycompany.com/SSO/Login?encryptedSessionRequestId={1}",
                HttpUtility.UrlEncode(Request.QueryString["encryptedSessionRequestId"]));

            var text = File.ReadAllText(Server.MapPath("~/UnauthorizedError.html"));
            text = text.Replace("[USERNAME_PASSWORD_LOGON_REDIRECT]", redirectUrl);

            Response.Write(text);

            Logger.Debug("Done writing response");
            Response.End();
        }
    }
</code>```

UnauthorizedError.html contains the following script which forwards the user on

```<code><script language="javascript" type="text/javascript">
    window.location = "[USERNAME_PASSWORD_LOGON_REDIRECT]";
</script>
</code>```

When running locally in (Win7/IIS7.5), this works great, we use Response.Write() to send our content and the user is able to see it when they cancel the dialog.

But when accessing the site remotely, e.g. when it running in our development environment, although we can see from the logs that Application_EndRequest is being called and our content written to the response, it is overridden at some point and all that reaches the browser is the authentication headers and the text You do not have permission to view this directory or page.

1) How can we prevent this content being overwritten?

2) Where in the pipeline might this be happening?

3) Does anyone have any suggestions of another way to implement this behaviour, e.g. with an HTTP module?

Thanks!

答:
I know this is an old post but I would like to share a solution to this problem.

When altering the response message for remote requests (read: non-localhost) you will need to add the following to your config file:

```<code><system.webServer>
    <httpErrors existingResponse="PassThrough"></httpErrors>
</system.webServer>
</code>```

If you do not allow the response to "pass through" remote clients will get the default "You do not have permission to view this directory or page".

I got this info from: https://stackoverflow.com/a/17324195/3310441

Body:
We have an internal system where users can authenticate using Windows authentication but we want to include some custom content in the 401 repsonse that takes the user to a custom username/password authentication page if the cancel off the Windows authentication dialog.

When an unauthenticated user accesses a page, Windows authentication responds with a 401 Unauthorized response, with the headers

WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM

This prompts the browser to show a dialog asking for Windows credentials. If the user enters their credentials, there is another handshake request-response, and then the user is authenticated and the requested page is shown.

If the user cancels the dialog, the browser displays the content of the original 401 Unauthorized reponse.
We use Application_EndRequest in the Global.asax to return some custom content here which takes the user to our custom login system.

    ///
    /// If we are about to send the NTLM authenticate headers, include this content. Then, if the user cancels off the
    /// windows auth dialog, they will be presented with this page and redirected to the username / password login screen
    ///
    void Application_EndRequest(object sender, EventArgs e)
    {
        Logger.DebugFormat("in Application_EndRequest. Response.StatusCode: {0}", Response.StatusCode);

        if (Response.StatusCode == 401)
        {
            Response.ContentType = "text/html";

            var redirectUrl = string.Format("https://mycompany.com/SSO/Login?encryptedSessionRequestId={1}",
                HttpUtility.UrlEncode(Request.QueryString["encryptedSessionRequestId"]));

            var text = File.ReadAllText(Server.MapPath("~/UnauthorizedError.html"));
            text = text.Replace("[USERNAME_PASSWORD_LOGON_REDIRECT]", redirectUrl);

            Response.Write(text);

            Logger.Debug("Done writing response");
            Response.End();
        }
    }

UnauthorizedError.html contains the following script which forwards the user on

When running locally in (Win7/IIS7.5), this works great, we use Response.Write() to send our content and the user is able to see it when they cancel the dialog.

But when accessing the site remotely, e.g. when it running in our development environment, although we can see from the logs that Application_EndRequest is being called and our content written to the response, it is overridden at some point and all that reaches the browser is the authentication headers and the text You do not have permission to view this directory or page.

1) How can we prevent this content being overwritten?

2) Where in the pipeline might this be happening?

3) Does anyone have any suggestions of another way to implement this behaviour, e.g. with an HTTP module?

Thanks!

Body:
I know this is an old post but I would like to share a solution to this problem.

When altering the response message for remote requests (read: non-localhost) you will need to add the following to your config file:

<system.webServer>
    <httpErrors existingResponse="PassThrough"></httpErrors>
</system.webServer>

If you do not allow the response to "pass through" remote clients will get the default "You do not have permission to view this directory or page".

I got this info from: https://stackoverflow.com/a/17324195/3310441


问:
Python: Real-Time Streaming Data
I am trying to capture real-time streaming financial time data via Python. I want to initially store the information in a database and then at a later date further develop a program to analyze and make trading decisions based on this data. It would be nice to also be able to subsequently display said data in some graphical format either on a website or in a Jupyter notebook.

As a starting point, I figured I would use bitcoin data from either GDAX or Gemini. I wanted to capture tick data and potentially additional order book information too if that is feasible.

In doing some research I am a bit overwhelmed by the options out there and could use some guidance in how to structure the project and what libraries would be most appropriate.

I have looked at the respective docs for each service's API as well as a few Github projects and am still unsure of where to start. Any advice, suggestions or recommended reading would be greatly appreciated.

答:
Any advice, suggestions or recommended reading?

If I may add a few cents after few decades hands-on experience on due architecture and design reasoning:

Always remain both realistic and honest to yourself:

```<code>           0.1 ns - NOP
           0.3 ns - XOR, ADD, SUB
           0.5 ns - CPU L1 dCACHE reference           (1st introduced in late 80-ies )
           0.9 ns - JMP SHORT
           1   ns - speed-of-light (a photon) travel a 1 ft (30.5cm) distance -- will stay, throughout any foreseeable future :o)
         3~4   ns - CPU L2  CACHE reference           (2020/Q1)
           5   ns - CPU L1 iCACHE Branch mispredict
           7   ns - CPU L2  CACHE reference
          10   ns - DIV
          19   ns - CPU L3  CACHE reference           (2020/Q1 considered slow on 28c Skylake)
          71   ns - CPU cross-QPI/NUMA best  case on XEON E5-46*
         100   ns - MUTEX lock/unlock
         100   ns - own DDR MEMORY reference
         135   ns - CPU cross-QPI/NUMA best  case on XEON E7-*
         202   ns - CPU cross-QPI/NUMA worst case on XEON E7-*
         325   ns - CPU cross-QPI/NUMA worst case on XEON E5-46*
      10,000   ns - Compress 1K bytes with Zippy PROCESS
      20,000   ns - Send 2K bytes over 1 Gbps NETWORK
     250,000   ns - Read 1 MB sequentially from MEMORY
     500,000   ns - Round trip within a same DataCenter
  10,000,000   ns - DISK seek
  10,000,000   ns - Read 1 MB sequentially from NETWORK
  30,000,000   ns - Read 1 MB sequentially from DISK
 150,000,000   ns - Send a NETWORK packet CA -> Netherlands
|   |   |   |
|   |   | ns|
|   | us|
| ms|
</code>```

decide, how much "real-time" is your ambition in reality, this makes the biggest difference -- if you technically have to implement the process control-loop, having due to its stability criterion a threshold under a say 1 kHz RTT-End-to-End ( event-origination + transport + local acquisition + local processing + feedback-loop << 1 [ms] ), 10 kHz ( << 100 [us] ). Knowing this "intention" helps you decide on proper and feasible technology, that can ( or principally cannot ) fulfill said target. Choosing in-adequate technology is a common ( and expensive ) mistake of amateurs ( but also often repeated even by professional software houses ).

after knowing the realistic value of the RTT-E2E threshold, check before going any step further, if the API-provider is indeed allowing you so frequent updates to be served in both technical and commercial sense. If not, you have to find another data-feed provider, who would. If your real-time system cannot be fed from an adequately sampled ( fast ) feeding-source, the control-loop will not work for you within its range of stability -- which is bad -- as bad as if you would try to watch your television which would show up not each and every but just about each 37~46-th picture, from the HD video stream. You would not be able to watch this "sub-sampled choppy something" ( sure, if your local DVB-T decoder would not give up to show anything at all, due to such brutal scale of the DVB-T stream-protocol violations, the checkered artifacts are obnoxious when even just a few CRC-bits over Reed/Solomon-redundant error-tolerant transcoding failed to get correctly through ) but definitely nothing nice compared to the stable and error-free 1:1 FullHD-stream.

having both the realistic value of the RTT-E2E threshold and the matching API-vendor available, start designing the technical steps ( not the technology to implement them ) how do you plan to help mask the real-world real-time latencies -- the actual time-costs [us] of the transport ( + all the associated encryption / decryption schemes, be it a SSL-tunnel or VPN or other ) from the API-provider reference access-point down to your processing-engine input. Not knowing this, all your further decisions would be flawed.

having measured that real-world ISO/OSI-L9-down-stream latency, double that time in [us], so as to also reserve reasonable amount of time to also cover the up-stream latency ( which need not have exactly the same sources of latency, but orders of magnitude will be near ).

In case your initial design RTT-E2E target figure has a control-loop threshold of the said 1kHz and your max( DownStream ) + max( UpStream ) ceiling of the latencies observed experimentally, as measured live against the provider's real-world production API-gateway ( that one, that was checked for matching your 1kHz control-loop threshold ) during at least one 24/7-duty-cycle, now calculate how much time is left for you to start any sort of local-processing - i.e. how many [us] actually remain for your local-processing such that your 1kHz control-loop does not fail to meet its stability threshold.

If your net local-processing time-budget has become already here negative, you know that your work will not yield anything good. It cannot. Pull stop.

If your net local-processing time-budget yet leaves some decent amount of [us] -- this is your actual process' design target to start designing such the computing steps and measures so as to always safely fit in.

Anybody, who starts coding without knowing this principal design-limit is either naive or irresponsible, a "just-teaching" academician or a headbang-lover ( who loves to fail and does not mind going again and again against a known wall ), while a systematic professional designer now gets focused to start all the careful design efforts, against the collected hard facts and evidence supported design-targets ( and never would spend a second on a task without knowing these principal set of constraint, that just only Alice in the Wonderlands can abstract from -- not knowing where you want to get, any road will lead you there -- which is a nice fairytale, but not a real-world practice to experiment with, is it? )

now, check you a threshold value, how often a GIL gets released ( in [us] ) - if it does not fit remarkable amount of times inside your remaining net local-processing time-budget, one may straight forget about using python, that simple ( and objections about multi-threaded processing do not get you better in Python domain:

"... in Python, the GIL means that even if you have multiple threads chugging simultaneously on a computation, only one of those threads will actually be running at any given instant, because all of the other ones will be blocked, waiting to acquire the global interpreter lock. That means that the multithreads Python program will actually be slower than the single-threaded version, rather than faster, since only one thread runs at a time -- plus there is the accounting overhead incurred by forcing every thread to wait for, acquire, and then relinquish the GIL (round-robin style) every few milliseconds. ..."

even if all wannabe experts post infinite amounts of a-free-of-charge pieces of advice that this and that package is such a great tool. Sure, many packages indeed are great tools, but sorry, almost never for any tighter real-time application domain under certain principal levels of stability thresholds. Yes, I was quite happy with designing and operating a python/scikit-learn GLAN-distributed fast AI/ML-predictive system, but I was pretty sure to fit under << 1 [ms] and a 80 ~ 90 [us] threshold for the local RTT-E2E was well inside my control-loop's stability perimeter )

One may spend literally any amount of just-love-coding in tools, that a professional would never have a reason to start using right due to known principal un-ability to match and meet the control-loop stability threshold, so better take due care in real-time system architecture feasibility / review phase not to repeat some of these or similarly naive fatal decision errors.

Title: Python: Real-Time Streaming Data

Body:
Any advice, suggestions or recommended reading?

If I may add a few cents after few decades hands-on experience on due architecture and design reasoning:

Always remain both realistic and honest to yourself:

           0.1 ns - NOP
           0.3 ns - XOR, ADD, SUB
           0.5 ns - CPU L1 dCACHE reference           (1st introduced in late 80-ies )
           0.9 ns - JMP SHORT
           1   ns - speed-of-light (a photon) travel a 1 ft (30.5cm) distance -- will stay, throughout any foreseeable future :o)
         3~4   ns - CPU L2  CACHE reference           (2020/Q1)
           5   ns - CPU L1 iCACHE Branch mispredict
           7   ns - CPU L2  CACHE reference
          10   ns - DIV
          19   ns - CPU L3  CACHE reference           (2020/Q1 considered slow on 28c Skylake)
          71   ns - CPU cross-QPI/NUMA best  case on XEON E5-46*
         100   ns - MUTEX lock/unlock
         100   ns - own DDR MEMORY reference
         135   ns - CPU cross-QPI/NUMA best  case on XEON E7-*
         202   ns - CPU cross-QPI/NUMA worst case on XEON E7-*
         325   ns - CPU cross-QPI/NUMA worst case on XEON E5-46*
      10,000   ns - Compress 1K bytes with Zippy PROCESS
      20,000   ns - Send 2K bytes over 1 Gbps NETWORK
     250,000   ns - Read 1 MB sequentially from MEMORY
     500,000   ns - Round trip within a same DataCenter
  10,000,000   ns - DISK seek
  10,000,000   ns - Read 1 MB sequentially from NETWORK
  30,000,000   ns - Read 1 MB sequentially from DISK
 150,000,000   ns - Send a NETWORK packet CA -> Netherlands
|   |   |   |
|   |   | ns|
|   | us|
| ms|

decide, how much "real-time" is your ambition in reality, this makes the biggest difference -- if you technically have to implement the process control-loop, having due to its stability criterion a threshold under a say 1 kHz RTT-End-to-End ( event-origination + transport + local acquisition + local processing + feedback-loop << 1 [ms] ), 10 kHz ( << 100 [us] ). Knowing this "intention" helps you decide on proper and feasible technology, that can ( or principally cannot ) fulfill said target. Choosing in-adequate technology is a common ( and expensive ) mistake of amateurs ( but also often repeated even by professional software houses ).

after knowing the realistic value of the RTT-E2E threshold, check before going any step further, if the API-provider is indeed allowing you so frequent updates to be served in both technical and commercial sense. If not, you have to find another data-feed provider, who would. If your real-time system cannot be fed from an adequately sampled ( fast ) feeding-source, the control-loop will not work for you within its range of stability -- which is bad -- as bad as if you would try to watch your television which would show up not each and every but just about each 37~46-th picture, from the HD video stream. You would not be able to watch this "sub-sampled choppy something" ( sure, if your local DVB-T decoder would not give up to show anything at all, due to such brutal scale of the DVB-T stream-protocol violations, the checkered artifacts are obnoxious when even just a few CRC-bits over Reed/Solomon-redundant error-tolerant transcoding failed to get correctly through ) but definitely nothing nice compared to the stable and error-free 1:1 FullHD-stream.

having both the realistic value of the RTT-E2E threshold and the matching API-vendor available, start designing the technical steps ( not the technology to implement them ) how do you plan to help mask the real-world real-time latencies -- the actual time-costs [us] of the transport ( + all the associated encryption / decryption schemes, be it a SSL-tunnel or VPN or other ) from the API-provider reference access-point down to your processing-engine input. Not knowing this, all your further decisions would be flawed.

having measured that real-world ISO/OSI-L9-down-stream latency, double that time in [us], so as to also reserve reasonable amount of time to also cover the up-stream latency ( which need not have exactly the same sources of latency, but orders of magnitude will be near ).

In case your initial design RTT-E2E target figure has a control-loop threshold of the said 1kHz and your max( DownStream ) + max( UpStream ) ceiling of the latencies observed experimentally, as measured live against the provider's real-world production API-gateway ( that one, that was checked for matching your 1kHz control-loop threshold ) during at least one 24/7-duty-cycle, now calculate how much time is left for you to start any sort of local-processing - i.e. how many [us] actually remain for your local-processing such that your 1kHz control-loop does not fail to meet its stability threshold.

If your net local-processing time-budget has become already here negative, you know that your work will not yield anything good. It cannot. Pull stop.

If your net local-processing time-budget yet leaves some decent amount of [us] -- this is your actual process' design target to start designing such the computing steps and measures so as to always safely fit in.

Anybody, who starts coding without knowing this principal design-limit is either naive or irresponsible, a "just-teaching" academician or a headbang-lover ( who loves to fail and does not mind going again and again against a known wall ), while a systematic professional designer now gets focused to start all the careful design efforts, against the collected hard facts and evidence supported design-targets ( and never would spend a second on a task without knowing these principal set of constraint, that just only Alice in the Wonderlands can abstract from -- not knowing where you want to get, any road will lead you there -- which is a nice fairytale, but not a real-world practice to experiment with, is it? )

now, check you a threshold value, how often a GIL gets released ( in [us] ) - if it does not fit remarkable amount of times inside your remaining net local-processing time-budget, one may straight forget about using python, that simple ( and objections about multi-threaded processing do not get you better in Python domain:

"... in Python, the GIL means that even if you have multiple threads chugging simultaneously on a computation, only one of those threads will actually be running at any given instant, because all of the other ones will be blocked, waiting to acquire the global interpreter lock. That means that the multithreads Python program will actually be slower than the single-threaded version, rather than faster, since only one thread runs at a time -- plus there is the accounting overhead incurred by forcing every thread to wait for, acquire, and then relinquish the GIL (round-robin style) every few milliseconds. ..."

even if all wannabe experts post infinite amounts of a-free-of-charge pieces of advice that this and that package is such a great tool. Sure, many packages indeed are great tools, but sorry, almost never for any tighter real-time application domain under certain principal levels of stability thresholds. Yes, I was quite happy with designing and operating a python/scikit-learn GLAN-distributed fast AI/ML-predictive system, but I was pretty sure to fit under << 1 [ms] and a 80 ~ 90 [us] threshold for the local RTT-E2E was well inside my control-loop's stability perimeter )

One may spend literally any amount of just-love-coding in tools, that a professional would never have a reason to start using right due to known principal un-ability to match and meet the control-loop stability threshold, so better take due care in real-time system architecture feasibility / review phase not to repeat some of these or similarly naive fatal decision errors.

ContentLicense: CC BY-SA 4.0


问:
How to change session values in php
i am trying to change the value of a session var in php.

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

if(isset($_POST["submit"])) {
    $_SESSION["registratie_data"]["straat"] = $_POST["straat"];
    $_SESSION["registratie_data"]["nummer"] = $_POST["nummer"];
    $_SESSION["registratie_data"]["gemeente"] = $_POST["gemeente"];
    $_SESSION["registratie_data"]["postcode"] = $_POST["postcode"];
}
$registratie_data    =   $_SESSION['registratie_data'];

if(isset($_POST["edit_button"])) {
    foreach($registratie_data as $key => $value) {
        if($key == $_GET["focus"]) {
            $value = $_POST["edit_value"];
            echo $value;
        }
    }
}
?>
</code>```

As you see i am trying to change the value in the foreach loop. This actually works and when i echo the value, i see the result i want... But then to display this value in html, doesnt work.

Anyone who can tell me what i'm doing wrong here?

This is my html code, if anyone needs this in order to help me out.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style>
        li {
            display: block;
        }
    </style>
</head>
<body>
    <a href="?session=destroy">Vernietig sessie</a>
    <h1>Registratiegegevens</h1>
    <?php if(isset($_POST["submit"]) || isset($_POST["edit_button"]) ): ?>
    <ul>
    <?php foreach($registratie_data as $key => $value): ?>
        <li>
            <?php echo $value . " | "  ?>
            <a href="?focus=<?php echo $key ?>">wijzig</a>
        </li>
    <?php endforeach ?>
    </ul>
    <?php elseif(isset($_GET["focus"])): ?>

            <form action="#" method=POST>
              <ul>
               <li>
                <?php echo $_GET["focus"] ?>
                <input type="text" name="edit_value" ?>
                <input type="submit" name="edit_button" value="Opslaan">
                </li>
              </ul>
            </form>

    <?php else: ?>
    <form action="#" method=POST>
        <ul>
            <li>
                <label for="straat">Straat</label>
                <input type="text" name="straat">
            </li>
            <li>
                <label for="nummer">Nummer</label>
                <input type="text" name="nummer">
            </li>
            <li>
                <label for="gemeente">Gemeente</label>
                <input type="text" name="gemeente">
            </li>
            <li>
                <label for="postcode">postcode</label>
                <input type="text" name="postcode">
            </li>
            <input class="el" type="submit" name="submit" value="Volgende">
        </ul>
    </form>
    <?php endif ?>
</body>
</html>
</code>```

答:
1.In PHP file your assigning the session value to $registratie_data variable the your using foreach loop to print.
   here $registratie_data as session data

In HTML file your not assigning any data to $registratie_data variable so it have empty data.
here $registratie_data empty data

so you need to assign data to $registratie_data as shown below to get required

 //you need to assgin the session value

```<code><?php foreach($registratie_data as $key => $value): ?>
    <li>
        <?php echo $value . " | "  ?>
        <a href="?focus=<?php echo $key ?>">wijzig</a>
    </li>
<?php endforeach ?>
</code>```

Title: How to change session values in php

Body:
i am trying to change the value of a session var in php.

<?php
session_start();

if(isset($_POST["submit"])) {
    $_SESSION["registratie_data"]["straat"] = $_POST["straat"];
    $_SESSION["registratie_data"]["nummer"] = $_POST["nummer"];
    $_SESSION["registratie_data"]["gemeente"] = $_POST["gemeente"];
    $_SESSION["registratie_data"]["postcode"] = $_POST["postcode"];
}
$registratie_data    =   $_SESSION['registratie_data'];

if(isset($_POST["edit_button"])) {
    foreach($registratie_data as $key => $value) {
        if($key == $_GET["focus"]) {
            $value = $_POST["edit_value"];
            echo $value;
        }
    }
}
?>

As you see i am trying to change the value in the foreach loop. This actually works and when i echo the value, i see the result i want... But then to display this value in html, doesnt work.

Anyone who can tell me what i'm doing wrong here?

This is my html code, if anyone needs this in order to help me out.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>test</title>

    Vernietig sessie

Registratiegegevens

    <?php if(isset($_POST["submit"]) || isset($_POST["edit_button"]) ): ?>

    <?php foreach($registratie_data as $key => $value): ?>

            <?php echo $value . " | "  ?>
            <a href="?focus=<?php echo $key ?>">wijzig

    <?php endforeach ?>

    <?php elseif(isset($_GET["focus"])): ?>

            <form action="#" method=POST>

                <?php echo $_GET["focus"] ?>
                <input type="text" name="edit_value" ?>
                <input type="submit" name="edit_button" value="Opslaan">

            </form>

    <?php else: ?>
    <form action="#" method=POST>

                Straat
                <input type="text" name="straat">

                Nummer
                <input type="text" name="nummer">

                Gemeente
                <input type="text" name="gemeente">

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

            <input class="el" type="submit" name="submit" value="Volgende">

    </form>
    <?php endif ?>

Body:
1.In PHP file your assigning the session value to $registratie_data variable the your using foreach loop to print.
   here $registratie_data as session data

In HTML file your not assigning any data to $registratie_data variable so it have empty data.
here $registratie_data empty data

so you need to assign data to $registratie_data as shown below to get required

 //you need to assgin the session value

<?php foreach($registratie_data as $key => $value): ?>
    <li>
        <?php echo $value . " | "  ?>
        <a href="?focus=<?php echo $key ?>">wijzig</a>
    </li>
<?php endforeach ?>


问:
mod rewrite Rule for Image + String to Imagefolder Rewrite
I have got some images on my server, which were always generated on the fly and requested right here:
http://www.mydomain.com/en/images.png?domain=test.com

They are now cached in
http://www.mydomain.com/images/test.com.png

I tried the following rule in my htaccess, but it doesn't work:

RewriteRule ^(en|de)?/images.png\?domain=(.*) /images/$2.png   [QSA,L]

Any clue what's wrong?

答:
just found the solution:

RewriteCond %{QUERY_STRING} ^domain=(.*)$
^ this line was missing to catch the Query String
RewriteRule ^(en|de)?/images.png$ /rating-images/%1.png [QSA]


问:
The request was denied by service delegate (SBMainWorkspace) for reason: Unspecified
im using the latest Cordova, XCode and Mac OSX Sierra

i am unable to build the sample project on any old devices in the simulator (iPhone 5 or less)

the error im getting isnt very helpful because the console.log file DOESNT EXIST!

any ideas at all?

An error was encountered processing the command

(domain=FBSOpenApplicationServiceErrorDomain, code=1): The request to
    open "com.hestor.nasmob" failed. The request was denied by service
    delegate (SBMainWorkspace) for reason: Unspecified.

logPath: /Developer/Cordova/NASMob/platforms/ios/cordova/console.log

Simon

答:
Quit the simulator, and re-run it again.

It works fine.


问:
How to do player movement calculations on c# console from unity movement
Question: How do i go about doing a equation on a c# console for where the player should be based on player input from unity.

To explain farther, the client is ran in unity and the server is a c# console application. When the player presses a movement key ex. (w, witch moves the player forward based on local position, as to always make the player move forward) it sends to the server that player pressed w, and then the sever responds and tells the client that it pressed w, changing the player w is pressed bool to true. Then the character moves.

Essentially I am trying to figure out how to make a equation that will do what unity does, but without a transform, or even how the transform works so that i can apply it to the server side.

Here is the client side code:

```<code> private void Update()
{
    SendKeysToServer();
    PlayerController();
    PlayerPositionUpdateChecker();
}

public void PlayerController()
{
    if (gameObject.name == ntwmng.Playername)
    {
        MovementControllerPlayer();
        JumpControllerPlayer();
        RotationControllerPlayer();
        MovementFinalizer();
    }
    else
    {
        MovementControllerClones();
        JumpControllerClones();
        RotationControllerClones();
        MovementFinalizerClones();
    }
}

public void MovementControllerPlayer()
{
    if (CharContr.isGrounded)
    {
        moveDirection = new Vector3(0, 0, 0);

        if (wKeyDownPlayer)
        {
            moveDirection = moveDirection + new Vector3(0, 0, speed * Time.deltaTime);
        }
        if (sKeyDownPlayer)
        {
            moveDirection = moveDirection + new Vector3(0, 0, -speed * Time.deltaTime);
        }
        if (qKeyDownPlayer)
        {
            moveDirection = moveDirection + new Vector3(-speed * Time.deltaTime, 0, 0);
        }
        if (eKeyDownPlayer)
        {
            moveDirection = moveDirection + new Vector3(speed * Time.deltaTime, 0, 0);
        }

        moveDirection = transform.TransformDirection(moveDirection);
        //moveDirection *= speed;
    }

}

public void RotationControllerPlayer()
{
    if (dKeyDownPlayer)
    {
        transform.Rotate(0, RotationSpeed * Time.deltaTime, 0);
    }
    if(aKeyDownPlayer)
    {
        transform.Rotate(0, -RotationSpeed * Time.deltaTime, 0);
    }
}

public void JumpControllerPlayer()
{
    if (CharContr.isGrounded)
    {

        if (SpaceKeyDownPlayer)
        {
            moveDirection.y = jumpSpeed * Time.deltaTime;
        }
    }
}

public void MovementFinalizer()
{
    moveDirection.y -= gravity * Time.deltaTime;
    CharContr.Move(moveDirection);
}

public void CameraAndListenerController()
{
    if (gameObject.name == ntwmng.Playername)
    {
        if (playercam.enabled == false)
        {
            playercam.enabled = true;
        }
        if (AudioListener.enabled == false)
        {
            AudioListener.enabled = true;
        }
    }
    else
    {
        if (playercam.enabled == true)
        {
            playercam.enabled = false;
        }
        if (AudioListener.enabled == true)
        {
            AudioListener.enabled = false;
        }
    }
}

public void SendKeysToServer()
{
    NetworkStream NtwrkStrm = ServerConnection.GetStream();
    IFormatter Formatter = new BinaryFormatter();

    foreach (KeyCode kcode in Enum.GetValues(typeof(KeyCode)))
    {
        if(Input.GetKeyDown(kcode))
        {
            string type = "Movement Update Key Down";
            string kycode = Convert.ToString(kcode);
            //Debug.Log(kycode);
            Formatter.Serialize(NtwrkStrm, type);
            NtwrkStrm.Flush();
            Formatter.Serialize(NtwrkStrm, ntwmng.Playername);
            NtwrkStrm.Flush();
            Formatter.Serialize(NtwrkStrm, kycode);
            NtwrkStrm.Flush();
        }else
        if(Input.GetKeyUp(kcode))
        {
            string type = "Movement Update Key Up";
            string kycode = Convert.ToString(kcode);
            //Debug.Log(kycode);
            Formatter.Serialize(NtwrkStrm, type);
            NtwrkStrm.Flush();
            Formatter.Serialize(NtwrkStrm, ntwmng.Playername);
            NtwrkStrm.Flush();
            Formatter.Serialize(NtwrkStrm, kycode);
            NtwrkStrm.Flush();
        }
    }
}

public void MovementControllerClones()
{
    if (CharContr.isGrounded)
    {
        moveDirection = new Vector3(0, 0, 0);

        if (wKeyDownClone)
        {
            moveDirection = moveDirection + new Vector3(0, 0, speed * Time.deltaTime);
        }
        if (sKeyDownClone)
        {
            moveDirection = moveDirection + new Vector3(0, 0, -speed * Time.deltaTime);
        }
        if (qKeyDownClone)
        {
            moveDirection = moveDirection + new Vector3(-speed * Time.deltaTime, 0, 0);
        }
        if (eKeyDownClone)
        {
            moveDirection = moveDirection + new Vector3(speed * Time.deltaTime, 0, 0);
        }

        moveDirection = transform.TransformDirection(moveDirection);
        //moveDirection *= speed;
    }

}

public void RotationControllerClones()
{
    if (dKeyDownClone)
    {
        transform.Rotate(0, RotationSpeed * Time.deltaTime, 0);
    }
    if (aKeyDownClone)
    {
        transform.Rotate(0, -RotationSpeed * Time.deltaTime, 0);
    }
}

public void JumpControllerClones()
{
    if (CharContr.isGrounded)
    {

        if (SpaceKeyDownClone)
        {
            moveDirection.y = jumpSpeed* Time.deltaTime;
        }
    }
}

public void MovementFinalizerClones()
{
    moveDirection.y -= gravity * Time.deltaTime;
    CharContr.Move(moveDirection);
}

public void CloneKeyUpdater(string type,string kcode)
{
    //Debug.Log("Key " + kcode + " Clone Updating");
    if (type == "Movement Update Key Down")
    {
        if (kcode == "W")
        {
            wKeyDownClone = true;
        }
        if (kcode == "A")
        {
            aKeyDownClone = true;
        }
        if (kcode == "D")
        {
            dKeyDownClone = true;
        }
        if (kcode == "S")
        {
            sKeyDownClone = true;
        }
        if (kcode == "Q")
        {
            qKeyDownClone = true;
        }
        if (kcode == "E")
        {
            eKeyDownClone = true;
        }
        if (kcode == "Space")
        {
            SpaceKeyDownClone = true;
        }
    }
    else if (type == "Movement Update Key Up")
    {
        if (kcode == "W")
        {
            wKeyDownClone = false;
        }
        if (kcode == "A")
        {
            aKeyDownClone = false;
        }
        if (kcode == "D")
        {
            dKeyDownClone = false;
        }
        if (kcode == "S")
        {
            sKeyDownClone = false;
        }
        if (kcode == "Q")
        {
            qKeyDownClone = false;
        }
        if (kcode == "E")
        {
            eKeyDownClone = false;
        }
        if (kcode == "Space")
        {
            SpaceKeyDownClone = false;
        }
    }
}

public void PlayerKeyUpdater(string type, string kcode)
{
    //Debug.Log("Key down " + kcode + " Updating");
    if (type == "Movement Update Key Down")
    {
        if (kcode == "W")
        {
            wKeyDownPlayer = true;
        }
        if (kcode == "A")
        {
            aKeyDownPlayer = true;
        }
        if (kcode == "D")
        {
            dKeyDownPlayer = true;
        }
        if (kcode == "S")
        {
            sKeyDownPlayer = true;
        }
        if (kcode == "Q")
        {
            qKeyDownPlayer = true;
        }
        if (kcode == "E")
        {
            eKeyDownPlayer = true;
        }
        if (kcode == "Space")
        {
            SpaceKeyDownPlayer = true;
        }
    }
    else if (type == "Movement Update Key Up")
    {
        if (kcode == "W")
        {
            wKeyDownPlayer = false;
        }
        if (kcode == "A")
        {
            aKeyDownPlayer = false;
        }
        if (kcode == "D")
        {
            dKeyDownPlayer = false;
        }
        if (kcode == "S")
        {
            sKeyDownPlayer = false;
        }
        if (kcode == "Q")
        {
            qKeyDownPlayer = false;
        }
        if (kcode == "E")
        {
            eKeyDownPlayer = false;
        }
        if (kcode == "Space")
        {
            SpaceKeyDownPlayer = false;
        }
    }
}
</code>```

Any help will be muchly appreciated. :)

Edit:
so i have figured out a equation that i am using to try and mimic player movement, as of right now it only work between 0 and 90 degrees, just tell i get it exact. the equation comes out really close, but is just a tiny bit off. Any suggestions? Also, this is running on client side, no server influence, so that I can get the math to an exact. The math comes out about 1 unit per second slower then the players current position. Basically after pressing w for 1 second with speed = 20 the math comes out to 19 and actual position is 20.

here is code

```<code>    if (CharContr.velocity != Vector3.zero)//checks if the player is moving
    {
        if (rotation < 90f && rotation > 0f) // makes sure the rotation is 0-90
        {
            percent = (100 / (90 / rotation)) / 100; // gets the percent
            x = x + (percent * speed * Time.deltaTime); //adds to current position multiplied by speed and delta time
            invertPercent = 1 - percent; //gets the percent for z
            z = z + (invertPercent * speed * Time.deltaTime); // adds and stuff again
        }
</code>```

答:
This is really complicated than you thought if you want to implement it yourself instead of using Unity's built-in NetworkTransform. Read this "Client-Side Prediction and Server Reconciliation" article. There are many parts of that article but it shows you what's going on and how this is done.

Although, Unity simplified a part of this if you are using Rigidbody by providing a new function (Physics.Simulate). You simulate all the Rigidbody on the server with the Physics.Simulate function, serialize the transform of each one and send to all the clients.

On the clients, receive the data, de-serialize them then lerp from the current transform to the received ones. You can find an example of how to use Physics.Simulate to determine the position of a Rigidbody in x second here.

Body:
Question: How do i go about doing a equation on a c# console for where the player should be based on player input from unity.

To explain farther, the client is ran in unity and the server is a c# console application. When the player presses a movement key ex. (w, witch moves the player forward based on local position, as to always make the player move forward) it sends to the server that player pressed w, and then the sever responds and tells the client that it pressed w, changing the player w is pressed bool to true. Then the character moves.

Essentially I am trying to figure out how to make a equation that will do what unity does, but without a transform, or even how the transform works so that i can apply it to the server side.

Here is the client side code:

 private void Update()
{
    SendKeysToServer();
    PlayerController();
    PlayerPositionUpdateChecker();
}

public void PlayerController()
{
    if (gameObject.name == ntwmng.Playername)
    {
        MovementControllerPlayer();
        JumpControllerPlayer();
        RotationControllerPlayer();
        MovementFinalizer();
    }
    else
    {
        MovementControllerClones();
        JumpControllerClones();
        RotationControllerClones();
        MovementFinalizerClones();
    }
}

public void MovementControllerPlayer()
{
    if (CharContr.isGrounded)
    {
        moveDirection = new Vector3(0, 0, 0);

        if (wKeyDownPlayer)
        {
            moveDirection = moveDirection + new Vector3(0, 0, speed * Time.deltaTime);
        }
        if (sKeyDownPlayer)
        {
            moveDirection = moveDirection + new Vector3(0, 0, -speed * Time.deltaTime);
        }
        if (qKeyDownPlayer)
        {
            moveDirection = moveDirection + new Vector3(-speed * Time.deltaTime, 0, 0);
        }
        if (eKeyDownPlayer)
        {
            moveDirection = moveDirection + new Vector3(speed * Time.deltaTime, 0, 0);
        }

        moveDirection = transform.TransformDirection(moveDirection);
        //moveDirection *= speed;
    }

}

public void RotationControllerPlayer()
{
    if (dKeyDownPlayer)
    {
        transform.Rotate(0, RotationSpeed * Time.deltaTime, 0);
    }
    if(aKeyDownPlayer)
    {
        transform.Rotate(0, -RotationSpeed * Time.deltaTime, 0);
    }
}

public void JumpControllerPlayer()
{
    if (CharContr.isGrounded)
    {

        if (SpaceKeyDownPlayer)
        {
            moveDirection.y = jumpSpeed * Time.deltaTime;
        }
    }
}

public void MovementFinalizer()
{
    moveDirection.y -= gravity * Time.deltaTime;
    CharContr.Move(moveDirection);
}

public void CameraAndListenerController()
{
    if (gameObject.name == ntwmng.Playername)
    {
        if (playercam.enabled == false)
        {
            playercam.enabled = true;
        }
        if (AudioListener.enabled == false)
        {
            AudioListener.enabled = true;
        }
    }
    else
    {
        if (playercam.enabled == true)
        {
            playercam.enabled = false;
        }
        if (AudioListener.enabled == true)
        {
            AudioListener.enabled = false;
        }
    }
}

public void SendKeysToServer()
{
    NetworkStream NtwrkStrm = ServerConnection.GetStream();
    IFormatter Formatter = new BinaryFormatter();

    foreach (KeyCode kcode in Enum.GetValues(typeof(KeyCode)))
    {
        if(Input.GetKeyDown(kcode))
        {
            string type = "Movement Update Key Down";
            string kycode = Convert.ToString(kcode);
            //Debug.Log(kycode);
            Formatter.Serialize(NtwrkStrm, type);
            NtwrkStrm.Flush();
            Formatter.Serialize(NtwrkStrm, ntwmng.Playername);
            NtwrkStrm.Flush();
            Formatter.Serialize(NtwrkStrm, kycode);
            NtwrkStrm.Flush();
        }else
        if(Input.GetKeyUp(kcode))
        {
            string type = "Movement Update Key Up";
            string kycode = Convert.ToString(kcode);
            //Debug.Log(kycode);
            Formatter.Serialize(NtwrkStrm, type);
            NtwrkStrm.Flush();
            Formatter.Serialize(NtwrkStrm, ntwmng.Playername);
            NtwrkStrm.Flush();
            Formatter.Serialize(NtwrkStrm, kycode);
            NtwrkStrm.Flush();
        }
    }
}

public void MovementControllerClones()
{
    if (CharContr.isGrounded)
    {
        moveDirection = new Vector3(0, 0, 0);

        if (wKeyDownClone)
        {
            moveDirection = moveDirection + new Vector3(0, 0, speed * Time.deltaTime);
        }
        if (sKeyDownClone)
        {
            moveDirection = moveDirection + new Vector3(0, 0, -speed * Time.deltaTime);
        }
        if (qKeyDownClone)
        {
            moveDirection = moveDirection + new Vector3(-speed * Time.deltaTime, 0, 0);
        }
        if (eKeyDownClone)
        {
            moveDirection = moveDirection + new Vector3(speed * Time.deltaTime, 0, 0);
        }

        moveDirection = transform.TransformDirection(moveDirection);
        //moveDirection *= speed;
    }

}

public void RotationControllerClones()
{
    if (dKeyDownClone)
    {
        transform.Rotate(0, RotationSpeed * Time.deltaTime, 0);
    }
    if (aKeyDownClone)
    {
        transform.Rotate(0, -RotationSpeed * Time.deltaTime, 0);
    }
}

public void JumpControllerClones()
{
    if (CharContr.isGrounded)
    {

        if (SpaceKeyDownClone)
        {
            moveDirection.y = jumpSpeed* Time.deltaTime;
        }
    }
}

public void MovementFinalizerClones()
{
    moveDirection.y -= gravity * Time.deltaTime;
    CharContr.Move(moveDirection);
}

public void CloneKeyUpdater(string type,string kcode)
{
    //Debug.Log("Key " + kcode + " Clone Updating");
    if (type == "Movement Update Key Down")
    {
        if (kcode == "W")
        {
            wKeyDownClone = true;
        }
        if (kcode == "A")
        {
            aKeyDownClone = true;
        }
        if (kcode == "D")
        {
            dKeyDownClone = true;
        }
        if (kcode == "S")
        {
            sKeyDownClone = true;
        }
        if (kcode == "Q")
        {
            qKeyDownClone = true;
        }
        if (kcode == "E")
        {
            eKeyDownClone = true;
        }
        if (kcode == "Space")
        {
            SpaceKeyDownClone = true;
        }
    }
    else if (type == "Movement Update Key Up")
    {
        if (kcode == "W")
        {
            wKeyDownClone = false;
        }
        if (kcode == "A")
        {
            aKeyDownClone = false;
        }
        if (kcode == "D")
        {
            dKeyDownClone = false;
        }
        if (kcode == "S")
        {
            sKeyDownClone = false;
        }
        if (kcode == "Q")
        {
            qKeyDownClone = false;
        }
        if (kcode == "E")
        {
            eKeyDownClone = false;
        }
        if (kcode == "Space")
        {
            SpaceKeyDownClone = false;
        }
    }
}

public void PlayerKeyUpdater(string type, string kcode)
{
    //Debug.Log("Key down " + kcode + " Updating");
    if (type == "Movement Update Key Down")
    {
        if (kcode == "W")
        {
            wKeyDownPlayer = true;
        }
        if (kcode == "A")
        {
            aKeyDownPlayer = true;
        }
        if (kcode == "D")
        {
            dKeyDownPlayer = true;
        }
        if (kcode == "S")
        {
            sKeyDownPlayer = true;
        }
        if (kcode == "Q")
        {
            qKeyDownPlayer = true;
        }
        if (kcode == "E")
        {
            eKeyDownPlayer = true;
        }
        if (kcode == "Space")
        {
            SpaceKeyDownPlayer = true;
        }
    }
    else if (type == "Movement Update Key Up")
    {
        if (kcode == "W")
        {
            wKeyDownPlayer = false;
        }
        if (kcode == "A")
        {
            aKeyDownPlayer = false;
        }
        if (kcode == "D")
        {
            dKeyDownPlayer = false;
        }
        if (kcode == "S")
        {
            sKeyDownPlayer = false;
        }
        if (kcode == "Q")
        {
            qKeyDownPlayer = false;
        }
        if (kcode == "E")
        {
            eKeyDownPlayer = false;
        }
        if (kcode == "Space")
        {
            SpaceKeyDownPlayer = false;
        }
    }
}

Any help will be muchly appreciated. :)

Edit:
so i have figured out a equation that i am using to try and mimic player movement, as of right now it only work between 0 and 90 degrees, just tell i get it exact. the equation comes out really close, but is just a tiny bit off. Any suggestions? Also, this is running on client side, no server influence, so that I can get the math to an exact. The math comes out about 1 unit per second slower then the players current position. Basically after pressing w for 1 second with speed = 20 the math comes out to 19 and actual position is 20.

here is code

    if (CharContr.velocity != Vector3.zero)//checks if the player is moving
    {
        if (rotation < 90f && rotation > 0f) // makes sure the rotation is 0-90
        {
            percent = (100 / (90 / rotation)) / 100; // gets the percent
            x = x + (percent * speed * Time.deltaTime); //adds to current position multiplied by speed and delta time
            invertPercent = 1 - percent; //gets the percent for z
            z = z + (invertPercent * speed * Time.deltaTime); // adds and stuff again
        }


答:
You forgot this line of code from the first example in your HTML example:</p>

```<code>$registratie_data    =   $_SESSION['registratie_data'];
</code>```

Title: How to change session values in php

Body:
You forgot this line of code from the first example in your HTML example:

$registratie_data    =   $_SESSION['registratie_data'];


问:
AWS EMR Spark- Cloudwatch
I was running an application on AWS EMR-Spark. Here, is the spark-submit job;-

```<code>Arguments : spark-submit --deploy-mode cluster --class com.amazon.JavaSparkPi s3://spark-config-test/SWALiveOrderModelSpark-1.0.assembly.jar s3://spark-config-test/2017-08-08
</code>```

So, AWS uses YARN for resource management. I had a couple of doubts around this while I was observing the cloudwatch metrics :-

1)

What does container allocated imply here? I am using 1 master & 3 slave/executor nodes (all 4 are 8 cores CPU).

2)

I changed my query to:-

```<code>spark-submit --deploy-mode cluster --executor-cores 4 --class com.amazon.JavaSparkPi s3://spark-config-test/SWALiveOrderModelSpark-1.0.assembly.jar s3://spark-config-test/2017-08-08
</code>```

Here the number of cores running is 3. Should it not be 3(number of executors)*4(number of cores) = 12?

答:
1) Container allocated here basically represents the number of spark executors. Spark executor-cores are more like `executor-tasks meaning that you could have your app configured to run one executor per physical cpu and still ask it to have 3 executor-cores per cpu (think hyper-threading).

What happens by default on EMR, when you don't specify the number of spark-executors, is that dynamic allocation is assumed and Spark will only ask from YARN what it thinks it needs in terms of resources. Tried setting explicitly the number of executors to 10 and the containers allocated went upto 6 (max partitions of data).  Also, under the tab "Application history", you can get a detailed view of YARN/Spark executors.

2) "cores" here refer to EMR core nodes and are not the same as spark executor cores. Same for "task" that in the monitoring tab refer to EMR task nodes. That is consistent with my setup, as I have 3 EMR slave nodes.

Title: AWS EMR Spark- Cloudwatch

Body:
I was running an application on AWS EMR-Spark. Here, is the spark-submit job;-

Arguments : spark-submit --deploy-mode cluster --class com.amazon.JavaSparkPi s3://spark-config-test/SWALiveOrderModelSpark-1.0.assembly.jar s3://spark-config-test/2017-08-08

So, AWS uses YARN for resource management. I had a couple of doubts around this while I was observing the cloudwatch metrics :-

1)

What does container allocated imply here? I am using 1 master & 3 slave/executor nodes (all 4 are 8 cores CPU).

2)

I changed my query to:-

spark-submit --deploy-mode cluster --executor-cores 4 --class com.amazon.JavaSparkPi s3://spark-config-test/SWALiveOrderModelSpark-1.0.assembly.jar s3://spark-config-test/2017-08-08

Here the number of cores running is 3. Should it not be 3(number of executors)*4(number of cores) = 12?


问:
How to remove different times from the date from MYSQL
can you help me to update the column of due_date where is something like:

```<code>2017-12-04T02:36:00.000Z
2017-12-04T22:56:00.000Z
2017-12-04T21:34:00.000Z
2017-12-04T06:23:00.000Z
</code>```

to get just pure date like: 2017-12-04

I can use something like:

```<code>UPDATE projects set due_date = REPLACE
(due_date, 'T23:00:00.000Z', '')
</code>```

But the problem is that, in the "due_date" column times can be different like:

```<code>2017-12-04T22:36:00.000Z
2017-12-04T12:22:00.000Z
2017-12-04T15:22:00.000Z
..............
</code>```

Can I update the due_date column to remove completely this part (T15:22:00.000Z), and get just 2017-12-04?
Date column is varchar,

答:
```<code>Execute this query
UPDATE projects set due_date = CAST(due_date AS DATE)
</code>```

Body:
can you help me to update the column of due_date where is something like:

2017-12-04T02:36:00.000Z
2017-12-04T22:56:00.000Z
2017-12-04T21:34:00.000Z
2017-12-04T06:23:00.000Z

to get just pure date like: 2017-12-04

I can use something like:

UPDATE projects set due_date = REPLACE
(due_date, 'T23:00:00.000Z', '')

But the problem is that, in the "due_date" column times can be different like:

2017-12-04T22:36:00.000Z
2017-12-04T12:22:00.000Z
2017-12-04T15:22:00.000Z
..............

Can I update the due_date column to remove completely this part (T15:22:00.000Z), and get just 2017-12-04?
Date column is varchar,


问:
Many RabbitMQ brokers and one celery application
I have a many RabbitMQ brokers and single Celery application.
I would like to route all messages from all brokers to this single application. What is the simplest way to do this?

I know that it can be done by creating a federation between RabbitMQ brokers and I would like to know is there another way to do it.

答:
I think you can't do this in Celery. There is an option to provide list of brokers, but it will be used for failover strategy. Read more here</p>

```<code>broker_url = [
    'transport://userid:password@localhost:port//',
    'transport://userid:password@hostname:port//'
]
</code>```

Body:
I think you can't do this in Celery. There is an option to provide list of brokers, but it will be used for failover strategy. Read more here

broker_url = [
    'transport://userid:password@localhost:port//',
    'transport://userid:password@hostname:port//'
]