问:
combine three tables with keyword with in laravel
I want to join three tables. Here is the DB model in server:

```<code>lecturers
    id - integer (PK)
    ......

examination
    id - integer (PK)
   .....

exam_supervision
    lecturer_id - integer (FK)
    exam_id- integer (FK)
</code>```

Model relation as I implemented in laravel.

```</p>

```<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Examsupervision extends Model {

    public $timestamps = false;

    protected $table = 'exam_supervision';

    protected $fillable = ['lecturer_id', 'exam_id'];
}

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Examination extends Model {

    public $timestamps = false;

    protected $table = 'examination';

    protected $fillable = ['name', 'module_id', 'startdate', 'enddate', 'duration', 'type', 'code', 'status'];

}

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Lecturers extends Model {

    public $timestamps = false;

    protected $table = 'lecturers';

    protected $fillable = ['user_id', 'address', 'phone'];

}
```

<p>```

lecturers, examinations and exam_supervision which is M:M. What I want is find all the examinations of a lecturer.

My code

```<code> public function lecturerViewExaminations($id)
  {

what code to get all exam for a lecturer..say ID 129

  }
</code>```

Returning me empty set. WHat am I doing wrong? It is easy in SQL syntax but in laravel I am finding it very confusing

答:
You are missing ->get() after the last where.

```<code> $examinations= Examsupervision::with('lecturers', 'examinations')->where('lecturer_id', 'id')->where('exam_id', 'id')->get();
</code>```

Body:
I want to join three tables. Here is the DB model in server:

lecturers
    id - integer (PK)
    ......

examination
    id - integer (PK)
   .....

exam_supervision
    lecturer_id - integer (FK)
    exam_id- integer (FK)

Model relation as I implemented in laravel.

```</p>

<pre><code><?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Examsupervision extends Model {

    public $timestamps = false;

    protected $table = 'exam_supervision';

    protected $fillable = ['lecturer_id', 'exam_id'];
}

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Examination extends Model {

    public $timestamps = false;

    protected $table = 'examination';

    protected $fillable = ['name', 'module_id', 'startdate', 'enddate', 'duration', 'type', 'code', 'status'];

}

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Lecturers extends Model {

    public $timestamps = false;

    protected $table = 'lecturers';

    protected $fillable = ['user_id', 'address', 'phone'];

}
</code></pre>

<p>```

lecturers, examinations and exam_supervision which is M:M. What I want is find all the examinations of a lecturer.

My code

 public function lecturerViewExaminations($id)
  {

what code to get all exam for a lecturer..say ID 129

  }

Returning me empty set. WHat am I doing wrong? It is easy in SQL syntax but in laravel I am finding it very confusing

Body:
You are missing ->get() after the last where.

 $examinations= Examsupervision::with('lecturers', 'examinations')->where('lecturer_id', 'id')->where('exam_id', 'id')->get();


来源: stackexchange

问:
Reverse a float number C
I am learning C. We use scanf and printf for input and output data.

We have a question in our lesson: Reverse a float number.

My programming skills are good and I can do this easily.

For example one of my ideas is to convert a float number to int by power 10 then reverse it and convert it to float again. There are lots of other ideas too.

But we have a limit in our question. Use scanf features to reverse number.

I ask my teacher to give me a code for this. He gave below code. I am sorry because I don't understand code clearly. This code give 12 and 33 for 12.33 but this code doesnt work for 12.00001 because we get 12 and 1. When we get this number we reverse them and print it. My teacber asks me a way to solve this but I can't find a way. It is not neccesary to exist a way but Is it possible to help me?

My teacher code:

```<code>int main(){
    int a,b;
    scanf("%d.%d", &a, &b);
    printf("a = %d, b = %d", a, b);
}
</code>```

Thanks.

答:
```<code>#include<stdio.h>
#define MAX 20

void main(void) {
  char str[MAX];
  int i;
  printf("Enter number: ");
  scanf( "%s" , str );

  for (i=0;i<MAX; i++){
      printf("%c",str[MAX-1-i]);
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Reverse a float number C

Body:
I am learning C. We use scanf and printf for input and output data.

We have a question in our lesson: Reverse a float number.

My programming skills are good and I can do this easily.

For example one of my ideas is to convert a float number to int by power 10 then reverse it and convert it to float again. There are lots of other ideas too.

But we have a limit in our question. Use scanf features to reverse number.

I ask my teacher to give me a code for this. He gave below code. I am sorry because I don't understand code clearly. This code give 12 and 33 for 12.33 but this code doesnt work for 12.00001 because we get 12 and 1. When we get this number we reverse them and print it. My teacber asks me a way to solve this but I can't find a way. It is not neccesary to exist a way but Is it possible to help me?

My teacher code:

int main(){
    int a,b;
    scanf("%d.%d", &a, &b);
    printf("a = %d, b = %d", a, b);
}

Thanks.


问:
Deploying actions on google webhook on glitch
I want to deploy this example on glitch. I've added package.js and index.js to my glitch project and built successfully.

However, the code is missing a section to listen for HTTPS requests. In most node.js/express webapps, there is code to indicate which paths trigger which functions, but this is missing from the example. Can you explain to me how it should work and why that part is missing from this example?

答:
The part that "listens to requests" is

```<code>// The Entry point to all our actions
  const actionMap = new Map();
  actionMap.set(ACTION_PRICE, priceHandler);
  actionMap.set(ACTION_TOTAL, totalHandler);
  actionMap.set(ACTION_BLOCK, blockCountHandler);
  actionMap.set(ACTION_MARKET, marketCaptHandler);
  actionMap.set(ACTION_INTERVAL, intervalHandler);

  assistant.handleRequest(actionMap);
</code>```

where each ACTION is an action(in an intent) in Dialogflow and the handler is the corresponding function in your code.

I'd recommend you take a look at

https://codelabs.developers.google.com/codelabs/assistant-codelab/index.html?index=..%2F..%2Findex#0

If you want a good example of an assistant app, though this uses firebase instead of glitch.

Body:
The part that "listens to requests" is

// The Entry point to all our actions
  const actionMap = new Map();
  actionMap.set(ACTION_PRICE, priceHandler);
  actionMap.set(ACTION_TOTAL, totalHandler);
  actionMap.set(ACTION_BLOCK, blockCountHandler);
  actionMap.set(ACTION_MARKET, marketCaptHandler);
  actionMap.set(ACTION_INTERVAL, intervalHandler);

  assistant.handleRequest(actionMap);

where each ACTION is an action(in an intent) in Dialogflow and the handler is the corresponding function in your code.

I'd recommend you take a look at

https://codelabs.developers.google.com/codelabs/assistant-codelab/index.html?index=..%2F..%2Findex#0

If you want a good example of an assistant app, though this uses firebase instead of glitch.


问:
Create new Record Error
HI any help please  I have this code but create d'ont work  (odoo 10)</p>

```<code> for obj in self.browse(self):
                backup_status = 'Backup completed successfully at path : %s ' %(tar_file_path)
                self.env['db.backup.line'].create({
                 'backup_id' : obj.id,
                 'name' : obj.name,
                 'date_time' : time.strftime('%Y-%m-%d %H:%M:%S'),
                 'message' : backup_status,
                 'automatic' : automatic,
                 'done_by' : user_id,
                 'path' : tar_file_path,
                 'file_size' : str(os.path.getsize(tar_file_path)),
                })
</code>```

答:
if you are trying to create a one2many relation, then you must give the related field value. else you cant see that on view. please check the db tables and whether the data is updating. or if you think this is an security issue, then try to create as superuser.
like </p>

```<code>self.env['db.backup.line'].sudo().create({...})
</code>```

<p>.
kindly update question with logs if you have any for more help</p>

Title: Create new Record Error

Body:
HI any help please  I have this code but create d'ont work  (odoo 10)

 for obj in self.browse(self):
                backup_status = 'Backup completed successfully at path : %s ' %(tar_file_path)
                self.env['db.backup.line'].create({
                 'backup_id' : obj.id,
                 'name' : obj.name,
                 'date_time' : time.strftime('%Y-%m-%d %H:%M:%S'),
                 'message' : backup_status,
                 'automatic' : automatic,
                 'done_by' : user_id,
                 'path' : tar_file_path,
                 'file_size' : str(os.path.getsize(tar_file_path)),
                })

Body:
if you are trying to create a one2many relation, then you must give the related field value. else you cant see that on view. please check the db tables and whether the data is updating. or if you think this is an security issue, then try to create as superuser.
like

self.env['db.backup.line'].sudo().create({...})

.
kindly update question with logs if you have any for more help


问:
How to send to texts to listview using fragment activity
I have created fragment activity using viewpager with two tabs, and created listview with two textviews. I want to sent the two texts from tab one to tab two as title and description. I have successfully sent the description, but I failed to send the title (]I can only send one text to listview).

My fragment_one.java :

```<code>public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    viewPager = (ViewPager)view.findViewById(R.id.viewPager);
    Button btnPassData = (Button) view.findViewById(R.id.btnPassData);

    final ListView list=(ListView)view.findViewById(R.id.list_view);
    final EditText inData = (EditText) view.findViewById(R.id.inMessage);
    btnPassData.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SM.sendData(inData.getText().toString().trim());
        }
    });

}

interface SendMessage {
    void sendData(String message);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    try {
        SM = (SendMessage) getActivity();
    } catch (ClassCastException e) {
        throw new ClassCastException("Error in retrieving data. Please try again");
    }
}
}
</code>```

my fragment_two.java :

```<code>public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(
            R.layout.fragment_two, container, false);
    return rootView;

}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    listView = (ListView) view.findViewById(R.id.list_view);
    adapter = new ArrayAdapter<String>(getActivity(), R.layout.single_item,R.id.tvdesc, arrayList);

    listView.setAdapter(adapter);
}

protected void displayReceivedData(String message) {
    arrayList.add(0,message);
    adapter.notifyDataSetChanged();

}
}
</code>```

答:
You should use call back data from  fragment_one to main activity , and send data from activity to fragment_two (and refresh view)

Callback fragment to activity you can use How to make a callback between Activity and Fragment?

and Fragment_two you can set this value in Activity,
EX,
private Fragment mFragmentTwo;
.........
mFragmentTwo= new Fragment();

and can set value by funtion : mFragmentTwo.displayReceivedData(yourString)

Body:
I have created fragment activity using viewpager with two tabs, and created listview with two textviews. I want to sent the two texts from tab one to tab two as title and description. I have successfully sent the description, but I failed to send the title (]I can only send one text to listview).

My fragment_one.java :

public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    viewPager = (ViewPager)view.findViewById(R.id.viewPager);
    Button btnPassData = (Button) view.findViewById(R.id.btnPassData);

    final ListView list=(ListView)view.findViewById(R.id.list_view);
    final EditText inData = (EditText) view.findViewById(R.id.inMessage);
    btnPassData.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SM.sendData(inData.getText().toString().trim());
        }
    });

}

interface SendMessage {
    void sendData(String message);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    try {
        SM = (SendMessage) getActivity();
    } catch (ClassCastException e) {
        throw new ClassCastException("Error in retrieving data. Please try again");
    }
}
}

my fragment_two.java :

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(
            R.layout.fragment_two, container, false);
    return rootView;

}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    listView = (ListView) view.findViewById(R.id.list_view);
    adapter = new ArrayAdapter<String>(getActivity(), R.layout.single_item,R.id.tvdesc, arrayList);

    listView.setAdapter(adapter);
}

protected void displayReceivedData(String message) {
    arrayList.add(0,message);
    adapter.notifyDataSetChanged();

}
}


问:
Result of the sum of random-ordered IEEE 754 double precision floats
Here is a pseudocode of my problem.

I have an array of IEEE 754 double precision positive numbers.

The array can come in a random order but numbers are always the same, just scrambled in their positions. Also these numbers can vary in a very wide range in the valid IEEE range of the double representation.

Once I have the list, I initialize a variable:

```<code>double sum_result = 0.0;
</code>```

And I accumulate the sum on sum_result, in a loop over the whole array. At each step I do:

```<code>sum_result += my_double_array[i]
</code>```

Is it guaranteed that, whatever the order of the initial array of double, if the numbers are the same, the printed out sum result will be always the same?

答:
Let's just take an example: I'm transposing the floating point problem using a model in base 10 with only 2 significant digits to make it simple, operation result being rounded to nearest.

Say we must sum the 3 numbers 9.9 + 8.4 + 1.4

The exact result is 19.7 but we have only two digits so it hould be rounded to 20.

If we first sum 9.9 + 8.4 we get 18.3 which is then rounded to 18.

We then sum 18. + 1.4 we get 19.4 rounded to 19..

If we first sum the last two terms 8.4 + 1.4 we get 9.8, no rounding required yet.

Then 9.9 + 9.8 we get 19.7 rounded to 20., a different result.

(9.9 + 8.4) + 1.4 differs from 9.9 + (8.4 + 1.4), the sum operation is not associative and this is due to intermediate rounding. We could exhibit similar examples with other rounding modes too...

The problem is exactly the same in base 2 with 53 bits significand: intermediate rounding will be causing the non associativity whatever the base or significand length.

To eliminate the problem, you could either sort the numbers so that the order is allways the same, or eliminate the intermediate rounding and keep only the final one, for example with a super accumulator like this https://arxiv.org/pdf/1505.05571.pdf

...Or just accept to live with an approximate result (up to you to analyze average or worse error and decide if acceptable...).

Body:
Here is a pseudocode of my problem.

I have an array of IEEE 754 double precision positive numbers.

The array can come in a random order but numbers are always the same, just scrambled in their positions. Also these numbers can vary in a very wide range in the valid IEEE range of the double representation.

Once I have the list, I initialize a variable:

double sum_result = 0.0;

And I accumulate the sum on sum_result, in a loop over the whole array. At each step I do:

sum_result += my_double_array[i]

Is it guaranteed that, whatever the order of the initial array of double, if the numbers are the same, the printed out sum result will be always the same?


问:
How to package and deploy cumulocity server-side agents?
We are creating a server-side agent which periodically fetches data from nodes and maps this data to cumulocity measurements, events.

What is an elegant approach for hosting and/or packaging such a server-side agent?

We are hosting our own instance of the Cumulocity platform.

It's preferable to keep this server-side agent as 'close' to the core platform as possible, e.g. share some core agent framework dependencies.

We'd like to limit the amount of setting up additional environments or containers (e.g. Tomcat).

Cumulocity uses Karaf, would it make any sense to deploy the server-side agent into Karaf as a bundle?

Is there any recommended approach for hosting server-side agents? Does the cumulocity platform offer an alternative to deploying the agent to some "own environment"?

The Cumulocity examples repository contains the "tracker-agent" server-side agent example, which is an embedded tomcat Java application. There is little information about the intended deployment location.

答:
I don't recommend deploying agents/microservices directly into the core Karaf server, since that endangers the resources available to the core APIs and is not supported. (I.e., will likely be overwritten with the next upgrade...)

Typically, people just provision an additional VM or docker next to Cumulocity to place their agents/microservices in. On top of that, we, for example, often use Spring Boot, so the effort is pretty low (java -jar ...).

We do have a hosting system for agents/microservices and will make that generally available also for others to use in Q1/2018. Follow the announcement channel at https://support.cumulocity.com to stay posted...


问:
Explicitly cast from JSON to double precision in SQLAlchemy
I am implementing a query for average, but how can I explicitly define double in SQLAlchemy as defined in the below PostgreSQL query:

```<code>SELECT avg((tags->>'price')::double precision) from parcel_table
</code>```

The Python:

```<code>parcel_table.query.\
    with_entities(
        func.avg(parcel_table.tags["price"]).
            label('average`')).\
    filter(
        parcel_table.time_stamp.between("'2017-01-01 00:00:000'",
                                        "'2017-10-01 00:00:000'"),
        parcel_table.name== 'sakshi').\
    first()
</code>```

答:
The expression

```<code>(tags->>'price')::double precision
</code>```

being a JSON index operation with a cast has a nice shortcut in SQLAlchemy:

```<code>from sqlalchemy.dialects import postgresql

parcel_table.tags["price"].astext.cast(postgresql.DOUBLE_PRECISION)
</code>```

Note that the name "price" would hint at this being about money, and floating point numbers and money are a bad match, usually.

Body:
I am implementing a query for average, but how can I explicitly define double in SQLAlchemy as defined in the below PostgreSQL query:

SELECT avg((tags->>'price')::double precision) from parcel_table

The Python:

parcel_table.query.\
    with_entities(
        func.avg(parcel_table.tags["price"]).
            label('average`')).\
    filter(
        parcel_table.time_stamp.between("'2017-01-01 00:00:000'",
                                        "'2017-10-01 00:00:000'"),
        parcel_table.name== 'sakshi').\
    first()

Body:
The expression

(tags->>'price')::double precision

being a JSON index operation with a cast has a nice shortcut in SQLAlchemy:

from sqlalchemy.dialects import postgresql

parcel_table.tags["price"].astext.cast(postgresql.DOUBLE_PRECISION)

Note that the name "price" would hint at this being about money, and floating point numbers and money are a bad match, usually.


问:
Drone.io | Create docker-compose settings
I can't connect to Drone.io with my GitHub.
And have several problems with the app:

1) drone-agent can't connect to server

```<code>dodge@comp:$drone agent
28070:M 15 Nov 22:04:01.906 * connecting to server http://<my_ip>
28070:M 15 Nov 22:04:01.906 # connection failed, retry in 15s. websocket.Dial http://<my_ip>: bad scheme
</code>```

2) I can't add Postgresql to docker-compose.
When I add this text from your site

```<code>DRONE_DATABASE_DRIVER: postgres
DRONE_DATABASE_DATASOURCE: postgres://root:password@1.2.3.4:5432/postgres?sslmode=disable
</code>```

I have this error

```<code>INFO: 2017/11/15 19:42:33 grpc: addrConn.resetTransport failed to create client transport: connection error: desc = "transport: Error while dialing dial tcp 172.18.0.2:9000: getsockopt: connection refused"; Reconnecting to {drone-server:9000 <nil>}
</code>```

3) When I use only a server and an agent in docker-compose I have this error

```<code>dodge@comp:$drone server

ERRO[0000] sql: unknown driver "sqlite3" (forgotten import?)
FATA[0000] database connection failed
</code>```

docker-compose.yml

```<code>version: '2'
services:
  drone-server:
    image: drone/drone:0.8
    ports:
      - 80:8000
      - 9000
    volumes:
      - /var/lib/drone:/var/lib/drone/
      - ./drone:/var/lib/drone/
    restart: always
    environment:
      - DRONE_DEBUG=true
      - DRONE_OPEN=true
      - DRONE_HOST=http://172.18.0.2
      - DRONE_GITHUB=true
      - DRONE_GITHUB_CLIENT=secretid
      - DRONE_GITHUB_SECRET=secretpass
      - DRONE_SECRET=password

  drone-agent:
    image: drone/agent:0.8
    command: agent
    restart: always
    depends_on: [ drone-server ]
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      - DRONE_SERVER=drone-server:9000
      - DRONE_SECRET=password
</code>```

4) I cannot start tests in my project. Maybe I missed something during the setup.

答:
```<code>version: '2'

services:
  drone-server:
    image: drone/drone:latest
    ports:
      - 80:8000
      - 9000:9000
    volumes:
      - /var/lib/drone:/var/lib/drone/
      - ./drone:/var/lib/drone/
    restart: always
    environment:
      - DRONE_DEBUG=true
      - DRONE_HOST=http://<container_ip_server>
      - DRONE_OPEN=true
      - DRONE_GITHUB=true
      - DRONE_GITHUB_CLIENT=<client_git>
      - DRONE_GITHUB_SECRET=<secret_git>
      - DRONE_SECRET=<secret_drone>
      - DRONE_GITHUB_MERGE_REF=true

  drone-agent:
    image: drone/agent:latest
    command: agent
    restart: always
    depends_on: [ drone-server ]
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      - DRONE_SERVER=drone-server:9000
      - DRONE_SECRET=<drone_secret>
</code>```

This workes fine.

Body:
I can't connect to Drone.io with my GitHub.
And have several problems with the app:

1) drone-agent can't connect to server

dodge@comp:$drone agent
28070:M 15 Nov 22:04:01.906 * connecting to server http://<my_ip>
28070:M 15 Nov 22:04:01.906 # connection failed, retry in 15s. websocket.Dial http://<my_ip>: bad scheme

2) I can't add Postgresql to docker-compose.
When I add this text from your site

DRONE_DATABASE_DRIVER: postgres
DRONE_DATABASE_DATASOURCE: postgres://root:password@1.2.3.4:5432/postgres?sslmode=disable

I have this error

INFO: 2017/11/15 19:42:33 grpc: addrConn.resetTransport failed to create client transport: connection error: desc = "transport: Error while dialing dial tcp 172.18.0.2:9000: getsockopt: connection refused"; Reconnecting to {drone-server:9000 <nil>}

3) When I use only a server and an agent in docker-compose I have this error

dodge@comp:$drone server

ERRO[0000] sql: unknown driver "sqlite3" (forgotten import?)
FATA[0000] database connection failed

docker-compose.yml

version: '2'
services:
  drone-server:
    image: drone/drone:0.8
    ports:
      - 80:8000
      - 9000
    volumes:
      - /var/lib/drone:/var/lib/drone/
      - ./drone:/var/lib/drone/
    restart: always
    environment:
      - DRONE_DEBUG=true
      - DRONE_OPEN=true
      - DRONE_HOST=http://172.18.0.2
      - DRONE_GITHUB=true
      - DRONE_GITHUB_CLIENT=secretid
      - DRONE_GITHUB_SECRET=secretpass
      - DRONE_SECRET=password

  drone-agent:
    image: drone/agent:0.8
    command: agent
    restart: always
    depends_on: [ drone-server ]
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      - DRONE_SERVER=drone-server:9000
      - DRONE_SECRET=password

4) I cannot start tests in my project. Maybe I missed something during the setup.

Body:
version: '2'

services:
  drone-server:
    image: drone/drone:latest
    ports:
      - 80:8000
      - 9000:9000
    volumes:
      - /var/lib/drone:/var/lib/drone/
      - ./drone:/var/lib/drone/
    restart: always
    environment:
      - DRONE_DEBUG=true
      - DRONE_HOST=http://<container_ip_server>
      - DRONE_OPEN=true
      - DRONE_GITHUB=true
      - DRONE_GITHUB_CLIENT=<client_git>
      - DRONE_GITHUB_SECRET=<secret_git>
      - DRONE_SECRET=<secret_drone>
      - DRONE_GITHUB_MERGE_REF=true

  drone-agent:
    image: drone/agent:latest
    command: agent
    restart: always
    depends_on: [ drone-server ]
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      - DRONE_SERVER=drone-server:9000
      - DRONE_SECRET=<drone_secret>

This workes fine.


问:
How to check the type of a parameter in Haxe
I'm converting a JavaScript library to Haxe.
It seems Haxe is very similar to JS, but in working I got a problem for function overwriting.

For example, in the following function param can be an an integer or an array.

JavaScript:

```<code>function testFn(param) {
    if (param.constructor.name == 'Array') {
        console.log('param is Array');
        // to do something for Array value
    } else if (typeof param === 'number') {
        console.log('param is Integer');
        // to do something for Integer value
    } else {
        console.log('unknown type');
    }
}
</code>```

Haxe:

```<code>function testFn(param: Dynamic) {
    if (Type.typeof(param) == 'Array') { // need the checking here
        trace('param is Array');
        // to do something for Array value
    } else if (Type.typeof(param) == TInt) {
        trace('param is Integer');
        // to do something for Integer value
    } else {
        console.log('unknown type');
    }
}
</code>```

Of course Haxe supports Type.typeof() but there isn't any ValueType for Array. How can I solve this problem?

答:
In Haxe, you'd usually use the is operator for this instead of Type.typeof(). Behind the scenes, the operator uses Std.isOfType().

```<code>if (param is Array) {
    trace('param is Array');
} else if (param is Int) {
    trace('param is Integer');
} else {
    trace('unknown type');
}
</code>```

It's possible to use Type.typeof() as well, but less common - you can use pattern matching for this purpose. Arrays are of ValueType.TClass, which has a c:Class<Dynamic> parameter:

```<code>switch (Type.typeof(param)) {
    case TClass(Array):
        trace("param is Array");
    case TInt:
        trace("param is Int");
    case _:
        trace("unknown type");
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm converting a JavaScript library to Haxe.
It seems Haxe is very similar to JS, but in working I got a problem for function overwriting.

For example, in the following function param can be an an integer or an array.

JavaScript:

function testFn(param) {
    if (param.constructor.name == 'Array') {
        console.log('param is Array');
        // to do something for Array value
    } else if (typeof param === 'number') {
        console.log('param is Integer');
        // to do something for Integer value
    } else {
        console.log('unknown type');
    }
}

Haxe:

function testFn(param: Dynamic) {
    if (Type.typeof(param) == 'Array') { // need the checking here
        trace('param is Array');
        // to do something for Array value
    } else if (Type.typeof(param) == TInt) {
        trace('param is Integer');
        // to do something for Integer value
    } else {
        console.log('unknown type');
    }
}

Of course Haxe supports Type.typeof() but there isn't any ValueType for Array. How can I solve this problem?

Body:
In Haxe, you'd usually use the is operator for this instead of Type.typeof(). Behind the scenes, the operator uses Std.isOfType().

if (param is Array) {
    trace('param is Array');
} else if (param is Int) {
    trace('param is Integer');
} else {
    trace('unknown type');
}

It's possible to use Type.typeof() as well, but less common - you can use pattern matching for this purpose. Arrays are of ValueType.TClass, which has a c:Class<Dynamic> parameter:

switch (Type.typeof(param)) {
    case TClass(Array):
        trace("param is Array");
    case TInt:
        trace("param is Int");
    case _:
        trace("unknown type");
}


问:
ttk treeview get tags
Hello i try to get the tags attribute
i have this

```<code>def treeview(self):
    w = self.widget
    curItem = w.focus()
    print w.item(curItem)

lisswidget = ttk.Treeview(photoFrame)
lisswidget.bind("<<TreeviewSelect>>", treeview)
lisswidget.insert('', 'end', "", open=True, image=IMG, tags="MyTags")
</code>```

The console return :

```<code>{'text': '', 'image': [u'pyimage9'], 'values': '', 'open': 1, 'tags': ['MyTags']}
</code>```

How i can extract tags ?

Thx

答:
I find it, it's a dictionnary so i do like this :</p>

```<code>print w.item(curItem)['tags']
</code>```

Title: ttk treeview get tags

Body:
Hello i try to get the tags attribute
i have this

def treeview(self):
    w = self.widget
    curItem = w.focus()
    print w.item(curItem)

lisswidget = ttk.Treeview(photoFrame)
lisswidget.bind("<<TreeviewSelect>>", treeview)
lisswidget.insert('', 'end', "", open=True, image=IMG, tags="MyTags")

The console return :

{'text': '', 'image': [u'pyimage9'], 'values': '', 'open': 1, 'tags': ['MyTags']}

How i can extract tags ?

Thx

Body:
I find it, it's a dictionnary so i do like this :

print w.item(curItem)['tags']


问:
Wrong ordering items (fields) in JSON object in Swift
For example: I have a JSON like this:

```<code>{
    name : "Name",
    info: {
            info_one : "A",
            info_two : "B",
            info_three : "C"
    }
}
</code>```

When I got info item by data["info"] as? [String:String], The result was wrong order. Like:

```<code>[("info_two":"B"), ("info_three":"C"), ("info_one":"A")]
</code>```

How can I fix it? Please help me, thank you!

答:
In Objective-c, Dictionary is order less.
But it`s depend on your requirement, follow it</p>

Body:
For example: I have a JSON like this:

{
    name : "Name",
    info: {
            info_one : "A",
            info_two : "B",
            info_three : "C"
    }
}

When I got info item by data["info"] as? [String:String], The result was wrong order. Like:

[("info_two":"B"), ("info_three":"C"), ("info_one":"A")]

How can I fix it? Please help me, thank you!


问:
Connecting Database to Application with NameCheap
I'm trying to connect a database to my application I'm designing (Android in Android Studio) and I keep running into errors. I'm designing a login page, so putting the database in the resource folder isn't an option.

I followed a tutorial that used 000webhost, so I tried that. My PHP code always delivers a 'not connected message'. I also tried setting up a database via NameCheap on my hosting and connecting via that, but my PHP code gives the same error. In hopes that it's just an error I've made, I'm going to paste the PHP code here (the app code is irrelevant, the PHP is directly giving me an error).

Here's the PHP:

```<code><?php
    $con = mysqli_connect("localhost", "ID HERE", "PASSHERE", "DBNAMEHERE");
    if (!$conn){
        echo "Not Connected :(";
    } else{
        echo "Connection Established! :)";
    }
    $name = $_POST["name"];
    $company = $_POST["company_id"];
    $username = $_POST["username"];
    $password = $_POST["password"];
    $email = $_POST["email"];
    $phone = $_POST["phone"];

    $statement = mysqli_prepare($con, "INSERT INTO user (name, username, password, email, company_id, phone) VALUES (?, ?, ?, ?, ?, ?)");
    mysqli_stmt_bind_param($statement, "siss", $name, $username, $password, $email, $companyid, $phone);
    mysqli_stmt_execute($statement);

    $response = array();
    $response["success"] = true;

    echo json_encode($response);
?>
</code>```

Obviously with the values up top entered, just clearing them for security sake.

答:
You have a typo $con and $conn.
If it doesn't works, make sure you doesn't have active VPN.

Body:
I'm trying to connect a database to my application I'm designing (Android in Android Studio) and I keep running into errors. I'm designing a login page, so putting the database in the resource folder isn't an option.

I followed a tutorial that used 000webhost, so I tried that. My PHP code always delivers a 'not connected message'. I also tried setting up a database via NameCheap on my hosting and connecting via that, but my PHP code gives the same error. In hopes that it's just an error I've made, I'm going to paste the PHP code here (the app code is irrelevant, the PHP is directly giving me an error).

Here's the PHP:

<?php
    $con = mysqli_connect("localhost", "ID HERE", "PASSHERE", "DBNAMEHERE");
    if (!$conn){
        echo "Not Connected :(";
    } else{
        echo "Connection Established! :)";
    }
    $name = $_POST["name"];
    $company = $_POST["company_id"];
    $username = $_POST["username"];
    $password = $_POST["password"];
    $email = $_POST["email"];
    $phone = $_POST["phone"];

    $statement = mysqli_prepare($con, "INSERT INTO user (name, username, password, email, company_id, phone) VALUES (?, ?, ?, ?, ?, ?)");
    mysqli_stmt_bind_param($statement, "siss", $name, $username, $password, $email, $companyid, $phone);
    mysqli_stmt_execute($statement);

    $response = array();
    $response["success"] = true;

    echo json_encode($response);
?>

Obviously with the values up top entered, just clearing them for security sake.


问:
What should I use for performance sensitive data access?
So I have an application which requires very fast access to large volumes of data and we're at the stage where we're undergoing a large re-design of the database, which gives a good opertunity to re-write the data access layer if nessersary!

Currently in our data access layer we use manually created entities along with plain SQL to fill them. This is pretty fast, but this technology is really getting old, and I'm concerned we're missing out on a newer framework or data access method which could be better in terms of neatness and maintainability.

We've seen the Entity Framework, but after some research it just seems that the benefit of the ORM it gives is not enough to justify the lower performance and as some of our queries are getting complex I'm sure performance with the EF would become more of an issue.

So it is a case of sticking with our current methods of data access, or is there something a bit neater than manually creating and maintaining entities?

I guess the thing that's bugging me is just opening our data layer solution and seeing lots of entities, all of which need to be maintained exactly in line with the database, which sometimes can be a lot of work, but then maybe this is the price we pay for performance?

Any ideas, comments and suggestions are very appreciated! :)

Thanks,

Andy.

** Update **

Forgot to mention that we really need to be able to handle using Azure (client requirements), which currently stops us from using stored procedures. ** Update 2 ** Actually we have an interface layer for our DAL which means we can created an Azure implementation which just override data access methods from the Local implementation which aren't suitable for Azure, so I guess we could just use stored procedures for performance sensitive local databases with EF for the cloud.

答:
I would use an ORM layer (Entity Framework, NHibernate etc) for management of individual entities. For example, I would use the ORM / entities layers to allow users to make edits to entities. This is because thinking of your data as entities is conceptually simpler and the ORMs make it pretty easy to code this stuff without ever having to program any SQL.

For the bulk reporting side of things, I would definitely not use an ORM layer. I would probably create a separate class library specifically for standard reports, which creates SQL statements itself or calls sprocs. ORMs are not really for bulk reporting and you'll never get the same flexibility of querying through the ORM as through hand-coded SQL.

ContentLicense: CC BY-SA 2.5


问:
Compare iterated character from std::string with unicode C++
i've been struggling with this problem for quite some time and this is my first for dealing with unicode or UTF-8 basically.

This is what i'm trying to do, I just want to iterate a std::string containing with combination from normal alphabet and a unicode symbol, which in my case is en dash "–". more info: http://www.fileformat.info/info/unicode/char/2013/index.htm

this is the code that i've tried and it won't run:

```<code>#include <iostream>
#include <string>

int main()
{
    std::string str = "test string with symbol – and !";
    for (auto &letter : str) {
        if (letter == "–") {
            std::cout << "found!" << std::endl;
        }
    }
    return 0;
}
</code>```

This is the result of my compiler:

```<code>main.cpp: In function 'int main()':
main.cpp:18:23: error: ISO C++ forbids comparison between pointer and
integer [-fpermissive]
     if (letter == "–") {
                   ^
</code>```

also, when i was looking through the internet i found an interesting information for this type of task that i need to solve. How to search a non-ASCII character in a c++ string?

But when i tried to modified my code with those UTF-8 hex code, it also won't run:

```<code>    if (letter == "\xE2\x80\x93") {
        std::cout << "found!" << std::endl;
    }
</code>```

with the exact same message from my compiler, which is c++ forbids comparison between pointer and integer.

Did i miss something? or do i need to use libraries like ICU or Boost?
Your help is much appreciated. thank you!

Update

based on the answer from UnholySheep, i've been improving my code but it's still cannot work. it can pass the compiling but when i tried to run it, it can't ouput "found!" to out. so, how do i solve this? thank you.

答:
As said in comment by UnholySheep, a char literal "–" is a char array. Assuming an utf8 representation, char em_dash = "–"; is the same as char em_dash = {'\xe2', '\x80', '\x93'};.

You can only find true characters with your current code. For example this would work correctly:

```<code>...
if (letter == '!')
...
</code>```

because '!' is a char constant.

If you only want to process unicode characters in the Basic Multilingual Plane (code below 0xFFFF), using wide characters should be enough as proposed in @ArashMohammadi's answer. An alternate solution for characters outside the BMP like emoji chars would be to use a std::u32string in which every unicode char is represented by a single char32_t character.

If you want to directly process a UTF8 encoded string of single byte characters, you will have to use the compare method:

```<code>std::string em_dash = "–"; // or "\xe2\x80\x93"
...
    for (size_t pos=0; pos <= str.size() - em_dash.size(); pos++) {
        if (str.compare(pos, em_dash.size(), em_dash()) == 0) {
            std::cout << "found!" << std::endl;
        }
    }
...
</code>```

or directly use the find method:

```<code>...
    if (str.find(em_dash) != str.npos) {
        std::cout << "found!" << std::endl;
    }
...
</code>```

Body:
i've been struggling with this problem for quite some time and this is my first for dealing with unicode or UTF-8 basically.

This is what i'm trying to do, I just want to iterate a std::string containing with combination from normal alphabet and a unicode symbol, which in my case is en dash "–". more info: http://www.fileformat.info/info/unicode/char/2013/index.htm

this is the code that i've tried and it won't run:

#include <iostream>
#include <string>

int main()
{
    std::string str = "test string with symbol – and !";
    for (auto &letter : str) {
        if (letter == "–") {
            std::cout << "found!" << std::endl;
        }
    }
    return 0;
}

This is the result of my compiler:

main.cpp: In function 'int main()':
main.cpp:18:23: error: ISO C++ forbids comparison between pointer and
integer [-fpermissive]
     if (letter == "–") {
                   ^

also, when i was looking through the internet i found an interesting information for this type of task that i need to solve. How to search a non-ASCII character in a c++ string?

But when i tried to modified my code with those UTF-8 hex code, it also won't run:

    if (letter == "\xE2\x80\x93") {
        std::cout << "found!" << std::endl;
    }

with the exact same message from my compiler, which is c++ forbids comparison between pointer and integer.

Did i miss something? or do i need to use libraries like ICU or Boost?
Your help is much appreciated. thank you!

Update

based on the answer from UnholySheep, i've been improving my code but it's still cannot work. it can pass the compiling but when i tried to run it, it can't ouput "found!" to out. so, how do i solve this? thank you.

Body:
As said in comment by UnholySheep, a char literal "–" is a char array. Assuming an utf8 representation, char em_dash = "–"; is the same as char em_dash = {'\xe2', '\x80', '\x93'};.

You can only find true characters with your current code. For example this would work correctly:

...
if (letter == '!')
...

because '!' is a char constant.

If you only want to process unicode characters in the Basic Multilingual Plane (code below 0xFFFF), using wide characters should be enough as proposed in @ArashMohammadi's answer. An alternate solution for characters outside the BMP like emoji chars would be to use a std::u32string in which every unicode char is represented by a single char32_t character.

If you want to directly process a UTF8 encoded string of single byte characters, you will have to use the compare method:

std::string em_dash = "–"; // or "\xe2\x80\x93"
...
    for (size_t pos=0; pos <= str.size() - em_dash.size(); pos++) {
        if (str.compare(pos, em_dash.size(), em_dash()) == 0) {
            std::cout << "found!" << std::endl;
        }
    }
...

or directly use the find method:

...
    if (str.find(em_dash) != str.npos) {
        std::cout << "found!" << std::endl;
    }
...


问:
SpriteKit: sprite looks blurry (with ghosting) at high velocity but fine at low velocity
When using high velocity (linear or angular) in SpriteKit, sprites look blurry as if there are "ghosts" trailing the sprite. The sprite looks fine at slow speeds.

Below is a screenshot and GIF illustrating the blurriness/ghosting problem with high linear velocity, but the problem also occurs with the angularVelocity property.

Ball Code (use SKScene below to reproduce blurriness):

```<code>    let radius = CGFloat(8)

    let body = SKPhysicsBody(circleOfRadius: radius)
    body.isDynamic = true
    body.affectedByGravity = false
    body.allowsRotation = true
    body.friction = 0
    body.restitution = 0.0
    body.linearDamping = 0.0
    body.angularDamping = 0
    body.categoryBitMask = categoryBitMask

    let ball = SKShapeNode(circleOfRadius: radius)
    ball.physicsBody = body
    ball.physicsBody?.velocity.dx = 0
    ball.physicsBody?.velocity.dy = -1200
</code>```

Looks fine:

```<code>ball.physicsBody?.velocity.dy = -200
</code>```

Looks blurry:

```<code>ball.physicsBody?.velocity.dy = -1200
</code>```

Screenshot:

GIF:

SKScene (drop in project and present scene to see blurriness):

```<code>import Foundation
import SpriteKit

class TestScene : SKScene, SKPhysicsContactDelegate {
    let BallBitMask                   : UInt32 = 0x1 << 1
    let BottomWallBitMask             : UInt32 = 0x1 << 3
    let TopWallBitMask                : UInt32 = 0x1 << 4
    let RightWallBitMask              : UInt32 = 0x1 << 5
    let LeftWallBitMask               : UInt32 = 0x1 << 6

    let SceneBackgroundColor = UIColor(red: 58/255.0, green: 50/255.0, blue: 96/255.0, alpha: 1.0)

    let HorizontalWallHeight = CGFloat(10)
    let VerticallWallWidth = CGFloat(5)

    override init() {
        super.init()
    }

    override init(size: CGSize) {
        super.init(size: size)
        doInit()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    fileprivate func doInit() {
        // Set background
        backgroundColor = SceneBackgroundColor

        // Set scale mode
        scaleMode = .resizeFill

        // Set anchor point to screen center
        anchorPoint = CGPoint(x: 0.5, y: 0.5)

        // Add walls
        layoutWalls()

        // Create ball
        let radius = CGFloat(8)
        let body = SKPhysicsBody(circleOfRadius: radius)
        body.isDynamic = true
        body.affectedByGravity = false
        body.allowsRotation = true
        body.friction = 0
        body.restitution = 0.0
        body.linearDamping = 0.0
        body.angularDamping = 0
        body.categoryBitMask = BallBitMask
        body.collisionBitMask =  TopWallBitMask | RightWallBitMask | BottomWallBitMask | LeftWallBitMask

        let ball = SKShapeNode(circleOfRadius: radius)
        ball.fillColor = UIColor.orange
        ball.physicsBody = body
        ball.physicsBody?.velocity.dx = 0
        ball.physicsBody?.velocity.dy = -1200

        // Add ball to scene
        addChild(ball)
    }

    fileprivate func layoutWalls() {
        // Set wall offset
        let wallOffset = CGFloat(3)

        // Layout bottom wall
        let bottomWallSize = CGSize(width: UIScreen.main.bounds.width, height: HorizontalWallHeight)
        let bottomWall = SKSpriteNode(color: UIColor.red, size: bottomWallSize)
        bottomWall.position.y = -UIScreen.main.bounds.height/2 - bottomWallSize.height/2 - wallOffset
        bottomWall.physicsBody = createWallPhysics(categoryBitMask: BottomWallBitMask, wallSize: bottomWallSize)
        addChild(bottomWall)

        // Layout top wall
        let topWallSize = CGSize(width: UIScreen.main.bounds.width, height: HorizontalWallHeight)
        let topWall = SKSpriteNode(color: UIColor.red, size: topWallSize)
        topWall.position.y = UIScreen.main.bounds.height/2 + topWallSize.height/2 + wallOffset
        topWall.physicsBody = createWallPhysics(categoryBitMask: TopWallBitMask, wallSize: topWallSize)
        addChild(topWall)

        // Layout right wall
        let rightWallSize = CGSize(width: VerticallWallWidth, height: UIScreen.main.bounds.height)
        let rightWall = SKSpriteNode(color: UIColor.blue, size: rightWallSize)
        rightWall.position.x = UIScreen.main.bounds.width/2 + rightWallSize.width/2 + wallOffset
        rightWall.physicsBody = createWallPhysics(categoryBitMask: RightWallBitMask, wallSize: rightWallSize)
        addChild(rightWall)

        // Layout left wall
        let leftWallSize = CGSize(width: VerticallWallWidth, height: UIScreen.main.bounds.height)
        let leftWall = SKSpriteNode(color: UIColor.blue, size: leftWallSize)
        leftWall.position.x = -UIScreen.main.bounds.width/2 - leftWallSize.width/2 - wallOffset
        leftWall.physicsBody = createWallPhysics(categoryBitMask: LeftWallBitMask, wallSize: leftWallSize)
        addChild(leftWall)
    }

    fileprivate func createWallPhysics(categoryBitMask: UInt32, wallSize: CGSize) -> SKPhysicsBody {
        // Create new physics body for wall
        let physicsBody = SKPhysicsBody(edgeLoopFrom: CGRect(x: -wallSize.width/2, y: -wallSize.height/2, width: wallSize.width, height: wallSize.height))
        physicsBody.isDynamic = true
        physicsBody.friction = 0
        physicsBody.restitution = 1.0
        physicsBody.linearDamping = 0
        physicsBody.angularDamping = 0.0
        physicsBody.categoryBitMask = categoryBitMask

        // Return body
        return physicsBody
    }
}
</code>```

答:
Which one of these looks more ghosty?

The "trick" is being performed by the eye. We're not equipped to deal with screens at a lowly 60fps with fast moving objects. We sustain an image on the screen and in position through a faux persistence of vision so our brains and consciousness can figure out how fast something is "moving" on the screen.

In real life we get a near infinite number of "frames" to process movement with, and depth and all sorts of other cues, so we rarely do this anywhere near as much.

We still do it, but it's much less perceptible because we've got that near infinite number of frames to call on.

The below three images do different things to reveal this in different ways.

The first one is linear speed, accelerates instantly to its velocity of rotation and stops instantly.

The second has a ramp up and ramp down to its rotational speed, which has a higher peak speed of rotation. This has an interesting effect on the brain that permits it to prepare for the velocity that's going to be achieved.

The final has a lot of fake motion blur (too much for real world motion graphics usage) that shows how effective blur is at solving the effect of this problem, and why slow shutter speeds are so incredibly important to movie making.

Linear rotation rate:

Accel and decel:

Heavily blurred:

Body:
When using high velocity (linear or angular) in SpriteKit, sprites look blurry as if there are "ghosts" trailing the sprite. The sprite looks fine at slow speeds.

Below is a screenshot and GIF illustrating the blurriness/ghosting problem with high linear velocity, but the problem also occurs with the angularVelocity property.

Ball Code (use SKScene below to reproduce blurriness):

    let radius = CGFloat(8)

    let body = SKPhysicsBody(circleOfRadius: radius)
    body.isDynamic = true
    body.affectedByGravity = false
    body.allowsRotation = true
    body.friction = 0
    body.restitution = 0.0
    body.linearDamping = 0.0
    body.angularDamping = 0
    body.categoryBitMask = categoryBitMask

    let ball = SKShapeNode(circleOfRadius: radius)
    ball.physicsBody = body
    ball.physicsBody?.velocity.dx = 0
    ball.physicsBody?.velocity.dy = -1200

Looks fine:

ball.physicsBody?.velocity.dy = -200

Looks blurry:

ball.physicsBody?.velocity.dy = -1200

Screenshot:

GIF:

SKScene (drop in project and present scene to see blurriness):

import Foundation
import SpriteKit

class TestScene : SKScene, SKPhysicsContactDelegate {
    let BallBitMask                   : UInt32 = 0x1 << 1
    let BottomWallBitMask             : UInt32 = 0x1 << 3
    let TopWallBitMask                : UInt32 = 0x1 << 4
    let RightWallBitMask              : UInt32 = 0x1 << 5
    let LeftWallBitMask               : UInt32 = 0x1 << 6

    let SceneBackgroundColor = UIColor(red: 58/255.0, green: 50/255.0, blue: 96/255.0, alpha: 1.0)

    let HorizontalWallHeight = CGFloat(10)
    let VerticallWallWidth = CGFloat(5)

    override init() {
        super.init()
    }

    override init(size: CGSize) {
        super.init(size: size)
        doInit()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    fileprivate func doInit() {
        // Set background
        backgroundColor = SceneBackgroundColor

        // Set scale mode
        scaleMode = .resizeFill

        // Set anchor point to screen center
        anchorPoint = CGPoint(x: 0.5, y: 0.5)

        // Add walls
        layoutWalls()

        // Create ball
        let radius = CGFloat(8)
        let body = SKPhysicsBody(circleOfRadius: radius)
        body.isDynamic = true
        body.affectedByGravity = false
        body.allowsRotation = true
        body.friction = 0
        body.restitution = 0.0
        body.linearDamping = 0.0
        body.angularDamping = 0
        body.categoryBitMask = BallBitMask
        body.collisionBitMask =  TopWallBitMask | RightWallBitMask | BottomWallBitMask | LeftWallBitMask

        let ball = SKShapeNode(circleOfRadius: radius)
        ball.fillColor = UIColor.orange
        ball.physicsBody = body
        ball.physicsBody?.velocity.dx = 0
        ball.physicsBody?.velocity.dy = -1200

        // Add ball to scene
        addChild(ball)
    }

    fileprivate func layoutWalls() {
        // Set wall offset
        let wallOffset = CGFloat(3)

        // Layout bottom wall
        let bottomWallSize = CGSize(width: UIScreen.main.bounds.width, height: HorizontalWallHeight)
        let bottomWall = SKSpriteNode(color: UIColor.red, size: bottomWallSize)
        bottomWall.position.y = -UIScreen.main.bounds.height/2 - bottomWallSize.height/2 - wallOffset
        bottomWall.physicsBody = createWallPhysics(categoryBitMask: BottomWallBitMask, wallSize: bottomWallSize)
        addChild(bottomWall)

        // Layout top wall
        let topWallSize = CGSize(width: UIScreen.main.bounds.width, height: HorizontalWallHeight)
        let topWall = SKSpriteNode(color: UIColor.red, size: topWallSize)
        topWall.position.y = UIScreen.main.bounds.height/2 + topWallSize.height/2 + wallOffset
        topWall.physicsBody = createWallPhysics(categoryBitMask: TopWallBitMask, wallSize: topWallSize)
        addChild(topWall)

        // Layout right wall
        let rightWallSize = CGSize(width: VerticallWallWidth, height: UIScreen.main.bounds.height)
        let rightWall = SKSpriteNode(color: UIColor.blue, size: rightWallSize)
        rightWall.position.x = UIScreen.main.bounds.width/2 + rightWallSize.width/2 + wallOffset
        rightWall.physicsBody = createWallPhysics(categoryBitMask: RightWallBitMask, wallSize: rightWallSize)
        addChild(rightWall)

        // Layout left wall
        let leftWallSize = CGSize(width: VerticallWallWidth, height: UIScreen.main.bounds.height)
        let leftWall = SKSpriteNode(color: UIColor.blue, size: leftWallSize)
        leftWall.position.x = -UIScreen.main.bounds.width/2 - leftWallSize.width/2 - wallOffset
        leftWall.physicsBody = createWallPhysics(categoryBitMask: LeftWallBitMask, wallSize: leftWallSize)
        addChild(leftWall)
    }

    fileprivate func createWallPhysics(categoryBitMask: UInt32, wallSize: CGSize) -> SKPhysicsBody {
        // Create new physics body for wall
        let physicsBody = SKPhysicsBody(edgeLoopFrom: CGRect(x: -wallSize.width/2, y: -wallSize.height/2, width: wallSize.width, height: wallSize.height))
        physicsBody.isDynamic = true
        physicsBody.friction = 0
        physicsBody.restitution = 1.0
        physicsBody.linearDamping = 0
        physicsBody.angularDamping = 0.0
        physicsBody.categoryBitMask = categoryBitMask

        // Return body
        return physicsBody
    }
}


问:
Center the login form in the middle of the screen with bootstrap
I am trying to get my login form in the middle of the screen and the company logo on the right above.

In the picture this is what I want to make in bootstrap.

This is my HTML code:

```<code><div class="row">
    <div class="col-sm-3">
        .col-sm-3
    </div>

    <div class="col-sm-6">
        <div class="panel panel-info">
            <div class="panel-heading">
                <div class="panel-title">
                    Sign In
                </div>
                <div class="forgot-password">
                    <a href="#">Forgot password?</a>
                </div>
            </div>
            <div class="panel-body body-panel-styling">
                <form class="form-horizontal" id="loginform"></form>
            </div>
        </div>
    </div>

    <div class="col-sm-3">
        <img alt="Cerrix" class="img-responsive" src="~/Images/Cerrix-Logo.gif">
    </div>
</div>
</code>```

I already try this website but no luck

https://css-tricks.com/centering-css-complete-guide/

How can I center the login form in the middle of the screen and the company logo on the right above side of the screen?

Kind regards

UPDATE: jsfiddle

https://jsfiddle.net/fok6f2fc/

答:
Would something like this match your needs? Login box centered horizontally and vertically with 100% height columns. Best viewed here on CodePen.

html,body,.container {
  height: 100%;
}

#login-box {
  display: table;
  height: 100%;
}

.container {
  display: table;
  width: 100%;
  padding: 0;
  box-sizing: border-box;
}

.row {
  height: 100%;
  display: table-row;
}

.row .no-float {
  display: table-cell;
  float: none;
  vertical-align: top;
}

.new {
  display: table-cell;
  vertical-align: middle;
  float: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row">
    <div class="col-md-3 no-float">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dui augue, sollicitudin et tortor sodales, mollis luctus massa. Praesent non tincidunt neque. Pellentesque facilisis maximus risus, ut porta risus vulputate in. Aliquam erat volutpat. Ut neque mi, tincidunt accumsan diam sed, vehicula vulputate ante. Morbi congue purus nulla, a sodales mi pellentesque id. Vestibulum tempor diam cursus nunc convallis, ac vehicula ipsum faucibus. Aenean malesuada pretium est, id laoreet diam aliquam porta. Aenean elementum pharetra leo id consequat. Pellentesque nec odio leo. Donec luctus nibh orci, sit amet malesuada risus suscipit eget. Maecenas aliquet odio nec vulputate vestibulum. Fusce tincidunt enim a mauris ornare, id iaculis nunc luctus. Donec placerat ex in lorem semper faucibus. Praesent ut tempus erat.</p>
    </div>
    <div class="col-md-12" id="login-box">
      <div class="new"><div class="panel panel-info">

        <div class="panel-heading">
          <div class="panel-title">Sign In</div>
          <div class="forgot-password">Forgot password?</div>
        </div>

        <div class="panel-body body-panel-styling">
          <form id="loginform" class="form-horizontal" role="form">

            <div class="input-group styling-field">
              <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
              <input id="login-username" type="text" class="form-control" name="username" value="" placeholder="username">
            </div>

            <div class="input-group styling-field">
              <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
              <input id="login-password" type="password" class="form-control" name="password" placeholder="password">
            </div>

            <div class="form-group styling-button">
              <div class="col-sm-12 controls">
                Login
              </div>
            </div>

          </form>
        </div>
        </div></div>
    </div>
    <div class="col-md-3 no-float">
      <div class="row">
         <div class="col-md-12">
            <img src="http://placehold.it/300x100" class="img-responsive">
        </div>
      </div>

      <div class="row">
         <div class="col-md-12">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dui augue, sollicitudin et tortor sodales, mollis luctus massa. Praesent non tincidunt neque. Pellentesque facilisis maximus risus, ut porta risus vulputate in. Aliquam erat volutpat. Ut neque mi, tincidunt accumsan diam sed, vehicula vulputate ante. Morbi congue purus nulla, a sodales mi pellentesque id. Vestibulum tempor diam cursus nunc convallis, ac vehicula ipsum faucibus. Aenean malesuada pretium est, id laoreet diam aliquam porta. Aenean elementum pharetra leo id consequat. Pellentesque nec odio leo. Donec luctus nibh orci, sit amet malesuada risus suscipit eget. Maecenas aliquet odio nec vulputate vestibulum. Fusce tincidunt enim a mauris ornare, id iaculis nunc luctus. Donec placerat ex in lorem semper faucibus. Praesent ut tempus erat.
        </div>
      </div>
    </div>
  </div>
</div></code>```

Body:
I am trying to get my login form in the middle of the screen and the company logo on the right above.

In the picture this is what I want to make in bootstrap.

This is my HTML code:

        .col-sm-3

                    Sign In

                    Forgot password?

                <form class="form-horizontal" id="loginform"></form>

I already try this website but no luck

https://css-tricks.com/centering-css-complete-guide/

How can I center the login form in the middle of the screen and the company logo on the right above side of the screen?

Kind regards

UPDATE: jsfiddle

https://jsfiddle.net/fok6f2fc/

Body:
Would something like this match your needs? Login box centered horizontally and vertically with 100% height columns. Best viewed here on CodePen.

html,body,.container {
  height: 100%;
}

#login-box {
  display: table;
  height: 100%;
}

.container {
  display: table;
  width: 100%;
  padding: 0;
  box-sizing: border-box;
}

.row {
  height: 100%;
  display: table-row;
}

.row .no-float {
  display: table-cell;
  float: none;
  vertical-align: top;
}

.new {
  display: table-cell;
  vertical-align: middle;
  float: none;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row">
    <div class="col-md-3 no-float">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dui augue, sollicitudin et tortor sodales, mollis luctus massa. Praesent non tincidunt neque. Pellentesque facilisis maximus risus, ut porta risus vulputate in. Aliquam erat volutpat. Ut neque mi, tincidunt accumsan diam sed, vehicula vulputate ante. Morbi congue purus nulla, a sodales mi pellentesque id. Vestibulum tempor diam cursus nunc convallis, ac vehicula ipsum faucibus. Aenean malesuada pretium est, id laoreet diam aliquam porta. Aenean elementum pharetra leo id consequat. Pellentesque nec odio leo. Donec luctus nibh orci, sit amet malesuada risus suscipit eget. Maecenas aliquet odio nec vulputate vestibulum. Fusce tincidunt enim a mauris ornare, id iaculis nunc luctus. Donec placerat ex in lorem semper faucibus. Praesent ut tempus erat.</p>
    </div>
    <div class="col-md-12" id="login-box">
      <div class="new"><div class="panel panel-info">

        <div class="panel-heading">
          <div class="panel-title">Sign In</div>
          <div class="forgot-password"><a href="#">Forgot password?</a></div>
        </div>

        <div class="panel-body body-panel-styling">
          <form id="loginform" class="form-horizontal" role="form">

            <div class="input-group styling-field">
              <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
              <input id="login-username" type="text" class="form-control" name="username" value="" placeholder="username">
            </div>

            <div class="input-group styling-field">
              <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
              <input id="login-password" type="password" class="form-control" name="password" placeholder="password">
            </div>

            <div class="form-group styling-button">
              <div class="col-sm-12 controls">
                <a href="#" class="btn btn-info">Login  </a>
              </div>
            </div>

          </form>
        </div>
        </div></div>
    </div>
    <div class="col-md-3 no-float">
      <div class="row">
         <div class="col-md-12">
            <img src="http://placehold.it/300x100" class="img-responsive">
        </div>
      </div>

      <div class="row">
         <div class="col-md-12">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus dui augue, sollicitudin et tortor sodales, mollis luctus massa. Praesent non tincidunt neque. Pellentesque facilisis maximus risus, ut porta risus vulputate in. Aliquam erat volutpat. Ut neque mi, tincidunt accumsan diam sed, vehicula vulputate ante. Morbi congue purus nulla, a sodales mi pellentesque id. Vestibulum tempor diam cursus nunc convallis, ac vehicula ipsum faucibus. Aenean malesuada pretium est, id laoreet diam aliquam porta. Aenean elementum pharetra leo id consequat. Pellentesque nec odio leo. Donec luctus nibh orci, sit amet malesuada risus suscipit eget. Maecenas aliquet odio nec vulputate vestibulum. Fusce tincidunt enim a mauris ornare, id iaculis nunc luctus. Donec placerat ex in lorem semper faucibus. Praesent ut tempus erat.
        </div>
      </div>
    </div>
  </div>
</div>


问:
how to listen to custom events in components which are loaded using routing in Angular 4?
In app.component.html

```<code><li routerLinkActive="active current">
       <a  [routerLink]="['/stats']">
                    Cluster stats
       </a>
   </li>
</code>```

Since we are routing to DisplayAllStatsComponent , how to listen for 'viewdetails' event triggered in above li or a tag?
In app.module.ts

```<code>{
    path:'/stats',
    component : DisplayAllStatsComponent
 }
</code>```

In DisplayAllStatsComponent
     when the component is clicked it triggers an event

@Output('viewdetails') viewdetails = new EventEmitter();

// here below function is called .

```<code>  callViewDetails(name,alias){
    let ev = {
      name:name,alias:alias
    };
    this.viewdetails.emit(ev); // here value is being emitted.
  }
</code>```

now i need the emitted value in app.component.html

答:
The EventEmitter can be used to communicate between parent and child components. In your case, it won't work.
However, there is a way to "broadcast" an event using a Subject.

You can create a Broadcaster class, which would be something like this:

```<code>import { Subject } from "rxjs/Subject";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/filter";
import "rxjs/add/operator/map";

export class Broadcaster {
  private _event: Subject<BroadcastEvent>;

  constructor() {
    this._event = new Subject<BroadcastEvent>();
  }

  broadcast$(key: any, data?: any) {
    this._event.next({key, data});
  }

  on$<T>(key: any): Observable<T> {
    return this._event.asObservable()
      .filter(event => event.key === key)
      .map(event => <T>event.data);
  }
}

export interface BroadcastEvent {
  key: any;
  data?: any;
}
</code>```

Then, you can broadcast the event like this:

```<code>callViewDetails(name,alias){
    let ev = {
      name:name,alias:alias
    };
    this.broadcaster.broadcast$("viewDetailsEvent", ev); //Broadcast
  }
</code>```

And subscribe to the event in your app component:

```<code>this.broadcaster.on$("viewDetailsEvent").subscribe(viewDetails => {
  //do whatever you want with the viewDetails here
})
</code>```

Body:
In app.component.html

                    Cluster stats

Since we are routing to DisplayAllStatsComponent , how to listen for 'viewdetails' event triggered in above li or a tag?
In app.module.ts

{
    path:'/stats',
    component : DisplayAllStatsComponent
 }

In DisplayAllStatsComponent
     when the component is clicked it triggers an event

@Output('viewdetails') viewdetails = new EventEmitter();

// here below function is called .

  callViewDetails(name,alias){
    let ev = {
      name:name,alias:alias
    };
    this.viewdetails.emit(ev); // here value is being emitted.
  }

now i need the emitted value in app.component.html

Body:
The EventEmitter can be used to communicate between parent and child components. In your case, it won't work.
However, there is a way to "broadcast" an event using a Subject.

You can create a Broadcaster class, which would be something like this:

import { Subject } from "rxjs/Subject";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/filter";
import "rxjs/add/operator/map";

export class Broadcaster {
  private _event: Subject<BroadcastEvent>;

  constructor() {
    this._event = new Subject<BroadcastEvent>();
  }

  broadcast$(key: any, data?: any) {
    this._event.next({key, data});
  }

  on$<T>(key: any): Observable<T> {
    return this._event.asObservable()
      .filter(event => event.key === key)
      .map(event => <T>event.data);
  }
}

export interface BroadcastEvent {
  key: any;
  data?: any;
}

Then, you can broadcast the event like this:

callViewDetails(name,alias){
    let ev = {
      name:name,alias:alias
    };
    this.broadcaster.broadcast$("viewDetailsEvent", ev); //Broadcast
  }

And subscribe to the event in your app component:

this.broadcaster.on$("viewDetailsEvent").subscribe(viewDetails => {
  //do whatever you want with the viewDetails here
})


问:
CKAN docker db init: ERROR: relation "user" does not exist at character 435
I'm using latest ckan docker image built from source docker compose with my own .env file

```<code>docker-compose build
</code>```

After doing a couple of changes in the image to resolve minor bugs (latest ckan needs to install dev-requirements.txt, and entrypoint need to wait for db to be ready), after running docker-compose up. I'm getting four similar errors at db container, after which ckan fails to start.

The errors at db container are like this:

ERROR: relation "user" does not exist at character 435
STATEMENT: SELECT "user".password AS user_password, "user".id AS user_id, "user".name AS user_name, "user".fullname AS user_fullname, "user".email AS user_email, "user".apikey AS user_apikey, "user".created AS user_creat
ed, "user".reset_key AS user_reset_key, "user".about AS user_about, "user".activity_streams_email_notifications AS user_activity_streams_email_notifications, "user".sysadmin AS user_sysadmin, "user".state AS user_state
FROM "user"
WHERE "user".name = 'default' OR "user".id = 'default' ORDER BY "user".name
LIMIT 1

Pertinent log entries can be found at: http://www.wepaste.com/ckan%20image%20log/

Any hint on what's going on?

答:
Finally I went to latest "stable" version 2.7.2, and resolve again a couple of bugs to get it working.

The script that modifies the original dockerfile and build a correct image can be found here.

Body:
I'm using latest ckan docker image built from source docker compose with my own .env file

docker-compose build

After doing a couple of changes in the image to resolve minor bugs (latest ckan needs to install dev-requirements.txt, and entrypoint need to wait for db to be ready), after running docker-compose up. I'm getting four similar errors at db container, after which ckan fails to start.

The errors at db container are like this:

ERROR: relation "user" does not exist at character 435
STATEMENT: SELECT "user".password AS user_password, "user".id AS user_id, "user".name AS user_name, "user".fullname AS user_fullname, "user".email AS user_email, "user".apikey AS user_apikey, "user".created AS user_creat
ed, "user".reset_key AS user_reset_key, "user".about AS user_about, "user".activity_streams_email_notifications AS user_activity_streams_email_notifications, "user".sysadmin AS user_sysadmin, "user".state AS user_state
FROM "user"
WHERE "user".name = 'default' OR "user".id = 'default' ORDER BY "user".name
LIMIT 1

Pertinent log entries can be found at: http://www.wepaste.com/ckan%20image%20log/

Any hint on what's going on?


问:
How to convert this String to Timestamp
i have a column with the Data like this "08.06.2017/10:20:46". Data Type is string. i want to convert it into timestamp.
i tried CAST("08.06.2017/10:20:46" AS TIMESTAMP) but it doesn't work
Can you please help me to convert it??
Thanks</p>

答:
For Oracle SQL,

use to_date function as below,

SELECT TO_DATE('08.06.2017/10:20:46','dd.mm.yyyy/hh:mi:ss') FROM DUAL;

This conveys that the string is in this(dd.mm.yyyy/hh:mi:ss) form of date and convert to date column...

Title: How to convert this String to Timestamp


问:
what does `.rodata.str1.8` section mean in elf file
I know the .rodata section stores constant data in an ELF file. However, when I dump an ELF of a kernel module, I notice that there are two extra sections named rodata.str1.8 and rodata.str1.1. It seems that these two sections store constant variables and strings as well. But what exactly are the differences between these three rodata?

答:
It looks like .rodata.str1.1 has strings without alignment requirements, while .rodata.str1.8 must be 8-byte aligned. If you look at an ELF file with readelf this is visible:

```<code>Section Headers:
  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
  [ 0]                   NULL            00000000 000000 000000 00      0   0  0
  [ 1] .text             PROGBITS        00000000 000034 000050 00  AX  0   0  4
  [ 2] .rela.text        RELA            00000000 000184 000030 0c   I  8   1  4
  [ 3] .data             PROGBITS        00000000 000084 000000 00  WA  0   0  1
  [ 4] .bss              NOBITS          00000000 000084 000000 00  WA  0   0  1
  [ 5] .rodata.str1.8    PROGBITS        00000000 000088 000010 01 AMS  0   0  8   <---
  [ 6] .comment          PROGBITS        00000000 000098 000019 01  MS  0   0  1
  [ 7] .shstrtab         STRTAB          00000000 0001b4 000049 00      0   0  1
  [ 8] .symtab           SYMTAB          00000000 0000b4 0000a0 10      9   7  4
  [ 9] .strtab           STRTAB          00000000 000154 00002f 00      0   0  1
Key to Flags:
  W (write), A (alloc), X (execute), M (merge), S (strings)
  I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)
  O (extra OS processing required) o (OS specific), p (processor specific)
</code>```

Body:
It looks like .rodata.str1.1 has strings without alignment requirements, while .rodata.str1.8 must be 8-byte aligned. If you look at an ELF file with readelf this is visible:

Section Headers:
  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
  [ 0]                   NULL            00000000 000000 000000 00      0   0  0
  [ 1] .text             PROGBITS        00000000 000034 000050 00  AX  0   0  4
  [ 2] .rela.text        RELA            00000000 000184 000030 0c   I  8   1  4
  [ 3] .data             PROGBITS        00000000 000084 000000 00  WA  0   0  1
  [ 4] .bss              NOBITS          00000000 000084 000000 00  WA  0   0  1
  [ 5] .rodata.str1.8    PROGBITS        00000000 000088 000010 01 AMS  0   0  8   <---
  [ 6] .comment          PROGBITS        00000000 000098 000019 01  MS  0   0  1
  [ 7] .shstrtab         STRTAB          00000000 0001b4 000049 00      0   0  1
  [ 8] .symtab           SYMTAB          00000000 0000b4 0000a0 10      9   7  4
  [ 9] .strtab           STRTAB          00000000 000154 00002f 00      0   0  1
Key to Flags:
  W (write), A (alloc), X (execute), M (merge), S (strings)
  I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)
  O (extra OS processing required) o (OS specific), p (processor specific)


问:
WinSCP transferring PDF from unix to window
I am working on a project using Java that embedding PDF with text file. So far, I developed and tested on development tool Eclipse, the program run perfectly smooth and the result were as expected.

I try to run the program on unix, program was run, directories and files created as expected. I verified the result by transferring the PDF from unix to window by using winSCP, I try “Binary” and “Text” from Transfer Setting selection, it came out two different problems.

First of all, I clicked “Text” from the Transfer Setting selection, winSCP finished transfer. I opened the PDF and an error occurred, “Insufficient data for image”. I checked the embedded text file, it presented perfectly lines by lines.

Then, I chose “Binary” and winSCP transferred to window completely. I opened the PDF, it showed perfectly.  However, the sentences in the embedded text file massed together in one line.

Did I set something wrong or using wrong transfer method? Or something I looked over?

Thankyou in dvance

答:
Instead of using winscp you could go for alternatives like ftp, sftp, setting a nfs share between your windows and unix machine or putting your pdf files inside a tar/zip/tar.gz file to transfer it to windows (in binary mode) to avoid any transfer problem.

Then, I chose “Binary” and winSCP transferred to window completely. I opened the PDF, it showed perfectly. However, the sentences in the
  embedded text file massed together in one line.

Regarding, this point do you now that the unix EOL symbols are not the same than in windows \n vs \r\n? This might explain why you have your text, massed together. You might have to change your java code to produce windows style carriage return,  or use unix2dos/tr tools.

Last but not least, you could also try to open your pdf directly on Linux to check the result.


问:
how to use one preference activity for multiple instances of the widgets?
I am working on an android home screen app widget.

i am trying to add preferences to the widget. i can put multiple widgets. but i want to configure it with preferences using shared preference created dynamically.

how can i load the preference from the resource file which fetches the value from the sharedpreference and also updates it?

any suggestion?

答:
maybe try to write your own preference system maybe on somewhere on filesys.
just suggesting</p>


问:
Error during installing of module in odoo
I am currently encountering an error in Odoo. I am using Odoo v.10 and I am looking for loan management module for FREE and I found a module in lower version which is 8 and when I'm installing the module, it gives me an error. Why is this?

but I checked it and the model name is perfectly declared on its dunder init and the views are declared on its manifest or dunder openerp.

答:
you have to upgrade your addon from old api to new api. please read this guidelines and it will help you.

odoo new api guidlines


问:
Modifying ConcurrentBag objects from another thread
I have a thread #1 which is looping continuously with foreach through a ConcurrentBag list and modifying the items, but at some time another thread #2 needs to modify an item from the list. Is it safe if I take out all the objects from thread #2 (while the other one is looping with foreach) and modify the object then add all items back in thread #2 ? if it's not then is there a workaround ?

```<code>ConcurrentBag<MyObject> list;
</code>```

thread 1

```<code>while (1) // continuous loop
{
  foreach(MyObject obj in list)
  {
     obj.RunMethod();
     Thread.Sleep(500);
  }
  Thread.Sleep(1000);
}
</code>```

thread 2

(at some point a callback is called on thread #2 and need to modify an object)

```<code>List<MyObject> temp;
while (list.TryTake(out obj)
{
   MyObject obj2=obj.Clone(); // make a copy of the object
   if (obj2.Id==4) obj2.variable=10;
   temp.Add(obj2);
}
// Add objects back to concurrentbag
foreach(MyObject obj in temp) list.Add(obj);
</code>```

答:
No, this isn't safe because the thread doing foreach may have retrieved a reference to an object and be working with that object while the other thread removes it from the bag, modifies it and puts it back.

This could result in the object's state changing while the foreach thread is using it. You can avoid this by creating a copy of the object to be mutated, and then change the copy and put the copy back into the bag.

Have you considered making your object immutable? Doing so will really simplify things, and actually makes it impossible for two threads to mutate it at the same time.

NOTE: Copying a reference to an object does NOT copy the contents of the object, so when you do list.TakeOut(out obj) you are receiving a reference to an existing object, not creating a new copy of it.

[EDIT] So you edited your question to use obj.Clone(). If that does a proper deep clone of your object, then the code should be OK, but that's only if you're careful to copy the object everywhere it is changed. If you make the class immutable, then you GUARANTEE this behaviour,so that's the best solution if you can use it.

Body:
I have a thread #1 which is looping continuously with foreach through a ConcurrentBag list and modifying the items, but at some time another thread #2 needs to modify an item from the list. Is it safe if I take out all the objects from thread #2 (while the other one is looping with foreach) and modify the object then add all items back in thread #2 ? if it's not then is there a workaround ?

ConcurrentBag<MyObject> list;

thread 1

while (1) // continuous loop
{
  foreach(MyObject obj in list)
  {
     obj.RunMethod();
     Thread.Sleep(500);
  }
  Thread.Sleep(1000);
}

thread 2

(at some point a callback is called on thread #2 and need to modify an object)

List<MyObject> temp;
while (list.TryTake(out obj)
{
   MyObject obj2=obj.Clone(); // make a copy of the object
   if (obj2.Id==4) obj2.variable=10;
   temp.Add(obj2);
}
// Add objects back to concurrentbag
foreach(MyObject obj in temp) list.Add(obj);


问:
Why we use null in sqlite methods?
Why we use null in sqlite database methods like:

```<code>db.insert("table1", null, cv);
</code>```

Is it necessary use it in methods?
Without null we have error.

答:
Let's suppose you have a table named employee where all columns either allow NULL values or have defaults.

In some SQL implementations, this would be valid SQL:

INSERT INTO employee;

That's not valid in SQLite. You have to have at least one column specified:

INSERT INTO employee (somecol) VALUES (NULL);

Android and SQLite need some column that is safe to assign NULL to. If you have several such columns to choose from, pick one via the selection mechanism of your choice: roll of the dice, Magic 8-Ball(TM), coin flip, cubicle mate flip, etc.

Title: Why we use null in sqlite methods?

Body:
Why we use null in sqlite database methods like:

db.insert("table1", null, cv);

Is it necessary use it in methods?
Without null we have error.


问:
NodeJS - Error installing with NPM
```<code>Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

C:\Windows\system32>npm install caress-server
npm http GET https://registry.npmjs.org/caress-server
npm http 304 https://registry.npmjs.org/caress-server
npm http GET https://registry.npmjs.org/jspack/0.0.1
npm http GET https://registry.npmjs.org/buffertools
npm http 304 https://registry.npmjs.org/jspack/0.0.1
npm http 304 https://registry.npmjs.org/buffertools

> buffertools@2.0.1 install C:\Windows\system32\node_modules\caress-server\node_
modules\buffertools
> node-gyp rebuild

C:\Windows\system32\node_modules\caress-server\node_modules\buffertools>node "G:
\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-
gyp.js" rebuild
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT
HON env variable.
gyp ERR! stack     at failNoPython (G:\nodejs\node_modules\npm\node_modules\node
-gyp\lib\configure.js:101:14)
gyp ERR! stack     at G:\nodejs\node_modules\npm\node_modules\node-gyp\lib\confi
gure.js:64:11
gyp ERR! stack     at Object.oncomplete (fs.js:107:15)
gyp ERR! System Windows_NT 6.2.9200
gyp ERR! command "node" "G:\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\
bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Windows\system32\node_modules\caress-server\node_modules\buffert
ools
gyp ERR! node -v v0.10.25
gyp ERR! node-gyp -v v0.12.2
gyp ERR! not ok
npm ERR! buffertools@2.0.1 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the buffertools@2.0.1 install script.
npm ERR! This is most likely a problem with the buffertools package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls buffertools
npm ERR! There is likely additional logging output above.

npm ERR! System Windows_NT 6.2.9200
npm ERR! command "G:\\nodejs\\\\node.exe" "G:\\nodejs\\node_modules\\npm\\bin\\n
pm-cli.js" "install" "caress-server"
npm ERR! cwd C:\Windows\system32
npm ERR! node -v v0.10.25
npm ERR! npm -v 1.3.24
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     C:\Windows\system32\npm-debug.log
npm ERR! not ok code 0

C:\Windows\system32>
</code>```

I am installing a certain NodeJS script - Caress. But i am not unable to. I am using Windows 8.1, can anyone tell me what is the problem i am facing, and why is this installation not working. There seems to be a problem with the buffertools dependency, thats far as i can think. Dont know how maybe fix this?

If i download the build from github and place it in node-modules, nothing seems to work. when i try to start, using npm start, or during implementation either.

```<code>G:\nodejs\node_modules\caress-server>npm install

G:\nodejs\node_modules\caress-server>npm start

> caress-server@0.1.1 start G:\nodejs\node_modules\caress-server
> node examples/server.js

   info  - socket.io started

module.js:340
    throw err;
          ^
Error: Cannot find module './build/Release/buffertools.node'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (G:\nodejs\node_modules\caress-server\node_modules\buf
fertools\buffertools.js:16:19)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)

npm ERR! caress-server@0.1.1 start: `node examples/server.js`
npm ERR! Exit status 8
npm ERR!
npm ERR! Failed at the caress-server@0.1.1 start script.
npm ERR! This is most likely a problem with the caress-server package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node examples/server.js
npm ERR! You can get their info via:
npm ERR!     npm owner ls caress-server
npm ERR! There is likely additional logging output above.
npm ERR! System Windows_NT 6.2.9200
npm ERR! command "G:\\nodejs\\\\node.exe" "G:\\nodejs\\node_modules\\npm\\bin\\n
pm-cli.js" "start"
npm ERR! cwd G:\nodejs\node_modules\caress-server
npm ERR! node -v v0.10.25
npm ERR! npm -v 1.3.24
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     G:\nodejs\node_modules\caress-server\npm-debug.log
npm ERR! not ok code 0

G:\nodejs\node_modules\caress-server>
</code>```

答:
For windows

Check python path in system variable.
npm plugins need node-gyp to be installed.

open command prompt with admin rights, and run following command.

npm install --global --production windows-build-tools

npm install --global node-gyp

Title: NodeJS - Error installing with NPM

Body:
Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

C:\Windows\system32>npm install caress-server
npm http GET https://registry.npmjs.org/caress-server
npm http 304 https://registry.npmjs.org/caress-server
npm http GET https://registry.npmjs.org/jspack/0.0.1
npm http GET https://registry.npmjs.org/buffertools
npm http 304 https://registry.npmjs.org/jspack/0.0.1
npm http 304 https://registry.npmjs.org/buffertools

> buffertools@2.0.1 install C:\Windows\system32\node_modules\caress-server\node_
modules\buffertools
> node-gyp rebuild

C:\Windows\system32\node_modules\caress-server\node_modules\buffertools>node "G:
\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-
gyp.js" rebuild
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT
HON env variable.
gyp ERR! stack     at failNoPython (G:\nodejs\node_modules\npm\node_modules\node
-gyp\lib\configure.js:101:14)
gyp ERR! stack     at G:\nodejs\node_modules\npm\node_modules\node-gyp\lib\confi
gure.js:64:11
gyp ERR! stack     at Object.oncomplete (fs.js:107:15)
gyp ERR! System Windows_NT 6.2.9200
gyp ERR! command "node" "G:\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\
bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Windows\system32\node_modules\caress-server\node_modules\buffert
ools
gyp ERR! node -v v0.10.25
gyp ERR! node-gyp -v v0.12.2
gyp ERR! not ok
npm ERR! buffertools@2.0.1 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the buffertools@2.0.1 install script.
npm ERR! This is most likely a problem with the buffertools package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls buffertools
npm ERR! There is likely additional logging output above.

npm ERR! System Windows_NT 6.2.9200
npm ERR! command "G:\\nodejs\\\\node.exe" "G:\\nodejs\\node_modules\\npm\\bin\\n
pm-cli.js" "install" "caress-server"
npm ERR! cwd C:\Windows\system32
npm ERR! node -v v0.10.25
npm ERR! npm -v 1.3.24
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     C:\Windows\system32\npm-debug.log
npm ERR! not ok code 0

C:\Windows\system32>

I am installing a certain NodeJS script - Caress. But i am not unable to. I am using Windows 8.1, can anyone tell me what is the problem i am facing, and why is this installation not working. There seems to be a problem with the buffertools dependency, thats far as i can think. Dont know how maybe fix this?

If i download the build from github and place it in node-modules, nothing seems to work. when i try to start, using npm start, or during implementation either.

G:\nodejs\node_modules\caress-server>npm install

G:\nodejs\node_modules\caress-server>npm start

> caress-server@0.1.1 start G:\nodejs\node_modules\caress-server
> node examples/server.js

   info  - socket.io started

module.js:340
    throw err;
          ^
Error: Cannot find module './build/Release/buffertools.node'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (G:\nodejs\node_modules\caress-server\node_modules\buf
fertools\buffertools.js:16:19)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)

npm ERR! caress-server@0.1.1 start: `node examples/server.js`
npm ERR! Exit status 8
npm ERR!
npm ERR! Failed at the caress-server@0.1.1 start script.
npm ERR! This is most likely a problem with the caress-server package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node examples/server.js
npm ERR! You can get their info via:
npm ERR!     npm owner ls caress-server
npm ERR! There is likely additional logging output above.
npm ERR! System Windows_NT 6.2.9200
npm ERR! command "G:\\nodejs\\\\node.exe" "G:\\nodejs\\node_modules\\npm\\bin\\n
pm-cli.js" "start"
npm ERR! cwd G:\nodejs\node_modules\caress-server
npm ERR! node -v v0.10.25
npm ERR! npm -v 1.3.24
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     G:\nodejs\node_modules\caress-server\npm-debug.log
npm ERR! not ok code 0

G:\nodejs\node_modules\caress-server>


问:
Detect a Price In Brackets in a String (PHP)
I'm looking to analyse strings in PHP. They appear as such:

Premium Upgrade (€10.00)

I want to detect when a string contains '(€10.00)', however the price will change. Hence I'm guessing a RegEx for 'Bracket, Float, Bracket' The end result is I want to remove the price from the string, however, its possible something else may appear in the brackets e.g.

Premium Upgrade (Per Person)

And hence I can't just explode or substring on the first opening brackets. However, there could be two, or more, brackets e.g.

Premium Upgrade (Per Person) (€10.00)

Hence in this instance, I would need to output:

Premium Upgrade (Per Person)

Thus my high level flow would be:

Check string, does it contact brackets and float?

Yes, remove the brackets and float, leaving other brackets in place, proceed.

No brackets and float? Leave as is, proceed.

My pysedo code is:

```<code>//Get my string
$str = $meta->display_key;

//I need a RegEx here to detect my bracket and float e.g. (€X.YY)
if (strpos($str, '(') !== false) {
    //Need to remove brackets and float here, but leave all other brackets in place.
    $formatted_string  = substr($str, 0, strrpos($str, '('));
}

//Do nothing, the string doesn't match my criteria
else $display_key_formatted = $str;
</code>```

答: you're looking for a regex like: <code>!\((.\d+\.\d+\))!</code> that should match anything with a currency and a price within brackets. </p>

Body:
I'm looking to analyse strings in PHP. They appear as such:

Premium Upgrade (€10.00)

I want to detect when a string contains '(€10.00)', however the price will change. Hence I'm guessing a RegEx for 'Bracket, Float, Bracket' The end result is I want to remove the price from the string, however, its possible something else may appear in the brackets e.g.

Premium Upgrade (Per Person)

And hence I can't just explode or substring on the first opening brackets. However, there could be two, or more, brackets e.g.

Premium Upgrade (Per Person) (€10.00)

Hence in this instance, I would need to output:

Premium Upgrade (Per Person)

Thus my high level flow would be:

Check string, does it contact brackets and float?

Yes, remove the brackets and float, leaving other brackets in place, proceed.

No brackets and float? Leave as is, proceed.

My pysedo code is:

//Get my string
$str = $meta->display_key;

//I need a RegEx here to detect my bracket and float e.g. (€X.YY)
if (strpos($str, '(') !== false) {
    //Need to remove brackets and float here, but leave all other brackets in place.
    $formatted_string  = substr($str, 0, strrpos($str, '('));
}

//Do nothing, the string doesn't match my criteria
else $display_key_formatted = $str;

Body: you're looking for a regex like: !\((.\d+\.\d+\))! that should match anything with a currency and a price within brackets.


问:
Why un-moduled JAR can access non exposes packaged of a moduled JAR?
I'm playing around with Java 9 in intelliJ:
I've created 4 modules (all modules depended on module1):

module1: exports packages pkg1 and exports pkg2 to module 2.

module2: requires module1 and able to access both packages

module3: requires module1 and able to access only pkg1

module4: does not have the module-info.class, able to access both packages of module1

I thought that automatic modules should require all exposed packaged but not the ones which are not exposed.

I don't understand what is the point of encapsulation, if it works only on explicitly moduled JARs.

What am I missing?

答:
Since the automatic modules in the module system doesn't have a module descriptor(module-info.class), there is hence no good way to determine which other modules an automatic module might depend upon.

After a module graph is resolved, therefore, an automatic module is made to read every other named module, whether automatic or explicit.

Hence in your case, module4 being an automatic module is able to read the explicit module module1.

The accessibility as defined in the module system(similarity drawn out by me) is illustrated as: If two types S and T are defined in different modules, and T is public, then code in S can access T if:

S’s module reads T’s module, (module4 reads module1) and

T’s module exports T’s package. (module1 exports pckg1 to all modules that requires module1 and pckg2 to only module2)

A type referenced across module boundaries that is not accessible in
  this way is unusable in the same way that a private method or field is
  unusable: Any attempt to use it will cause an error to be reported by
  the compiler, or an IllegalAccessError to be thrown by the Java
  virtual machine, or an IllegalAccessException to be thrown by the
  reflective run-time APIs.

Thus, even when a type is declared public,
  if its package is not exported in the declaration of its module then
  it will only be accessible to code in that module.


问:
How to validate a price (money amount) mySql decimal column in Yii?
I am using a mySql DECIMAL(12,4) column to hold price values (seeing how that's what Magento uses). I want to validate them in my ActiveRecord model using Yii's CValidator rules, but I'm not quite sure how to do it.

I assume I can do it with the CTypeValidator set to "float", but I wanted to see how other folks are doing this. I don't see an actual "currency" validator. Maybe I should just validate the length?

```<code>array('price', 'type', 'type'=>'float'),
</code>```

or

```<code>array('price', 'length', 'max'=>17), // 12 + 4 + . = 17?
</code>```

Suggestions and examples? Thanks!

答:
I myself used the:

```<code>array('price', 'type', 'type'=>'float'),
</code>```

rule... if needed, you can also use or combine the previous with the 'match' validator

```<code>array('price', 'match', 'pattern'=>'fancy regex magic here'),
</code>```

Body:
I am using a mySql DECIMAL(12,4) column to hold price values (seeing how that's what Magento uses). I want to validate them in my ActiveRecord model using Yii's CValidator rules, but I'm not quite sure how to do it.

I assume I can do it with the CTypeValidator set to "float", but I wanted to see how other folks are doing this. I don't see an actual "currency" validator. Maybe I should just validate the length?

array('price', 'type', 'type'=>'float'),

or

array('price', 'length', 'max'=>17), // 12 + 4 + . = 17?

Suggestions and examples? Thanks!

Body:
I myself used the:

array('price', 'type', 'type'=>'float'),

rule... if needed, you can also use or combine the previous with the 'match' validator

array('price', 'match', 'pattern'=>'fancy regex magic here'),