答:
Stack your data, and do another groupby:

```<code>df.groupby('participant_id').corr().stack().groupby(level = [1,2]).median()
</code>```

Edit: Actually, you don't need to stack if you don't want to:

```<code>df.groupby('participant_id').corr().groupby(level = [1]).median()
</code>```

works too.

Title: Applying function to Pandas with GroupBy along direction of the grouping variable

Body:
I have a cohort of N people and I computed a correlation matrix of some quantities (q1_score,...q5_score)

    df.groupby('participant_id').corr()
    Out[130]:
                                q1_score    q2_score   q3_score  q4_score   q5_score
    participant_id
    11.0           q1_score     1.000000   -0.748887  -0.546893  -0.213635  -0.231169
                   q2_score    -0.748887    1.000000   0.639649   0.324976   0.335596
                   q3_score    -0.546893    0.639649   1.000000   0.154539   0.151233
                   q4_score    -0.213635    0.324976   0.154539   1.000000   0.998752
                   q5_score    -0.231169    0.335596   0.151233   0.998752   1.000000
    14.0           q1_score     1.000000   -0.668781  -0.124614  -0.352075  -0.244251
                   q2_score    -0.668781    1.000000  -0.175432   0.360183   0.184585
                   q3_score    -0.124614   -0.175432   1.000000  -0.137993  -0.125115
                   q4_score    -0.352075    0.360183  -0.137993   1.000000   0.968564
                   q5_score    -0.244251    0.184585  -0.125115   0.968564   1.000000
    17.0           q1_score     1.000000   -0.799223  -0.814424  -0.790587  -0.777318
                   q2_score    -0.799223    1.000000   0.787238   0.658524   0.640786
                   q3_score    -0.814424    0.787238   1.000000   0.702570   0.701440
                   q4_score    -0.790587    0.658524   0.702570   1.000000   0.998996
                   q5_score    -0.777318    0.640786   0.701440   0.998996   1.000000
    18.0           q1_score     1.000000   -0.595545  -0.617691  -0.472409  -0.477523
                   q2_score    -0.595545    1.000000   0.386705   0.148761   0.115068
                   q3_score    -0.617691    0.386705   1.000000   0.806637   0.782345
                   q4_score    -0.472409    0.148761   0.806637   1.000000   0.982617
                   q5_score    -0.477523    0.115068   0.782345   0.982617   1.000000

I need to compute the median values of the correlations of all participants? What I mean: I need to take corr. between the item J and item K for all participants and find their median value.

I am sure it is a one line of code, but I'm struggling to realise (still learning pandas by examples).

Body:
Stack your data, and do another groupby:

df.groupby('participant_id').corr().stack().groupby(level = [1,2]).median()

Edit: Actually, you don't need to stack if you don't want to:

df.groupby('participant_id').corr().groupby(level = [1]).median()

works too.


来源: stackexchange

问:
Create a div in HTML when calling a function in Angular 2
So what's going is that I have a list of orders which I show in a view. When I click on the order id for a specific order in the list I want to have it expand with more detailed information about the order. I've created a order view which I want to load in the div that expands but I was thinking the smart way to do this is to have a function creating a div when the order id is clicked.
This is the template for the component:

```<code><div class ="order" *ngFor="let order of orders | paginate: {itemsPerPage: 20, currentPage: pageNumber, totalItems: totalNumberOfOrders}">
    <span class="orderOrderId">{{order.orderId}}</span>
</div>
</code>```

Basically I want (click)="loadOrderView(order.orderId)" and then the function should do:

```<code>loadOrderView(orderId): {
"Create a div and load it in my html under the specified order"
}
</code>```

I don't want to use bootstrap, this should be easy enough but I don't really know how to proceed. What is the best and easiest way to achieve what I want, which in the end is basically for the order to expand and more information be presented.

答:
You should let Angular deal with DOM manipulation.
So you should have a inner div with *ngIf and when the data comes from the server, you should set it to true and let angular render inner div.

For example:

```<code><div class ="order" *ngFor="let order of orders | paginate: {itemsPerPage: 20, currentPage: pageNumber, totalItems: totalNumberOfOrders}"
    (click)="loadOrderView(order)">
    <span class="orderOrderId">{{order.orderId}}</span>
    <div *ngIf="order.hasDetail">
        <order-detail [data]="order"></order-detail>
    </div>
</div>
</code>```

Inside your component:

```<code>loadOrderView(order) {
    // fetch data
  order.hasDetail = true;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So what's going is that I have a list of orders which I show in a view. When I click on the order id for a specific order in the list I want to have it expand with more detailed information about the order. I've created a order view which I want to load in the div that expands but I was thinking the smart way to do this is to have a function creating a div when the order id is clicked.
This is the template for the component:

    {{order.orderId}}

Basically I want (click)="loadOrderView(order.orderId)" and then the function should do:

loadOrderView(orderId): {
"Create a div and load it in my html under the specified order"
}

I don't want to use bootstrap, this should be easy enough but I don't really know how to proceed. What is the best and easiest way to achieve what I want, which in the end is basically for the order to expand and more information be presented.

Body:
You should let Angular deal with DOM manipulation.
So you should have a inner div with *ngIf and when the data comes from the server, you should set it to true and let angular render inner div.

For example:

<div class ="order" *ngFor="let order of orders | paginate: {itemsPerPage: 20, currentPage: pageNumber, totalItems: totalNumberOfOrders}"
    (click)="loadOrderView(order)">
    <span class="orderOrderId">{{order.orderId}}</span>
    <div *ngIf="order.hasDetail">
        <order-detail [data]="order"></order-detail>
    </div>
</div>

Inside your component:

loadOrderView(order) {
    // fetch data
  order.hasDetail = true;
}


问:
how to store all facebook emoji in mysql database
I am using Emoji character in my project for facebook post. Some emoji character are saved good but some characters are saved like (??) into mysql database. My database table Default collation is utf8mb4_unicode_ci .
Is there any way to save all emoji into database.

I am working in Cakephp3.
My database structure is :

```<code>'Datasources' => [
        'default' => [
            'className' => 'Cake\Database\Connection',
            'driver' => 'Cake\Database\Driver\Mysql',
            'persistent' => false,
            'host' => 'localhost',
            'username' => '******',
            'password' => '******',
            'database' => '******',
            'encoding' => 'utf8mb4',
            'timezone' => 'UTC',
            'flags' => [],
            'cacheMetadata' => true,
            'log' => false,
            'url' => env('DATABASE_URL', null),
        ],
</code>```

答:
I had a similar problem to this when dealing with unusual characters such as this. The issue wasnt with the database, it was with how i was connecting to the database. Since you have provided no code, I can't give any specific advice, but check your DB connection string and make sure its using the mb4 version of utf8. Otherwise the response will not contain the characters.

If you are using PDO, then your db string will look like this.

```<code>$db = 'mysql:host=example.com;dbname=testdb;port=1234;charset=utf8mb4';
</code>```

Body:
I am using Emoji character in my project for facebook post. Some emoji character are saved good but some characters are saved like (??) into mysql database. My database table Default collation is utf8mb4_unicode_ci .
Is there any way to save all emoji into database.

I am working in Cakephp3.
My database structure is :

'Datasources' => [
        'default' => [
            'className' => 'Cake\Database\Connection',
            'driver' => 'Cake\Database\Driver\Mysql',
            'persistent' => false,
            'host' => 'localhost',
            'username' => '******',
            'password' => '******',
            'database' => '******',
            'encoding' => 'utf8mb4',
            'timezone' => 'UTC',
            'flags' => [],
            'cacheMetadata' => true,
            'log' => false,
            'url' => env('DATABASE_URL', null),
        ],

Body:
I had a similar problem to this when dealing with unusual characters such as this. The issue wasnt with the database, it was with how i was connecting to the database. Since you have provided no code, I can't give any specific advice, but check your DB connection string and make sure its using the mb4 version of utf8. Otherwise the response will not contain the characters.

If you are using PDO, then your db string will look like this.

$db = 'mysql:host=example.com;dbname=testdb;port=1234;charset=utf8mb4';


问:
outerHtml returns undefined for SVG elements in IE
Here is my code

```<code><svg id="a" height="210" width="400">
  <path id="b" d="M150 0 L75 200 L225 200 Z" />
</svg>
</code>```

i have trigger mouse move event on b

```<code>   $("#b").hover(function() {
        alert($(this)[0].outerHTML);
    });
</code>```

this was working in chrome but not working in IE how can i solve this..

please find the JSFiddle link : http://jsfiddle.net/r8v70Lnk/

alert box will show only in chrome but not in IE..

答:
Dont know if it is a solution for you but i usually do it like:

```<code>new XMLSerializer().serializeToString(document.querySelector('#b'))
</code>```

If you want to parse the string again and insert the node in your document:

```<code>new DOMParser().parseFromString(svgString, "image/svg+xml")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is my code

<svg id="a" height="210" width="400">
  <path id="b" d="M150 0 L75 200 L225 200 Z" />
</svg>

i have trigger mouse move event on b

   $("#b").hover(function() {
        alert($(this)[0].outerHTML);
    });

this was working in chrome but not working in IE how can i solve this..

please find the JSFiddle link : http://jsfiddle.net/r8v70Lnk/

alert box will show only in chrome but not in IE..

Body:
Dont know if it is a solution for you but i usually do it like:

new XMLSerializer().serializeToString(document.querySelector('#b'))

If you want to parse the string again and insert the node in your document:

new DOMParser().parseFromString(svgString, "image/svg+xml")


问:
Laravel Relationship result can not fetch for same foreign key
My table looks like below,

```<code>donation_requests
---------------------------------------------------------------
| id    name    donation_type_id    donation_request_type_id
|--------------------------------------------------------------
| 1     xyz     1                   3
| 2     pqr     3                   2
| 3     abc     3                   1
| 4     klm     4                   1

donation_types
------------------------
| id    name
-----------------------
| 1     jakat
| 2     sadka
| 3     lillah
| 4     fitra

donation_request_types
------------------------
| id    name
-----------------------
| 1     widow
| 2     masjid
| 3     madresha
</code>```

i want donation_request data with donation_types name and donation_request_types name
In my DonationRequest model code is as below

```<code>public function donation_types()
{
    return $this->belongsTo('App\DonationType','id','donation_type_id');
}

public function donation_request_types()
{
    return $this->belongsTo('App\DonationRequestType','id','donation_request_type_id');
}
</code>```

but in first two row i get proper result but for third row has same donation_type_id as 3 so it give blank and same as in donation_request_type_id

答: As per my above question relationship is working fine, and it has issue in laravel tinker. While testing in postman i found perfect result, but in tinker there will be some issue. Update tinker but still have same problem.</p>

Body:
My table looks like below,

donation_requests
---------------------------------------------------------------
| id    name    donation_type_id    donation_request_type_id
|--------------------------------------------------------------
| 1     xyz     1                   3
| 2     pqr     3                   2
| 3     abc     3                   1
| 4     klm     4                   1

donation_types
------------------------
| id    name
-----------------------
| 1     jakat
| 2     sadka
| 3     lillah
| 4     fitra

donation_request_types
------------------------
| id    name
-----------------------
| 1     widow
| 2     masjid
| 3     madresha

i want donation_request data with donation_types name and donation_request_types name
In my DonationRequest model code is as below

public function donation_types()
{
    return $this->belongsTo('App\DonationType','id','donation_type_id');
}

public function donation_request_types()
{
    return $this->belongsTo('App\DonationRequestType','id','donation_request_type_id');
}

but in first two row i get proper result but for third row has same donation_type_id as 3 so it give blank and same as in donation_request_type_id


问:
Python 2.7 - Raw_input and If and else
raw_input('What are you doing?     ')

a = 'nothing'
if type(a):
    print 'That seems boring'
else:
    print 'Nice'

The meaning of this code, is that if a person answers the raw_input with 'nothing'. It should print that seems boring. And if a person writes something else it should print ok.

I am new to programming so please help me :)

答:
If I understood your question correctly, what you are looking for is:

```<code>a = raw_input("What are you doing?")
</code>```

Notice that the answer to the prompt is saved in the variable 'a'.

```<code>if a == 'nothing':
    print 'That seems boring'
else:
    print 'Nice'
</code>```

Pay attention to the indentation. Also, we use '==' for comparison and '=' for assigning values to a variable.

I suggest you learn basics of python from https://www.codecademy.com/

Title: Python 2.7 - Raw_input and If and else

Body:
If I understood your question correctly, what you are looking for is:

a = raw_input("What are you doing?")

Notice that the answer to the prompt is saved in the variable 'a'.

if a == 'nothing':
    print 'That seems boring'
else:
    print 'Nice'

Pay attention to the indentation. Also, we use '==' for comparison and '=' for assigning values to a variable.

I suggest you learn basics of python from https://www.codecademy.com/


问:
Material UI Cards subttitle introduces Horizontal Scroll bar
I face this issue for Cards that when the Subtitle becomes long the card starts a Horizontal scroll bar before breaking into next Line. Any way this can be solved? Please see the demo of what I am talking here...

I would ideally like the Subtitle to break without the horizontal scrolling, any help would be appreciated.. thanks

答:
This will fix your problem. You just need to fix the strange padding-right: 90px todiv in card-header.

```<code><CardHeader className="card-header" /*Your next attributes*/ />

.card-header{
  display: flex;
}
</code>```

Body:
This will fix your problem. You just need to fix the strange padding-right: 90px todiv in card-header.

<CardHeader className="card-header" /*Your next attributes*/ />

.card-header{
  display: flex;
}


问:
Anomaly detection with machine learning without labels
I am tracing multiple signals for a certain period of time and associating them with a timestamp like following:

```<code>t0 1 10 2 0 1 0 ...
t1 1 10 2 0 1 0 ...
t2 3  0 9 7 1 1 ... // pressed a button to change the mode
t3 3  0 9 7 1 1 ...
t4 3  0 8 7 1 1 ... // pressed button to adjust a certain characterstic like temperature (signal 3)
</code>```

where t0 is the tamp stamp, 1 is the value for signal 1, 10 the value for signal 2 and so on.

That captured data during that certain period of time should be considered as the normal case. Now significant derivations should be detected from the normal case. With significant derivation I do NOT mean that one signal value just changes to a value that has not been seen during the tracing phase but rather that a lot of values change that have not yet been related to each other. I do not want to hardcode rules since in the future more signals might be added or removed and other "modi" that have other signal values might be implemented.

Can this be achieved via a certain Machine Learning algorithm? If a small derivation occurs I want the algorithm to first see it as a minor change to the training set and if it occurs multiple times in the future it should be "learned". The major goal is to detect the bigger changes / anomalies.

I hope I could explain my problem detailed enough. Thanks in advance.

答:
you could just calculate the nearest neighbor in your feature space and set a threshold how far its allowed to be away from your test point to not be an anomaly.

Lets say you have 100 values in your "certain period of time"

so you use a 100 dimensional feature space with your training data (which doesn't contain anomalies)

If you get a new dataset you want to test, you calculate the (k) nearest neighbor(s) and calculate the (e.g. euclidean) distance in your featurespace.

If that distance is larger than a certain threshold it's an anomaly.
What you have to do in order to optimize is finding a good k and a good threshold. E.g. by Grid-search.

(1) Note that something like this probably only works well if your data has a fixed starting and ending point. Otherwise you would need a huge amount of data and even than it will not perform as good.

(2) Note It should be worth trying to create an own detector for every "mode" you have mentioned in your question.

Body:
I am tracing multiple signals for a certain period of time and associating them with a timestamp like following:

t0 1 10 2 0 1 0 ...
t1 1 10 2 0 1 0 ...
t2 3  0 9 7 1 1 ... // pressed a button to change the mode
t3 3  0 9 7 1 1 ...
t4 3  0 8 7 1 1 ... // pressed button to adjust a certain characterstic like temperature (signal 3)

where t0 is the tamp stamp, 1 is the value for signal 1, 10 the value for signal 2 and so on.

That captured data during that certain period of time should be considered as the normal case. Now significant derivations should be detected from the normal case. With significant derivation I do NOT mean that one signal value just changes to a value that has not been seen during the tracing phase but rather that a lot of values change that have not yet been related to each other. I do not want to hardcode rules since in the future more signals might be added or removed and other "modi" that have other signal values might be implemented.

Can this be achieved via a certain Machine Learning algorithm? If a small derivation occurs I want the algorithm to first see it as a minor change to the training set and if it occurs multiple times in the future it should be "learned". The major goal is to detect the bigger changes / anomalies.

I hope I could explain my problem detailed enough. Thanks in advance.


问:
getchar function to clear input buffer outside of while-condition?
I have learned that one can empty the input buffer like this:

```<code>while((ch = getchar()) != EOF && ch != '\n');
if (ch == EOF) {
    // oops
}
</code>```

Why then, can I not empty the buffer by one character with the line:

```<code>c = getchar();
</code>```

This line will cause the program to wait for user input. Context:

```<code>void strfuncs()
{
    char name[50] = {0};
    char lastname[50] = {0};
    char c;

    printf("Enter name...:");
    fgets(name, 50, stdin);
    printf("Enter last name...:");
    fgets(lastname, 50, stdin);

    c=getchar();
    printf("Enter a character...:");
    fgets(&c, 1, stdin);

    printf("c: %c",c);
}
</code>```

答:
```<code>c = getchar();
</code>```

That does empty the buffer by one character, if there is a buffer. However, given the speed at which humans type relative to the speed at which computers operate, it is likely that the buffer is empty when that line gets executed. if the buffer is empty getchar will wait until it is not.

```<code>while((ch = getchar()) != EOF && ch != '\n');
</code>```

The above is no different. Most of the time, the computer will be waiting inside getchar for the buffer to become non empty.

In normal mode when standard input comes from the terminal, the operating system only sends characters to the program's input buffer when it has received a new line character or, if forced to by the user typing ctrl-D (on *nixes, not sure what the equivalent is on Windows). The loop will actually block in the first getchar() until you have typed a whole line and pressed return. It will then whizz round the loop as fast as possible consuming all the characters you typed. This all happens after you pressed the return key.

```<code>char c;        // <<<< Wrong!
c = getchar();
</code>```

This is tangential to the question, but the type of getchar() is int. This is important because EOF needs to be differentiated from all of the valid characters that can be entered and in some character sets, every possible value of a char (0 to 255 or -128 to 127 on all modern common implementations) is a valid character.

Body:
I have learned that one can empty the input buffer like this:

while((ch = getchar()) != EOF && ch != '\n');
if (ch == EOF) {
    // oops
}

Why then, can I not empty the buffer by one character with the line:

c = getchar();

This line will cause the program to wait for user input. Context:

void strfuncs()
{
    char name[50] = {0};
    char lastname[50] = {0};
    char c;

    printf("Enter name...:");
    fgets(name, 50, stdin);
    printf("Enter last name...:");
    fgets(lastname, 50, stdin);

    c=getchar();
    printf("Enter a character...:");
    fgets(&c, 1, stdin);

    printf("c: %c",c);
}

Body:
c = getchar();

That does empty the buffer by one character, if there is a buffer. However, given the speed at which humans type relative to the speed at which computers operate, it is likely that the buffer is empty when that line gets executed. if the buffer is empty getchar will wait until it is not.

while((ch = getchar()) != EOF && ch != '\n');

The above is no different. Most of the time, the computer will be waiting inside getchar for the buffer to become non empty.

In normal mode when standard input comes from the terminal, the operating system only sends characters to the program's input buffer when it has received a new line character or, if forced to by the user typing ctrl-D (on *nixes, not sure what the equivalent is on Windows). The loop will actually block in the first getchar() until you have typed a whole line and pressed return. It will then whizz round the loop as fast as possible consuming all the characters you typed. This all happens after you pressed the return key.

char c;        // <<<< Wrong!
c = getchar();

This is tangential to the question, but the type of getchar() is int. This is important because EOF needs to be differentiated from all of the valid characters that can be entered and in some character sets, every possible value of a char (0 to 255 or -128 to 127 on all modern common implementations) is a valid character.


问:
How to capture exception by SQL Server to console program?
```<code>for(int i=0; i < fileDirectories.Count;i++){

string script = File.ReadAllText(@fileDirectories[i]);
string[] singleCommand = Regex.Split(script,"^GO", RegexOptions.Multiline);
StringCollection scl = new StringCollection();

foreach(string t in singleCommand){
    if(t.Trim().Length > 0) scl.Add(t.Trim());
}

try
{
    int[] result = Server
               .ConnectionContext
               .ExecuteNonQuery(scl, ExecutionTypes.ContinueOnError);
}catch(Exception e)
{
//whatever
}
}
</code>```

The objective of this program is to run multiple scripts and if fail, capture the exceptions thrown by SQL SERVER and continue running the remaining scripts.

In order to try out, INSERT PERMISSION has been taken away from DB and hence first query (INSERT query) will fail when being executed on SQL SERVER manually because INSERT PERMISSION been taken away with below Error

The INSERT permission was denied on object 'xxx',database 'xxxxx', schema 'xx'

When running the program, variable result will have value 0 indicating the query failed but however it's not throwing error and being catch at catch? How should I pass the exception given by SQL Server to my console program?

答:
Remove ExecutionTypes.ContinueOnError.

No exception is thrown when you set execution type to ContinueOnError.

```<code>try
{
      int[] result = Server.ConnectionContext
                    .ExecuteNonQuery(stringColleciton);
}
catch(SqlException se)
{
      //write log, show message
}
catch(Exception e)
{
      //write log, show message
}
</code>```

Read here about ServerConnection.ExecuteNonQuery Method (String, ExecutionTypes)

Body:
for(int i=0; i < fileDirectories.Count;i++){

string script = File.ReadAllText(@fileDirectories[i]);
string[] singleCommand = Regex.Split(script,"^GO", RegexOptions.Multiline);
StringCollection scl = new StringCollection();

foreach(string t in singleCommand){
    if(t.Trim().Length > 0) scl.Add(t.Trim());
}

try
{
    int[] result = Server
               .ConnectionContext
               .ExecuteNonQuery(scl, ExecutionTypes.ContinueOnError);
}catch(Exception e)
{
//whatever
}
}

The objective of this program is to run multiple scripts and if fail, capture the exceptions thrown by SQL SERVER and continue running the remaining scripts.

In order to try out, INSERT PERMISSION has been taken away from DB and hence first query (INSERT query) will fail when being executed on SQL SERVER manually because INSERT PERMISSION been taken away with below Error

The INSERT permission was denied on object 'xxx',database 'xxxxx', schema 'xx'

When running the program, variable result will have value 0 indicating the query failed but however it's not throwing error and being catch at catch? How should I pass the exception given by SQL Server to my console program?

Body:
Remove ExecutionTypes.ContinueOnError.

No exception is thrown when you set execution type to ContinueOnError.

try
{
      int[] result = Server.ConnectionContext
                    .ExecuteNonQuery(stringColleciton);
}
catch(SqlException se)
{
      //write log, show message
}
catch(Exception e)
{
      //write log, show message
}

Read here about ServerConnection.ExecuteNonQuery Method (String, ExecutionTypes)


问:
Learning CIL
Does anybody know any good resources for learning how to program CIL with in-depth descriptions of commands, etc.? I have looked around but not found anything particularly good.</p>

答:
Expert .NET 2.0 IL Assembler  by Serge Lidin

There was a 1.1 version of the same book, but I haven't seen anything for the latest .NET release.  It's an excellent book.  I used it to write an OCR component in MSIL, as a learning project.

[Edit] @Curt is right, 3.0 and 3.5 are just extensions to 2.0, I hadn't plugged that in to my head yet.  Now I've thought of a fun geek project... compare the disassembly of standard 2.0 code to the new LINQ/Lambda way of performing common tasks like filtering lists.  For some reason I assumed that the magic was happening in new IL features, not just the compiler.

OwnerDisplayName: kronoz

ContentLicense: CC BY-SA 2.5

Title: Learning CIL

LastEditorDisplayName: Eric Z Beard

OwnerDisplayName: Eric Z Beard


问:
How to fetch application icon and application description from iTunes store?
How could I fetch application icon and application details from iTunes store if I have app id?</p>

答:
I believe there is a way to retrieve at least some icons via one of the many App Store RSS feeds, perhaps more easily via a custom feed. I've not tried this method, but I know that at least some apps and websites use them that way.

Better Answer

You can retrieve it all by requesting XML information from the App Store. Dan Grigsby wrote about it about a year ago:

App Store Data Mining Techniques Revealed – Part 1

App Store Data Mining Techniques Revealed – Part 2: Scripting App Store XML Downloads

Part 2 explains how to send a query for a specific app using the app ID. The article doesn't provide code for doing it in iOS, but it's very straightforward once you know what to ask for.


问:
Concatenate two different cell strings, based on ID using Allen Browne ConcatRelated()
I'm trying to use the Allen Brownes ConcatRelated, but not sure if that is needed for this or not.

I have a database with pipes, and their ids, in this I also have a column with the amount of observations on a giving pipe. These observations are on the same pipe but in different rows. I would like to concatenate this into one cell.

To start of with I have two identical set up queries, with the same columns and types in them, these I join in a union query.

Then I want to create a query based on that Union where i concatenate the aforementioned rows.

Probably easier to show in a picture:

Union query is EksportOverblik, where I would like to concatenate the cells Antal observationer if they have the same delledning.

This is what I tried so far.

```<code>Concatrelated("Antal observationer fordelt på kriterie/type";"[EksportOverblik]";"DelledningsID = " & [DelledningsID])
</code>```

Also tried

```<code>ConcatRelated("[Antal observationer fordelt på kriterie/type]";"[EksportOverblik]";"DelledningsID = " & [EksportOverblik].[DelledningsID])
</code>```

and

```<code>ConcatRelated("[Antal observationer fordelt på kriterie/type]";"[EksportOverblik]";"DelledningsID";[EksportOverblik].[DelledningsID])
</code>```

Basically all the ones with the same DelledningsID need to have their Antal observationer fordelt på kriterie/type concatenated into one.

I'm getting Error 3070: The Microsoft Access database engine does not recognize '383' as a valid field name or expression.

答: Seemed I had it right, but a dynamic parameterized query beforehand was the issue. Removed that and it works. </p>

Body:
I'm trying to use the Allen Brownes ConcatRelated, but not sure if that is needed for this or not.

I have a database with pipes, and their ids, in this I also have a column with the amount of observations on a giving pipe. These observations are on the same pipe but in different rows. I would like to concatenate this into one cell.

To start of with I have two identical set up queries, with the same columns and types in them, these I join in a union query.

Then I want to create a query based on that Union where i concatenate the aforementioned rows.

Probably easier to show in a picture:

Union query is EksportOverblik, where I would like to concatenate the cells Antal observationer if they have the same delledning.

This is what I tried so far.

Concatrelated("Antal observationer fordelt på kriterie/type";"[EksportOverblik]";"DelledningsID = " & [DelledningsID])

Also tried

ConcatRelated("[Antal observationer fordelt på kriterie/type]";"[EksportOverblik]";"DelledningsID = " & [EksportOverblik].[DelledningsID])

and

ConcatRelated("[Antal observationer fordelt på kriterie/type]";"[EksportOverblik]";"DelledningsID";[EksportOverblik].[DelledningsID])

Basically all the ones with the same DelledningsID need to have their Antal observationer fordelt på kriterie/type concatenated into one.

I'm getting Error 3070: The Microsoft Access database engine does not recognize '383' as a valid field name or expression.


问:
Combobox for single data, but multiple representations
I am not sure combobox would be the best vehicle for tackling this problem, but visually it is appealing.

Consider such data as angle -- I could enter its value in radians (single editbox) or in form of degree, minute, second, millisecond (4 editboxes) -- there are other representations, but those two will suffice here. For now I have combobox with mode entries "radians", "DMS" changing mode shows/hides appropriate control.

This approach has two flaws -- it takes a bit more space (for extra combobox with modes), and since each control is different is size everything on right of it moves.

So I am thinking about more direct approach, instead selecting mode, which in turns switches visibility of given control, would it be possible to put each control inside combobox, and combobox would then select that control. The target data would be exactly the same for each row (angle), but each row would have different control, because each row would mean different representation.

Is doable with combobox or am I banging at the wrong door? If combobox is suitable for this task, how to do it?

答:
I was so focused on data binding at the combobox level that I didn't notice that the solution uses the basics of combobox.

So first, for the moment forget about combobox binding to anything -- simply per each row define ComboBoxItem and put any control you like. In effect you will get multiple controls for the same data.

At this point the only missing part is selecting the mode. Since I no longer rely on manually switching visibility of the controls (combobox does it automatically) then I can bind to SelectedIndex and convert it only fly back and forth to mode.

Please note combobox is not bound per se to the actual data (angle in this case).


问:
Scroll Position of UITextView at the top
I am using swift and want a UITextView to be at the top when the view launches. At the moment when I launch the app the UITextView is scrolled to the end. I have tried looking online and think scrollRangeToVisible might work but do not know how to use it in swift.</p>

```<code>import UIKit

class ThirdViewController: UIViewController {

    @IBOutlet weak var FunFact: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        FunFact.scrollRangeToVisible(0, 0)
        // Do any additional setup after loading the view.
    }
}
</code>```

答:
Add this to your ViewController:

```<code>    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        textView.layoutIfNeeded()
        textView.contentOffset = CGPoint.zero
    }
</code>```

This scrolls the UITextView to the top. Since it only knows its size, when it is layouted, "layoutIfNeeded" is needed after you changed the text (i changed it in viewDidLoad).

Body:
I am using swift and want a UITextView to be at the top when the view launches. At the moment when I launch the app the UITextView is scrolled to the end. I have tried looking online and think scrollRangeToVisible might work but do not know how to use it in swift.

import UIKit

class ThirdViewController: UIViewController {

    @IBOutlet weak var FunFact: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        FunFact.scrollRangeToVisible(0, 0)
        // Do any additional setup after loading the view.
    }
}

Body:
Add this to your ViewController:

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        textView.layoutIfNeeded()
        textView.contentOffset = CGPoint.zero
    }

This scrolls the UITextView to the top. Since it only knows its size, when it is layouted, "layoutIfNeeded" is needed after you changed the text (i changed it in viewDidLoad).


问:
non standard locale with java.util.Calendar
We have a customer in Sweden, using the software in English. So we set the Locale(en, SV). We did hope the Calendar class would adhere to the country settings, but it uses the language and with this locale it assumes US settings.

So I am now searching for a way to let the calendar get to know the new firstDayOfWeek and minimumDayinFirstWeek settings preferred by a standard way other than setting it manually and thus hardcoded.

For clarification: The 29. August 2010 is in Sweden in CW 34 (also in Germany and Great Britain) but in the US it is reported as CW 36. The different results from the fact that the 01.01.2010 is a Friday and the 29.08.2010 a Sunday.

I cannot change the language setting itself to Swedish and use the English fallback since we do not support Swedish as language, but Sun/Oracle/.. does, so the Swing UI would have a mixture of Swedish and English texts, which not acceptable.

And just adding a properties file named "sun.util.resources.CalendarData_en_SV.properties" does not work out: it does not get read! Manually as a ResourceBundle that's possible. Somehow LocaleData.getCalendarData(Locale) does its own magic in reading the resourcfiles which i cannot find out since the source of it is not available. The method is called here: java.util.Calendar.setWeekCountData(Locale).

I also found the java.util.spi package but it does not provide access to the firstDayOfWeek and minimumDaysInFirstWeek settings.

Perhaps I can try to intercept the calls to the resourcebundles and use the default fallback to English and only let the calls to CalendarData proceed!? But that sounds hacky.

```<code>package de.drews.i18n;

import java.util.Calendar;
import java.util.Locale;
import java.util.ResourceBundle;

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
       // en_GB = 34
       // en_US = 36
       // sv_SV = 34
       // en_SV = 36 --> wrong

       printTest("en", "GB", 34);
       printTest("en", "US", 36);
       printTest("sv", "SV", 34);
       printTest("en", "SV", 34);
    }

    private static void printTest(String language, String country, int expected) {
       Locale locale = new Locale(language, country);

       Calendar cal = Calendar.getInstance(locale);

       cal.set(Calendar.YEAR, 2010);
       cal.set(Calendar.MONTH, Calendar.AUGUST);
       cal.set(Calendar.DATE, 29);

       int actual = cal.get(Calendar.WEEK_OF_YEAR);

       System.out.println(actual + "\t" + expected + "\t"
        + ((actual == expected) ? "Yeah!" : "-") + "\t" + language
        + "\t" + country);
    }
}
</code>```

答: How about using getInstance(TimeZone zone, Locale aLocale) providing a timezone to select calendar behaviour and locale to define language?

Body:
We have a customer in Sweden, using the software in English. So we set the Locale(en, SV). We did hope the Calendar class would adhere to the country settings, but it uses the language and with this locale it assumes US settings.

So I am now searching for a way to let the calendar get to know the new firstDayOfWeek and minimumDayinFirstWeek settings preferred by a standard way other than setting it manually and thus hardcoded.

For clarification: The 29. August 2010 is in Sweden in CW 34 (also in Germany and Great Britain) but in the US it is reported as CW 36. The different results from the fact that the 01.01.2010 is a Friday and the 29.08.2010 a Sunday.

I cannot change the language setting itself to Swedish and use the English fallback since we do not support Swedish as language, but Sun/Oracle/.. does, so the Swing UI would have a mixture of Swedish and English texts, which not acceptable.

And just adding a properties file named "sun.util.resources.CalendarData_en_SV.properties" does not work out: it does not get read! Manually as a ResourceBundle that's possible. Somehow LocaleData.getCalendarData(Locale) does its own magic in reading the resourcfiles which i cannot find out since the source of it is not available. The method is called here: java.util.Calendar.setWeekCountData(Locale).

I also found the java.util.spi package but it does not provide access to the firstDayOfWeek and minimumDaysInFirstWeek settings.

Perhaps I can try to intercept the calls to the resourcebundles and use the default fallback to English and only let the calls to CalendarData proceed!? But that sounds hacky.

package de.drews.i18n;

import java.util.Calendar;
import java.util.Locale;
import java.util.ResourceBundle;

public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
       // en_GB = 34
       // en_US = 36
       // sv_SV = 34
       // en_SV = 36 --> wrong

       printTest("en", "GB", 34);
       printTest("en", "US", 36);
       printTest("sv", "SV", 34);
       printTest("en", "SV", 34);
    }

    private static void printTest(String language, String country, int expected) {
       Locale locale = new Locale(language, country);

       Calendar cal = Calendar.getInstance(locale);

       cal.set(Calendar.YEAR, 2010);
       cal.set(Calendar.MONTH, Calendar.AUGUST);
       cal.set(Calendar.DATE, 29);

       int actual = cal.get(Calendar.WEEK_OF_YEAR);

       System.out.println(actual + "\t" + expected + "\t"
        + ((actual == expected) ? "Yeah!" : "-") + "\t" + language
        + "\t" + country);
    }
}


问:
How to delete Failed Jenkins Job in a way that build number count remain noneffective?
Is there any way by which i can delete failed Jenkins jobs and count becomes like 1, 2, 3, 4, 5 and not like 1, 2, 4, 5, 6 assuming that job number 3 has failed and thus deleted.

My case:
I deleted Red (Failed) Jenkins Job as i want 5 consecutive Jobs to be Green. Now when i build again, new Job is build with new build number as +1. So it is visible that some job has been deleted.

Any help?

答:
It's possible. I only know one way but it's rather hacky and the exact steps will depend on your version of jenkins, the operating system that it's hosted on and the way that jenkins was installed. I'm including the steps for a fairly typical jenkins 2.63 CentOS install as a proof of concept with the caveat that it's not really standard practice for someone to rewrite their build history.

The change would involve modifying the jenkins build configs directly on disk and then restarting/reloading jenkins. The install path is site-specific, but in this example it's /var/lib/jenkins
The directory layout will depend on your jenkins version, but in this example there's a jobs subdirectory which contains a separate directory for each jenkins job, eg:

```<code>$ ls -l /var/lib/jenkins/jobs/
total 0
drwxr-x---. 5 jenkins jenkins 4096 Jul  3 08:37 jenkins_job_1
drwxr-x---. 5 jenkins jenkins 4096 Jul  3 08:37 jenkins_job_2
drwxr-x---. 5 jenkins jenkins 4096 Jul  3 08:37 jenkins_job_3
</code>```

Inside the job directory there is a subdirectory containing the jenkins build history, symlinks to the most recent successful and unsuccessful builds, the xml containing the job configuration and a file showing the next build number:

```<code>$ ls -l /var/lib/jenkins/jobs/jenkins_job_1
total 16
drwxr-x---. 4 jenkins jenkins 4096 Jun 21 16:54 builds
-rw-r-----. 1 jenkins jenkins 4146 Jun 21 12:28 config.xml
lrwxrwxrwx. 1 jenkins jenkins   22 Jun 21 16:29 lastStable -> builds/lastStableBuild
lrwxrwxrwx. 1 jenkins jenkins   26 Jun 21 16:29 lastSuccessful -> builds/lastSuccessfulBuild
-rw-r-----. 1 jenkins jenkins    4 Jun 27 10:53 nextBuildNumber
</code>```

The build runs themselves will look something like this:

```<code>$ ls -l /var/lib/jenkins/jobs/jenkins_job_1/builds/
total 0
drwxr-x---. 2 jenkins jenkins 78 Jun 29 10:13 1
drwxr-x---. 2 jenkins jenkins 78 Jun 29 10:13 2
drwxr-x---. 2 jenkins jenkins 78 Jun 29 10:14 3
drwxr-x---. 2 jenkins jenkins 78 Jun 29 10:38 4
drwxr-x---. 2 jenkins jenkins 78 Jun 29 11:51 5
drwxr-x---. 2 jenkins jenkins 78 Jun 29 13:11 6
drwxr-x---. 2 jenkins jenkins 78 Jun 29 13:21 7
drwxr-x---. 2 jenkins jenkins 78 Jun 29 13:41 8
drwxr-x---. 2 jenkins jenkins 78 Jun 29 13:50 9
drwxr-x---. 2 jenkins jenkins 78 Jun 29 13:55 10
lrwxrwxrwx. 1 jenkins jenkins  1 Jun 29 10:13 lastFailedBuild -> 2
lrwxrwxrwx. 1 jenkins jenkins  2 Jul  5 09:46 lastStableBuild -> 10
lrwxrwxrwx. 1 jenkins jenkins  2 Jul  5 09:46 lastSuccessfulBuild -> 10
lrwxrwxrwx. 1 jenkins jenkins  2 Jun 29 08:17 lastUnstableBuild -> -1
lrwxrwxrwx. 1 jenkins jenkins  1 Jun 29 10:13 lastUnsuccessfulBuild -> 2
-rw-r-----. 1 jenkins jenkins  0 Jun 29 08:17 legacyIds
</code>```

In order to edit the build history, the relevant build directory will need to be deleted, the subsequent build numbers will need to be decremented and the symlinks for the last failed, successful, unsuccessful, unstable and stable builds will need to be repointed where necessary. For example, if we choose to delete build 5, then builds 6-10 will need to be renamed and the relevant symlinks repointed:

```<code>$ rm -rf /var/lib/jenkins/jobs/jenkins_job_1/builds/5
$ for i in `seq 6 10`; do mv -i $i $(($i - 1)); done
$ ln -sf 9 lastStableBuild
$ ln -sf 9 lastSuccessfulBuild
</code>```

Once all the relevant symlinks have been updated, you'll also need to decrement the nextBuildNumber:

```<code>echo 10 > /var/lib/jenkins/jobs/jenkins_job_1/nextBuildNumber
</code>```

Then either restart jenkins from the command line or "Manage Jenkins" option in the web interface and the changes to the job should be visible. Alternatively, you could try the "Reload Configuration from Disk" option in the jenkins web interface.

Body:
It's possible. I only know one way but it's rather hacky and the exact steps will depend on your version of jenkins, the operating system that it's hosted on and the way that jenkins was installed. I'm including the steps for a fairly typical jenkins 2.63 CentOS install as a proof of concept with the caveat that it's not really standard practice for someone to rewrite their build history.

The change would involve modifying the jenkins build configs directly on disk and then restarting/reloading jenkins. The install path is site-specific, but in this example it's /var/lib/jenkins
The directory layout will depend on your jenkins version, but in this example there's a jobs subdirectory which contains a separate directory for each jenkins job, eg:

$ ls -l /var/lib/jenkins/jobs/
total 0
drwxr-x---. 5 jenkins jenkins 4096 Jul  3 08:37 jenkins_job_1
drwxr-x---. 5 jenkins jenkins 4096 Jul  3 08:37 jenkins_job_2
drwxr-x---. 5 jenkins jenkins 4096 Jul  3 08:37 jenkins_job_3

Inside the job directory there is a subdirectory containing the jenkins build history, symlinks to the most recent successful and unsuccessful builds, the xml containing the job configuration and a file showing the next build number:

$ ls -l /var/lib/jenkins/jobs/jenkins_job_1
total 16
drwxr-x---. 4 jenkins jenkins 4096 Jun 21 16:54 builds
-rw-r-----. 1 jenkins jenkins 4146 Jun 21 12:28 config.xml
lrwxrwxrwx. 1 jenkins jenkins   22 Jun 21 16:29 lastStable -> builds/lastStableBuild
lrwxrwxrwx. 1 jenkins jenkins   26 Jun 21 16:29 lastSuccessful -> builds/lastSuccessfulBuild
-rw-r-----. 1 jenkins jenkins    4 Jun 27 10:53 nextBuildNumber

The build runs themselves will look something like this:

$ ls -l /var/lib/jenkins/jobs/jenkins_job_1/builds/
total 0
drwxr-x---. 2 jenkins jenkins 78 Jun 29 10:13 1
drwxr-x---. 2 jenkins jenkins 78 Jun 29 10:13 2
drwxr-x---. 2 jenkins jenkins 78 Jun 29 10:14 3
drwxr-x---. 2 jenkins jenkins 78 Jun 29 10:38 4
drwxr-x---. 2 jenkins jenkins 78 Jun 29 11:51 5
drwxr-x---. 2 jenkins jenkins 78 Jun 29 13:11 6
drwxr-x---. 2 jenkins jenkins 78 Jun 29 13:21 7
drwxr-x---. 2 jenkins jenkins 78 Jun 29 13:41 8
drwxr-x---. 2 jenkins jenkins 78 Jun 29 13:50 9
drwxr-x---. 2 jenkins jenkins 78 Jun 29 13:55 10
lrwxrwxrwx. 1 jenkins jenkins  1 Jun 29 10:13 lastFailedBuild -> 2
lrwxrwxrwx. 1 jenkins jenkins  2 Jul  5 09:46 lastStableBuild -> 10
lrwxrwxrwx. 1 jenkins jenkins  2 Jul  5 09:46 lastSuccessfulBuild -> 10
lrwxrwxrwx. 1 jenkins jenkins  2 Jun 29 08:17 lastUnstableBuild -> -1
lrwxrwxrwx. 1 jenkins jenkins  1 Jun 29 10:13 lastUnsuccessfulBuild -> 2
-rw-r-----. 1 jenkins jenkins  0 Jun 29 08:17 legacyIds

In order to edit the build history, the relevant build directory will need to be deleted, the subsequent build numbers will need to be decremented and the symlinks for the last failed, successful, unsuccessful, unstable and stable builds will need to be repointed where necessary. For example, if we choose to delete build 5, then builds 6-10 will need to be renamed and the relevant symlinks repointed:

$ rm -rf /var/lib/jenkins/jobs/jenkins_job_1/builds/5
$ for i in `seq 6 10`; do mv -i $i $(($i - 1)); done
$ ln -sf 9 lastStableBuild
$ ln -sf 9 lastSuccessfulBuild

Once all the relevant symlinks have been updated, you'll also need to decrement the nextBuildNumber:

echo 10 > /var/lib/jenkins/jobs/jenkins_job_1/nextBuildNumber

Then either restart jenkins from the command line or "Manage Jenkins" option in the web interface and the changes to the job should be visible. Alternatively, you could try the "Reload Configuration from Disk" option in the jenkins web interface.


问:
Python checking if string in list to list
I am having a hard time trying to understand how the "for" function works.

I want to make a script that only outputs the strings in list2 that are not inside list1. For example:

```<code>list1 = ["link1.com", "link2.com", "link3.com"]
list2 = ["link2.com", "link123.com"]

for list2 in list1:
    print(list2)
</code>```

{My intention was that the code printed:

link123.com

But instead it printed the strings from list1}

I can't get it to work. Help would be much appreciated. I am using python 3 by the way.

答:
Or if you want to use a for loop (note that this isn't very efficient for large lists):</p>

```<code>for string in list2:
    if not string in list1:
        print (string)
</code>```

Body:
I am having a hard time trying to understand how the "for" function works.

I want to make a script that only outputs the strings in list2 that are not inside list1. For example:

list1 = ["link1.com", "link2.com", "link3.com"]
list2 = ["link2.com", "link123.com"]

for list2 in list1:
    print(list2)

{My intention was that the code printed:

link123.com

But instead it printed the strings from list1}

I can't get it to work. Help would be much appreciated. I am using python 3 by the way.

Body:
Or if you want to use a for loop (note that this isn't very efficient for large lists):

for string in list2:
    if not string in list1:
        print (string)


答:
The loop for list2 in list1 is actually an assignment: in each iteration the variable list2 gets the value of the next item in list1 - that is why only the elements of list1 are printed.

You could iterate over the elements of list2 and print, if they are not in list1:

```<code>for element in list2:
    if element not in list1:
        print(element)
</code>```

Title: Python checking if string in list to list

Body:
The loop for list2 in list1 is actually an assignment: in each iteration the variable list2 gets the value of the next item in list1 - that is why only the elements of list1 are printed.

You could iterate over the elements of list2 and print, if they are not in list1:

for element in list2:
    if element not in list1:
        print(element)


问:
React-Native play video using expo sdk
I want to play a video from url using expo sdk for react native.I read the sdk but I am unable to understand how to make it work.
Here is link for expo sdk video docs.

Here is my code

```<code> import React from 'react';
import { StyleSheet, Text, View,Button } from 'react-native';
import { Video } from 'expo';

export default class App extends React.Component {
    _handleVideoRef = component => {

    }

    onPlayPressed(){

    }

  render() {

    return (
      <View style={styles.container}>
            <Expo.Video
            source = {{uri :'url for video'}}
            ref={this._handleVideoRef}

            />
            <Text>Open up App.js to start working on your app! </Text>
            <Button onPress={this.onPlayPressed.bind(this)} title = "Play"/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
</code>```

Doc says video tag works as inline but I am not sure why it not playing video or anything more is needed.

Thanks for any help

答:
```<code>import { Video } from 'expo';
</code>```

You imported the Expo.Video module as Video, but you are trying to use that component via Expo.Video.

```<code><Video
  source = {{uri :'url for vide'}}
  ref={this._handleVideoRef}
/>
</code>```

Use it like this. Not Expo.Video

Title: React-Native play video using expo sdk

Body:
I want to play a video from url using expo sdk for react native.I read the sdk but I am unable to understand how to make it work.
Here is link for expo sdk video docs.

Here is my code

 import React from 'react';
import { StyleSheet, Text, View,Button } from 'react-native';
import { Video } from 'expo';

export default class App extends React.Component {
    _handleVideoRef = component => {

    }

    onPlayPressed(){

    }

  render() {

    return (
      <View style={styles.container}>
            <Expo.Video
            source = {{uri :'url for video'}}
            ref={this._handleVideoRef}

            />
            <Text>Open up App.js to start working on your app! </Text>
            <Button onPress={this.onPlayPressed.bind(this)} title = "Play"/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Doc says video tag works as inline but I am not sure why it not playing video or anything more is needed.

Thanks for any help

Body:
import { Video } from 'expo';

You imported the Expo.Video module as Video, but you are trying to use that component via Expo.Video.

<Video
  source = {{uri :'url for vide'}}
  ref={this._handleVideoRef}
/>

Use it like this. Not Expo.Video


问:
performance issues using UNION
Union in the oracle query is causing a lot of FTS (full table scans) and high row count any better way i can rewrite this query ?

```<code>            SELECT
                            tab1.a1,
                            tab1.a2 ,
                            tab2.b1,
                            tab2.b2

            FROM tab1 ,tab2
                    where tab1.aid = tab2.aid
                    and tab1.bid = tab2.bid
            UNION
            SELECT
                            tab1.a1,
                            tab1.a2,
                            tab3.c1,
                            tab3.c2
            FROM tab1 ,tab3
                    where tab1.cid = tab3.cid
                    and tab1.bid =tab3.bid;
</code>```

Explain plan pretty much looks like this..

```<code>                 | Id  | Operation                     | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
                 ---------------------------------------------------------------------------------------
                 |   0 | SELECT STATEMENT              |  1845K|    61M|       |   120K  (1)| 00:00:05 |
                 |   1 |  UNION-ALL                    |       |       |       |            |          |
                 |   2 |   MERGE JOIN                  |  1719K|    57M|       | 98522   (2)| 00:00:04 |
                 |   3 |    SORT JOIN                  |  1761K|    25M|    94M| 30984   (1)| 00:00:02 |
                 |   4 |     TABLE ACCESS FULL         |  1761K|    25M|       | 21911   (1)| 00:00:01 |
                 |*  5 |    SORT JOIN                  |  1882K|    35M|   115M| 67538   (2)| 00:00:03 |
                 |   6 |     TABLE ACCESS FULL         |  1882K|    35M|       | 56061   (2)| 00:00:03 |
                 |   7 |   NESTED LOOPS                |   126K|  3699K|       | 22186   (1)| 00:00:01 |
                 |   8 |    NESTED LOOPS               |   126K|  3699K|       | 22186   (1)| 00:00:01 |
                 |   9 |     TABLE ACCESS FULL         |   126K|  1726K|       |  3232   (2)| 00:00:01 |
</code>```

Index are on (tab1 (aid,bid), tab2(aid,bid) , tab3(cid,bid))

答:
```<code>SELECT t.a1, t.a2
FROM tab1 t
WHERE EXISTS (SELECT 1
              FROM tab2 t2
              WHERE t.aid = t2.aid
              AND t.bid = t2.bid)
OR EXISTS (SELECT 1
           FROM tab3 t3
           WHERE t.cid = t3.cid
           AND t.bid =t3.bid)
</code>```

Title: performance issues using UNION

Body:
Union in the oracle query is causing a lot of FTS (full table scans) and high row count any better way i can rewrite this query ?

            SELECT
                            tab1.a1,
                            tab1.a2 ,
                            tab2.b1,
                            tab2.b2

            FROM tab1 ,tab2
                    where tab1.aid = tab2.aid
                    and tab1.bid = tab2.bid
            UNION
            SELECT
                            tab1.a1,
                            tab1.a2,
                            tab3.c1,
                            tab3.c2
            FROM tab1 ,tab3
                    where tab1.cid = tab3.cid
                    and tab1.bid =tab3.bid;

Explain plan pretty much looks like this..

                 | Id  | Operation                     | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
                 ---------------------------------------------------------------------------------------
                 |   0 | SELECT STATEMENT              |  1845K|    61M|       |   120K  (1)| 00:00:05 |
                 |   1 |  UNION-ALL                    |       |       |       |            |          |
                 |   2 |   MERGE JOIN                  |  1719K|    57M|       | 98522   (2)| 00:00:04 |
                 |   3 |    SORT JOIN                  |  1761K|    25M|    94M| 30984   (1)| 00:00:02 |
                 |   4 |     TABLE ACCESS FULL         |  1761K|    25M|       | 21911   (1)| 00:00:01 |
                 |*  5 |    SORT JOIN                  |  1882K|    35M|   115M| 67538   (2)| 00:00:03 |
                 |   6 |     TABLE ACCESS FULL         |  1882K|    35M|       | 56061   (2)| 00:00:03 |
                 |   7 |   NESTED LOOPS                |   126K|  3699K|       | 22186   (1)| 00:00:01 |
                 |   8 |    NESTED LOOPS               |   126K|  3699K|       | 22186   (1)| 00:00:01 |
                 |   9 |     TABLE ACCESS FULL         |   126K|  1726K|       |  3232   (2)| 00:00:01 |

Index are on (tab1 (aid,bid), tab2(aid,bid) , tab3(cid,bid))


问:
Anugularjs ng-disabled not working as expected for a button element
I have created a new button which should be enabled on loading on page and should get disabled while data on page is getting saved (there is a save button). So basically this new button should be disabled whenever save button is enabled.

Angular code :

```<code><input id="save" class="btn " type="button"
                        value="SAVE BUTTON" ng-click="saveData()" ng-disabled="isSaveButtonDisabled"  />
<input id="create" class="btn " type="button"
                    value="NEW BUTTON" ng-click="createNewButton()" ng-disabled="isCreateButtonDisabled" />
</code>```

In the controller, it is getting attached to scope :

```<code>$scope.isSaveButtonDisabled= isSaveButtonDisabled;
$scope.isCreateButtonDisabled= isCreateButtonDisabled;
</code>```

and there are two function which defines the value of this attribute :

```<code>function isSaveButtonDisabled(){
        $scope.isSaveButtonDisabled= true;
}
function isCreateButtonDisabled(){
        $scope.isCreateButtonDisabled= false;
}
</code>```

But the Create Button remains disabled, not matter what.

What am i missing?

答:
You can call two functions in a  ng-click

try this way.

```<code>$scope.isSaveButtonDisabled= function(){
        $scope.isSaveButtonDisabled= true;
       $scope.isCreateButtonDisabled= false;
}

$scope.isCreateButtonDisabled= function(){
        $scope.isCreateButtonDisabled= false;
        $scope.isSaveButtonDisabled= true;
}
</code>```

Kindly change your code in HTML, like

```<code><input id="save" class="btn " type="button"
                        value="SAVE BUTTON" ng-click="isSaveButtonDisabled();saveData();" ng-disabled="isSaveButtonDisabled"  />
<input id="create" class="btn " type="button"
                    value="NEW BUTTON" ng-click="isCreateButtonDisabled();createNewButton();" ng-disabled="isCreateButtonDisabled" />
</code>```

Body:
I have created a new button which should be enabled on loading on page and should get disabled while data on page is getting saved (there is a save button). So basically this new button should be disabled whenever save button is enabled.

Angular code :

<input id="save" class="btn " type="button"
                        value="SAVE BUTTON" ng-click="saveData()" ng-disabled="isSaveButtonDisabled"  />
<input id="create" class="btn " type="button"
                    value="NEW BUTTON" ng-click="createNewButton()" ng-disabled="isCreateButtonDisabled" />

In the controller, it is getting attached to scope :

$scope.isSaveButtonDisabled= isSaveButtonDisabled;
$scope.isCreateButtonDisabled= isCreateButtonDisabled;

and there are two function which defines the value of this attribute :

function isSaveButtonDisabled(){
        $scope.isSaveButtonDisabled= true;
}
function isCreateButtonDisabled(){
        $scope.isCreateButtonDisabled= false;
}

But the Create Button remains disabled, not matter what.

What am i missing?

Body:
You can call two functions in a  ng-click

try this way.

$scope.isSaveButtonDisabled= function(){
        $scope.isSaveButtonDisabled= true;
       $scope.isCreateButtonDisabled= false;
}

$scope.isCreateButtonDisabled= function(){
        $scope.isCreateButtonDisabled= false;
        $scope.isSaveButtonDisabled= true;
}

Kindly change your code in HTML, like

<input id="save" class="btn " type="button"
                        value="SAVE BUTTON" ng-click="isSaveButtonDisabled();saveData();" ng-disabled="isSaveButtonDisabled"  />
<input id="create" class="btn " type="button"
                    value="NEW BUTTON" ng-click="isCreateButtonDisabled();createNewButton();" ng-disabled="isCreateButtonDisabled" />


问:
bootstrap selectpicker setting data-max-option not working
I am looking for following to get work  but none of the code is working:(

$("#comboColumnOption"+counter).selectpicker('maxOptions', '3');   //Not working

```<code>`$("#comboColumnOption"+counter).data("data-max-options", 3); //Not setting` up as when I click it allowed me to select more than 3 ......

    $("#comboColumnOption"+counter).selectpicker('maxOptions', '3');    $("#comboColumnOption"+counter).selectpicker('render'); //Not work
</code>```

I am using selectpicker from this website:
http://silviomoreto.github.io/bootstrap-select/

```<code>    $("#comboColumnOption"+counter).data("data-max-options", 3);
        $("#comboColumnOption"+counter).selectpicker('render'); // not working
</code>```

答:
Calling

```<code>$('.selectpicker').selectpicker({
    maxOptions:2
});
</code>```

only works once.

If you need to change maxOptions depending on some other parameter - changing maxOptions only works the first time. Subsequent calls will be ignored even if calling:

```<code>$( '#periodselect' ).selectpicker('refresh');
$( '#periodselect' ).selectpicker('render');
$( '#periodselect' ).selectpicker('init');
</code>```

Here is my code:

```<code>if ( i == 0 && periodDisplayName != "Aggregated all" ) {
    if ( $("#periodselect optgroup").attr("data-max-options") == "15" ) {
        $('#periodselect').selectpicker({
            maxOptions:2
        );
    }
} else if ( i == 0 ){
    if ( $("#periodselect optgroup").attr("data-max-options") == "2" ) {
        $('#periodselect').selectpicker({
            maxOptions:15
        });
        $("#periodselect optgroup").attr("data-max-options", 15);
        $('#periodselect').selectpicker('maxOptions', 15);
        $('#periodselect').selectpicker("data-max-options", 15);
        var selRefresh = $( '#periodselect' ).selectpicker('refresh');
        var selRender = $( '#periodselect' ).selectpicker('render');
        var selInit = $( '#periodselect' ).selectpicker('init');
    }
}
</code>```

Testing it I first see that maxOption is set to 2 (from 15), then I want to see if maxOption can be set to 15 again - which it doesnt.

Body:
I am looking for following to get work  but none of the code is working:(

$("#comboColumnOption"+counter).selectpicker('maxOptions', '3');   //Not working

`$("#comboColumnOption"+counter).data("data-max-options", 3); //Not setting` up as when I click it allowed me to select more than 3 ......

    $("#comboColumnOption"+counter).selectpicker('maxOptions', '3');    $("#comboColumnOption"+counter).selectpicker('render'); //Not work

I am using selectpicker from this website:
http://silviomoreto.github.io/bootstrap-select/

    $("#comboColumnOption"+counter).data("data-max-options", 3);
        $("#comboColumnOption"+counter).selectpicker('render'); // not working

Body:
Calling

$('.selectpicker').selectpicker({
    maxOptions:2
});

only works once.

If you need to change maxOptions depending on some other parameter - changing maxOptions only works the first time. Subsequent calls will be ignored even if calling:

$( '#periodselect' ).selectpicker('refresh');
$( '#periodselect' ).selectpicker('render');
$( '#periodselect' ).selectpicker('init');

Here is my code:

if ( i == 0 && periodDisplayName != "Aggregated all" ) {
    if ( $("#periodselect optgroup").attr("data-max-options") == "15" ) {
        $('#periodselect').selectpicker({
            maxOptions:2
        );
    }
} else if ( i == 0 ){
    if ( $("#periodselect optgroup").attr("data-max-options") == "2" ) {
        $('#periodselect').selectpicker({
            maxOptions:15
        });
        $("#periodselect optgroup").attr("data-max-options", 15);
        $('#periodselect').selectpicker('maxOptions', 15);
        $('#periodselect').selectpicker("data-max-options", 15);
        var selRefresh = $( '#periodselect' ).selectpicker('refresh');
        var selRender = $( '#periodselect' ).selectpicker('render');
        var selInit = $( '#periodselect' ).selectpicker('init');
    }
}

Testing it I first see that maxOption is set to 2 (from 15), then I want to see if maxOption can be set to 15 again - which it doesnt.


问:
Integrate a streaming server with onvif protocol
I have set a streaming server on my raspberry pi to stream my camera over the network, i can stream the camera using a url like http://ipAddress:portNumber I want to build on that to make the Camera onvif compliant, how do I proceed?
Thanks.</p>

答:
You can do that using "rpos", though I have not tested with it.

The result found by "Turn your raspberry pi into an ONVIF IP camera"

There is one thing you need to know.

You should consider the device meet the "Profile S" for inter-operation with "Profile S" compatible ONVIF client(VMS/NVR).

The well-known ONVIF client is "ONVIF Device Manager", also known as ONVIFDM


问:
iOS10 UNNotificationServiceExtension not called
Im implementing new iOS10 extension to use rich notifications. Im trying to test it on push notifications but is not working, I just receive a simple notification and is not going through the extension.

I did all that it's specified in the official sites and some other places:

I have my app up and running with push notifications and the right provisioning profile

I added a new target to my app, a Notification Service Extension

Implemented my own code (it doesn't matter really because is not even entering to the new class)

Also I had to set a provisioning profile for this extension, I just use one with a wildcard, I don't see any documentation specifying if the extension target has to enable push notifications capability, in that case I would need a specific provisioning for this one, at the moment I just use a wildcard prov, anyway it matches (it must match) the profile I use in the app target, and push notifications capability is enabled for the app target only.

I added UNNotificationExtensionCategory and NSExtensionPointIdentifier. Also Im sending the category as part of the push payload from the server.

As I said, I get the notification but never goes through the extension. I see how the OS tries to load the extension but then throws an error with no relevant description to identify the problem:

```<code>Dec 31 21:00:00 iPhone SpringBoard(libextension.dylib)[51] <Notice>: calling plugIn beginUsing:
Dec 31 21:00:57 iPhone pkd[86] <Notice>: assigning plug-in com.test.app.NotificationWithAttachmentExtension(1.0) to plugin sandbox
Dec 31 21:03:57 iPhone pkd[86] <Notice>: enabling pid=51 for plug-in com.test.app.NotificationWithAttachmentExtension(1.0) 38BB5FF1-2597-42E0-B950-169DBFA80573 /private/var/containers/Bundle/Application/A8C47706-C0EC-4FB1-ABA7-0118372F6900/testapp.app/PlugIns/NotificationWithAttachmentExtension.appex
Dec 31 21:00:53 iPhone SpringBoard(PlugInKit)[51] <Notice>: plugin com.test.app.NotificationWithAttachmentExtension interrupted
Dec 31 21:03:56 iPhone SpringBoard(PlugInKit)[51] <Notice>: Hub connection error Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.test.app.NotificationWithAttachmentExtension" UserInfo={NSDebugDescription=connection to service named com.test.app.NotificationWithAttachmentExtension}
Jun 29 13:33:36 iPhone SpringBoard(libextension.dylib)[51] <Notice>: PlugInKit error in beginUsing:
Jun 17 23:33:04 iPhone SpringBoard(libextension.dylib)[51] <Notice>: killing invalid plugIn
Dec 31 21:00:00 iPhone SpringBoard(UserNotificationsServer)[51] <Error>: Extension error whilst trying to modify push notification F502-9B36: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.test.app.NotificationWithAttachmentExtension" UserInfo={NSDebugDescription=connection to service named com.test.app.NotificationWithAttachmentExtension}
Dec 31 21:00:00 iPhone SpringBoard(UserNotificationsServer)[51] <Notice>: [com.test.app] Saving notification F502-9B36
Dec 31 21:00:00 iPhone SpringBoard(libextension.dylib)[51] <Notice>: completed calling plugIn beginUsing: for pid: 0
</code>```

Relevant extension .plist:

```<code>  <dict>
    <key>NSExtensionAttributes</key>
    <dict>
      <key>UNNotificationExtensionCategory</key>
      <string>attachmentCategory</string>
      <key>UNNotificationExtensionInitialContentSizeRatio</key>
      <real>1</real>
    </dict>
        <key>NSExtensionPointIdentifier</key>
        <string>com.apple.usernotifications.service</string>
        <key>NSExtensionPrincipalClass</key>
        <string>$(PRODUCT_MODULE_NAME).NotificationService</string>
  </dict>
</code>```

What's wrong or missing?

答:
Be sure that you have 'None' configuration set. Look at the screenshot. With other parameters didReceive doesn't work.

Configuration

Body:
Im implementing new iOS10 extension to use rich notifications. Im trying to test it on push notifications but is not working, I just receive a simple notification and is not going through the extension.

I did all that it's specified in the official sites and some other places:

I have my app up and running with push notifications and the right provisioning profile

I added a new target to my app, a Notification Service Extension

Implemented my own code (it doesn't matter really because is not even entering to the new class)

Also I had to set a provisioning profile for this extension, I just use one with a wildcard, I don't see any documentation specifying if the extension target has to enable push notifications capability, in that case I would need a specific provisioning for this one, at the moment I just use a wildcard prov, anyway it matches (it must match) the profile I use in the app target, and push notifications capability is enabled for the app target only.

I added UNNotificationExtensionCategory and NSExtensionPointIdentifier. Also Im sending the category as part of the push payload from the server.

As I said, I get the notification but never goes through the extension. I see how the OS tries to load the extension but then throws an error with no relevant description to identify the problem:

Dec 31 21:00:00 iPhone SpringBoard(libextension.dylib)[51] <Notice>: calling plugIn beginUsing:
Dec 31 21:00:57 iPhone pkd[86] <Notice>: assigning plug-in com.test.app.NotificationWithAttachmentExtension(1.0) to plugin sandbox
Dec 31 21:03:57 iPhone pkd[86] <Notice>: enabling pid=51 for plug-in com.test.app.NotificationWithAttachmentExtension(1.0) 38BB5FF1-2597-42E0-B950-169DBFA80573 /private/var/containers/Bundle/Application/A8C47706-C0EC-4FB1-ABA7-0118372F6900/testapp.app/PlugIns/NotificationWithAttachmentExtension.appex
Dec 31 21:00:53 iPhone SpringBoard(PlugInKit)[51] <Notice>: plugin com.test.app.NotificationWithAttachmentExtension interrupted
Dec 31 21:03:56 iPhone SpringBoard(PlugInKit)[51] <Notice>: Hub connection error Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.test.app.NotificationWithAttachmentExtension" UserInfo={NSDebugDescription=connection to service named com.test.app.NotificationWithAttachmentExtension}
Jun 29 13:33:36 iPhone SpringBoard(libextension.dylib)[51] <Notice>: PlugInKit error in beginUsing:
Jun 17 23:33:04 iPhone SpringBoard(libextension.dylib)[51] <Notice>: killing invalid plugIn
Dec 31 21:00:00 iPhone SpringBoard(UserNotificationsServer)[51] <Error>: Extension error whilst trying to modify push notification F502-9B36: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.test.app.NotificationWithAttachmentExtension" UserInfo={NSDebugDescription=connection to service named com.test.app.NotificationWithAttachmentExtension}
Dec 31 21:00:00 iPhone SpringBoard(UserNotificationsServer)[51] <Notice>: [com.test.app] Saving notification F502-9B36
Dec 31 21:00:00 iPhone SpringBoard(libextension.dylib)[51] <Notice>: completed calling plugIn beginUsing: for pid: 0

Relevant extension .plist:

  <dict>
    <key>NSExtensionAttributes</key>
    <dict>
      <key>UNNotificationExtensionCategory</key>
      <string>attachmentCategory</string>
      <key>UNNotificationExtensionInitialContentSizeRatio</key>
      <real>1</real>
    </dict>
        <key>NSExtensionPointIdentifier</key>
        <string>com.apple.usernotifications.service</string>
        <key>NSExtensionPrincipalClass</key>
        <string>$(PRODUCT_MODULE_NAME).NotificationService</string>
  </dict>

What's wrong or missing?


问:
reach out $this->basePath() in js file
I need to show some products images generated from database on a page. I use ZF2.

I have database table with src column (data in this column is something like this: img/products/test.jpg) which represents an img tag src.

When I am returning products objects from controller to view script I can easily generate images in .phtml file, img tag is generated this way:

```<code>echo '<img src="' . $this->basePath($product->src) . '">';
</code>```

It normally works.

Now, I am modifying the same code to work with jQuery via AJAX request. So, I need to generate somehow img src in .js file.

img/products/test.jpg is easily generated in .js but what about the $this->basePath() part?

答:
It seems that you are expecting full url using basePath() view helper. This may not be something that you want. But if that is the case, then you have to configure to make the view helper work as you expected in the module.config.php as follows

```<code>'view_manager' => [

    'base_path' => 'http://yoursite.com/', // <-- replace with your website

    'template_path_stack' => [
        __DIR__ . '/../view',
    ],
],
</code>```

If you have this configured then you would get url including your domain name.

```<code>$this->basePath($product->src);
</code>```

So the above would output

```<code>http://yoursite.com/img/products/test.jpg
</code>```

There is another view helper that you can use for the same purpose which does not need configuration like the basePath(). And that is

```<code>$this->serverUrl(); // Outputs http://yoursite.com
</code>```

But keep in mind that this view helper does not have a trailing slash /. So you need to put that manually as the following. Please note the / there.

```<code>$this->serverUrl('/path'); // Outputs http://yoursite.com/path
</code>```

Title: reach out $this->basePath() in js file

Body:
I need to show some products images generated from database on a page. I use ZF2.

I have database table with src column (data in this column is something like this: img/products/test.jpg) which represents an img tag src.

When I am returning products objects from controller to view script I can easily generate images in .phtml file, img tag is generated this way:

echo 'basePath($product->src) . '">';

It normally works.

Now, I am modifying the same code to work with jQuery via AJAX request. So, I need to generate somehow img src in .js file.

img/products/test.jpg is easily generated in .js but what about the $this->basePath() part?

Body:
It seems that you are expecting full url using basePath() view helper. This may not be something that you want. But if that is the case, then you have to configure to make the view helper work as you expected in the module.config.php as follows

'view_manager' => [

    'base_path' => 'http://yoursite.com/', // <-- replace with your website

    'template_path_stack' => [
        __DIR__ . '/../view',
    ],
],

If you have this configured then you would get url including your domain name.

$this->basePath($product->src);

So the above would output

http://yoursite.com/img/products/test.jpg

There is another view helper that you can use for the same purpose which does not need configuration like the basePath(). And that is

$this->serverUrl(); // Outputs http://yoursite.com

But keep in mind that this view helper does not have a trailing slash /. So you need to put that manually as the following. Please note the / there.

$this->serverUrl('/path'); // Outputs http://yoursite.com/path


问:
How do I configure Kubernetes node labels when creating a cluster with kops?
When creating a Kubernetes cluster on AWS with kops version 1.6.2, how do I configure Kubernetes labels for nodes? My specific scenario is that I need to set the label beta.kubernetes.io/fluentd-ds-ready as true, because otherwise Fluentd pods won't be scheduled.

My current kops command for creating a cluster looks as follows:

```<code>kops --state s3://example.com create cluster \
--zones eu-central-1a,eu-central-1b,eu-central-1c \
--master-zones eu-central-1a,eu-central-1b,eu-central-1c \
--topology private --networking flannel --master-size m4.large \
--node-size m4.large --node-count 2 --bastion --cloud aws \
--ssh-public-key id_rsa.pub --authorization RBAC --yes \
production.example.com
</code>```

How do I also configure kops to set the label beta.kubernetes.io/fluentd-ds-ready=true on created Kubernetes nodes?

答:
From https://github.com/kubernetes/kops/issues/742

You can create a yaml file with the cluster definition and the labelling there. On an existing cluster you can then do a rolling update.

Body:
When creating a Kubernetes cluster on AWS with kops version 1.6.2, how do I configure Kubernetes labels for nodes? My specific scenario is that I need to set the label beta.kubernetes.io/fluentd-ds-ready as true, because otherwise Fluentd pods won't be scheduled.

My current kops command for creating a cluster looks as follows:

kops --state s3://example.com create cluster \
--zones eu-central-1a,eu-central-1b,eu-central-1c \
--master-zones eu-central-1a,eu-central-1b,eu-central-1c \
--topology private --networking flannel --master-size m4.large \
--node-size m4.large --node-count 2 --bastion --cloud aws \
--ssh-public-key id_rsa.pub --authorization RBAC --yes \
production.example.com

How do I also configure kops to set the label beta.kubernetes.io/fluentd-ds-ready=true on created Kubernetes nodes?


问:
Named PIPE is stuck on open
I am trying to implement a named PIPE IPC method in which I am sending float values (10) each time the sendToPipe function is being called. Here is the sendToPipe function -

```<code>int fd;
char *fifoPipe = "/tmp/fifoPipe";

void sendToPipe(paTestData *data){

    int readCount   = 10;
    fd      = open(fifoPipe, O_WRONLY);   // Getting stuck here

    // Reading 10 sample float values from a buffer from readFromCB pointer as the initial address on each call to sendToPipe function.
    while(readCount > 0){

        write(fd, &data->sampleValues[data->readFromCB], sizeof(SAMPLE));  // SAMPLE is of float datatype
        data->readFromCB++;
        readCount--;
    }

    close(fd);

    //  Some code here
}
</code>```

And I have initialized the named PIPE in my main here :

```<code>int main(){

    // Some code
    mkfifo(fifoPipe, S_IWUSR | S_IRUSR);

    // Other code
}
</code>```

I am not getting where am I going wrong here. Any help is appreciated. Also let me know if any other information is required.

答:
Summing all the commented points:

Program is "freezing" because of there is no reader on the other side of pipe.

After the first program launch the pipe was created. Next program launches will return FILE_EXIST error.

To write 10 values in a shot to the pipe, making able the reader to receive all them in a shot, you should prepare a buffer and then open the pipe and write to it (blocking mode). As a side note take care of reader side: read function does not grants to retrieve the whole buffer in a shot, so you must check the returned read data number.

Title: Named PIPE is stuck on open

Body:
I am trying to implement a named PIPE IPC method in which I am sending float values (10) each time the sendToPipe function is being called. Here is the sendToPipe function -

int fd;
char *fifoPipe = "/tmp/fifoPipe";

void sendToPipe(paTestData *data){

    int readCount   = 10;
    fd      = open(fifoPipe, O_WRONLY);   // Getting stuck here

    // Reading 10 sample float values from a buffer from readFromCB pointer as the initial address on each call to sendToPipe function.
    while(readCount > 0){

        write(fd, &data->sampleValues[data->readFromCB], sizeof(SAMPLE));  // SAMPLE is of float datatype
        data->readFromCB++;
        readCount--;
    }

    close(fd);

    //  Some code here
}

And I have initialized the named PIPE in my main here :

int main(){

    // Some code
    mkfifo(fifoPipe, S_IWUSR | S_IRUSR);

    // Other code
}

I am not getting where am I going wrong here. Any help is appreciated. Also let me know if any other information is required.


问:
How to change a field based on user's selection in an HTML select?
I have a select list containing variables from a query

```<code><tr>
  <td>County Name:</td>
    <td>
      <select name="countyName" onchange="countyID.value = countyName.value">
                <option>Select a County</option>
        <cfloop query = "getCounties">
        <option value="#countyName#" >#countyName#   #countyID#</option>
        </cfloop>
    </select>
    </td>
</tr>
</code>```

How can I populate the County ID field?

```<code><tr>
  <td>County ID:</td>
    <td><input type="Text" name="countyID">
     </td>
</tr>
</code>```

I've never used jQuery. Is there a way to use just JavaScript? As you can see I've attempted JavaScript, however I can only populate countyID with the countyName and I need it populated with countyID.

答:
Breaking it out into a function this should work for you: Live Example

```<code><table>
    <tbody>
        <tr> <td>County ID:</td> <td><input id="countyId" type="Text" name="countyID"> </td> </tr>
        <tr> <td>County Name:</td>

            <td>
                <select name="countyName" onchange="update(this)">
                    <option>Select a County</option>
                    <option value="1234">asdf</option>
                    <option value="4321">asdf2</option>
                </select>
            </td>
        </tr>
    </tbody>
</table>
<script>
    function update( elem ) {
    document.getElementById('countyID').value = elem.value;
    }
</script>
</code>```

Or in short just change

this:

```<code><select name="countyName" onchange="countyID.value = countyName.value">
</code>```

to this, and it should work

```<code><select name="countyName" onchange="document.getElementById('countyId').value = this.value">
</code>```

You need to reference your DOM elements via document.getElementById() and not just their id alone

Another example here

Body:
I have a select list containing variables from a query

  County Name:

      <select name="countyName" onchange="countyID.value = countyName.value">
                <option>Select a County</option>
        <cfloop query = "getCounties">
        <option value="#countyName#" >#countyName#   #countyID#</option>
        </cfloop>
    </select>

How can I populate the County ID field?

  County ID:
    <input type="Text" name="countyID">

I've never used jQuery. Is there a way to use just JavaScript? As you can see I've attempted JavaScript, however I can only populate countyID with the countyName and I need it populated with countyID.

Body:
Breaking it out into a function this should work for you: Live Example

<table>
    <tbody>
        <tr> <td>County ID:</td> <td><input id="countyId" type="Text" name="countyID"> </td> </tr>
        <tr> <td>County Name:</td>

            <td>
                <select name="countyName" onchange="update(this)">
                    <option>Select a County</option>
                    <option value="1234">asdf</option>
                    <option value="4321">asdf2</option>
                </select>
            </td>
        </tr>
    </tbody>
</table>
<script>
    function update( elem ) {
    document.getElementById('countyID').value = elem.value;
    }
</script>

Or in short just change

this:

<select name="countyName" onchange="countyID.value = countyName.value">

to this, and it should work

<select name="countyName" onchange="document.getElementById('countyId').value = this.value">

You need to reference your DOM elements via document.getElementById() and not just their id alone

Another example here


问:
looping everything in array to compare with each cell
how can i let my my cell be assessed by all the values in the array before moving on to the next cell

sample values inside the array
  N/A

```<code>R008-0097X
R005-0077X
R002-1703X
R003-0301X
R019-1439U

  For Each cel In SrchRnga  ' this entire statement does not replace anything

            If InStr(1, cel.Value, BOM(b )) > 0 Then
                cel.Offset(0, 1).Value = SAP(b)
                cel.Offset(0 + 9, 1).Value = UF(b)
                b = b + 1
            End If
Next cel
</code>```

currently it is just reading it once and moving on.

```<code>for b =1 to 9  ' it starts replacing after i added this code
        For Each cel In SrchRnga

                    If InStr(1, cel.Value, BOM(b )) > 0 Then
                        cel.Offset(0, 1).Value = SAP(b)
                        cel.Offset(0 + 9, 1).Value = UF(b)

                    End If
        Next cel
next b
</code>```

i tried putting a for loop outside thinking that it will read the cell 8 times but this replaces all my values that isn't in the array to ""

what i want to know is:
how to loop the array for each cell without replacing the values that does not exist in the array.

答:
Put the iterator inside the For Each loop</p>

```<code>For Each cel In SrchRnga
    For b = 1 to 9
        If InStr(1, cel.Value, BOM(b )) > 0 Then
            cel.Offset(0, 1).Value = SAP(b)
            cel.Offset(0 + 9, 1).Value = UF(b)
        End If
    next b
Next cel
</code>```

Body:
how can i let my my cell be assessed by all the values in the array before moving on to the next cell

sample values inside the array
  N/A

R008-0097X
R005-0077X
R002-1703X
R003-0301X
R019-1439U

  For Each cel In SrchRnga  ' this entire statement does not replace anything

            If InStr(1, cel.Value, BOM(b )) > 0 Then
                cel.Offset(0, 1).Value = SAP(b)
                cel.Offset(0 + 9, 1).Value = UF(b)
                b = b + 1
            End If
Next cel

currently it is just reading it once and moving on.

for b =1 to 9  ' it starts replacing after i added this code
        For Each cel In SrchRnga

                    If InStr(1, cel.Value, BOM(b )) > 0 Then
                        cel.Offset(0, 1).Value = SAP(b)
                        cel.Offset(0 + 9, 1).Value = UF(b)

                    End If
        Next cel
next b

i tried putting a for loop outside thinking that it will read the cell 8 times but this replaces all my values that isn't in the array to ""

what i want to know is:
how to loop the array for each cell without replacing the values that does not exist in the array.

Body:
Put the iterator inside the For Each loop

For Each cel In SrchRnga
    For b = 1 to 9
        If InStr(1, cel.Value, BOM(b )) > 0 Then
            cel.Offset(0, 1).Value = SAP(b)
            cel.Offset(0 + 9, 1).Value = UF(b)
        End If
    next b
Next cel


问:
jQuery parse string before that symbols "{" "}" (different language on site)
i need to grab some text that is between that { }
But we have 3 languages same time

f.e
{:en}Resources List{:}{:ru}Список Ресурсов{:}{:uk}Список Ресурсів{:}

So if we have english version now, we need to show what is between {:en} some text {:}

答:
Why not use just plain old js

```<code>var langs = "{:en}Resources List{:}{:ru}Список Ресурсов{:}{:uk}Список Ресурсів{:}";
var languageTranslations = langs.split('{:}');
languageTranslations.pop(); // this will remove the last empty string element
</code>```

the above code will result an array like this :

```<code> ["{:en}Resources List", "{:ru}Список Ресурсов", "{:uk}Список Ресурсів"]
</code>```

Now you can parse each of them easily like

```<code>languageTranslations.map(function(item){
 var firstIndexOf = item.indexOf('}');
 var translation = item.substr(firstIndexOf +1 );
 var language =  item.substr(2,firstIndexOf -2);
 return { text : translation , language : language };
});
</code>```

The above code will yield something like this :

```<code>  [{"text":"Resources List","language":"en"},{"text":"Список
 Ресурсов","language":"ru"},{"text":"Список Ресурсів","language":"uk"}]
</code>```

The downside of this parsing method that you have to be sure that your "{:}" delimiter is not in your translations.

Body:
Why not use just plain old js

var langs = "{:en}Resources List{:}{:ru}Список Ресурсов{:}{:uk}Список Ресурсів{:}";
var languageTranslations = langs.split('{:}');
languageTranslations.pop(); // this will remove the last empty string element

the above code will result an array like this :

 ["{:en}Resources List", "{:ru}Список Ресурсов", "{:uk}Список Ресурсів"]

Now you can parse each of them easily like

languageTranslations.map(function(item){
 var firstIndexOf = item.indexOf('}');
 var translation = item.substr(firstIndexOf +1 );
 var language =  item.substr(2,firstIndexOf -2);
 return { text : translation , language : language };
});

The above code will yield something like this :

  [{"text":"Resources List","language":"en"},{"text":"Список
 Ресурсов","language":"ru"},{"text":"Список Ресурсів","language":"uk"}]

The downside of this parsing method that you have to be sure that your "{:}" delimiter is not in your translations.


问:
Django migrate ImageFiles from one app to another
I have two django apps on heroku, app_B is a copy of a section of app_A.

The app_A has models with ImageField:

```<code>image = models.ImageField(null=True, upload_to=get_image_uri)
</code>```

I'd like to copy these objects to the app_B.

The model I'd like to copy looks exactly the same. The images are stored in Amazon AWS.

The django command dumpdata / loaddata gives me FK errors..

However, I could try to solve those FK errors but I'm not sure if loaddata can copy the images themselves, or am I missing something?

Is there any other way to do this?

答:
You can perform a raw SQL query:

```<code>ModelB.objects.raw(
    '''
    INSERT INTO appb_modelb (image)
    SELECT image FROM appa_modela
    '''
)
</code>```

The above assumes that your tables are in the same database and your appb_modelb table is empty at the moment of the copy.

The are more complicated SQL queries that you can achieve this way, should the need rises, like copy a column to a table from a different database.

You must be careful though. Read the docs carefully and especially the warnings in there!

Good luck :)

Body:
I have two django apps on heroku, app_B is a copy of a section of app_A.

The app_A has models with ImageField:

image = models.ImageField(null=True, upload_to=get_image_uri)

I'd like to copy these objects to the app_B.

The model I'd like to copy looks exactly the same. The images are stored in Amazon AWS.

The django command dumpdata / loaddata gives me FK errors..

However, I could try to solve those FK errors but I'm not sure if loaddata can copy the images themselves, or am I missing something?

Is there any other way to do this?

Body:
You can perform a raw SQL query:

ModelB.objects.raw(
    '''
    INSERT INTO appb_modelb (image)
    SELECT image FROM appa_modela
    '''
)

The above assumes that your tables are in the same database and your appb_modelb table is empty at the moment of the copy.

The are more complicated SQL queries that you can achieve this way, should the need rises, like copy a column to a table from a different database.

You must be careful though. Read the docs carefully and especially the warnings in there!

Good luck :)


问:
wordpress font posts by tags count
Have custom post type posttype with multiple taxonomies like tax1, tax2 and post_tag which added like this:

```<code>function add_tags_categories() {
    register_taxonomy_for_object_type('post_tag', 'posttype');
}
add_action('init', 'add_tags_categories');
</code>```

And now searching for any solution to get most related posts by same tags count in posts.. most likely found solution like this:

```<code>$tags = wp_get_post_terms( $post -> ID, 'post_tag', ['fields' => 'ids'] );
$args = array(
    'post__not_in'        => array( $post -> ID ),
    'posts_per_page'      => -1,
    'ignore_sticky_posts' => true,
    'orderby'             => 'count',
    'tax_query' => array(
        array(
            'taxonomy' => 'post_tag',
            'terms'    => $tags
        )
    )
);

$my_query = new wp_query( $args );
</code>```

But its not working.. I got $tags in array with ids,
query also seems working, just not finding any similar posts... but I have created and similar, and identical with tags also.. But result is still 0 posts..

答:
Found solution in here

so I made like this:

```<code>$tags = wp_get_post_terms( $post -> ID, 'post_tag', ['fields' => 'ids'] );
$args = array(
    'post_type'      => 'posttype',
    'post__not_in'        => array( $post -> ID ),
    'posts_per_page'      => -1,
    'ignore_sticky_posts' => true,
    'orderby'             => 'tag_count',
    'order'             => 'DESC',
    'tag__in' => $tags,
);

add_filter( 'posts_clauses', 'wpse173949_posts_clauses', 10, 2 );
$query = new WP_Query( $args );
remove_filter( 'posts_clauses', 'wpse173949_posts_clauses', 10 );
</code>```

Title: wordpress font posts by tags count

Body:
Have custom post type posttype with multiple taxonomies like tax1, tax2 and post_tag which added like this:

function add_tags_categories() {
    register_taxonomy_for_object_type('post_tag', 'posttype');
}
add_action('init', 'add_tags_categories');

And now searching for any solution to get most related posts by same tags count in posts.. most likely found solution like this:

$tags = wp_get_post_terms( $post -> ID, 'post_tag', ['fields' => 'ids'] );
$args = array(
    'post__not_in'        => array( $post -> ID ),
    'posts_per_page'      => -1,
    'ignore_sticky_posts' => true,
    'orderby'             => 'count',
    'tax_query' => array(
        array(
            'taxonomy' => 'post_tag',
            'terms'    => $tags
        )
    )
);

$my_query = new wp_query( $args );

But its not working.. I got $tags in array with ids,
query also seems working, just not finding any similar posts... but I have created and similar, and identical with tags also.. But result is still 0 posts..

Body:
Found solution in here

so I made like this:

$tags = wp_get_post_terms( $post -> ID, 'post_tag', ['fields' => 'ids'] );
$args = array(
    'post_type'      => 'posttype',
    'post__not_in'        => array( $post -> ID ),
    'posts_per_page'      => -1,
    'ignore_sticky_posts' => true,
    'orderby'             => 'tag_count',
    'order'             => 'DESC',
    'tag__in' => $tags,
);

add_filter( 'posts_clauses', 'wpse173949_posts_clauses', 10, 2 );
$query = new WP_Query( $args );
remove_filter( 'posts_clauses', 'wpse173949_posts_clauses', 10 );


问:
Is there a way to empty the session file with PHP?
I'm wondering if I can destroy/modify sessions in a native PHP way that doesn't involve file I/O directives.

I'm not talking about $_SESSION, I mean access to the session files themselves.

For instance, PHP stores sessions on linux as files:

```<code>@lamp:/var/lib/php5$ ls
sess_301dc8935f1775312e9007431782c68b
sess_6892f0bec257e646d193adfd91233c40
sess_966909941003dd6fd333727d8862be6e
sess_cb7c07117cef89674a686ffff8a730f2
sess_ffb4db1d9002741b7e0fcc02090b9aaa
sess_305aeb0fdba7548e389394cb31d77c3b
.... etc
</code>```

$_SESSION gives us the value of what's inside a current session, and the session_start() and session_destroy() will terminate the current session identifier.

I want to know if I can destroy or modify sessions globally in a native way to php that doesn't resort to me having to do fopen(/var/lib/php5/sess_whatever), I don't want to work with the current session, I want a script to be able to either delete or modify sessions outside of what $_SESSION, session_start, and session_stop do, as they force you to use the present session.

答:
session_destroy does that:

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.

Body:
I'm wondering if I can destroy/modify sessions in a native PHP way that doesn't involve file I/O directives.

I'm not talking about $_SESSION, I mean access to the session files themselves.

For instance, PHP stores sessions on linux as files:

@lamp:/var/lib/php5$ ls
sess_301dc8935f1775312e9007431782c68b
sess_6892f0bec257e646d193adfd91233c40
sess_966909941003dd6fd333727d8862be6e
sess_cb7c07117cef89674a686ffff8a730f2
sess_ffb4db1d9002741b7e0fcc02090b9aaa
sess_305aeb0fdba7548e389394cb31d77c3b
.... etc

$_SESSION gives us the value of what's inside a current session, and the session_start() and session_destroy() will terminate the current session identifier.

I want to know if I can destroy or modify sessions globally in a native way to php that doesn't resort to me having to do fopen(/var/lib/php5/sess_whatever), I don't want to work with the current session, I want a script to be able to either delete or modify sessions outside of what $_SESSION, session_start, and session_stop do, as they force you to use the present session.