问:
MPMediaItemArtwork crashed in iOS9
```<code>if (image) {
    MPMediaItemArtwork *media = [[[MPMediaItemArtwork alloc] init] initWithImage:image];  //crashed in this line,iOS9.
}
</code>```

Error info:

ERROR:    258: CA_UISoundClientBase::StartPlaying: AddRunningClient failed (status = -66681).
  NSScanner: nil string argument

Why MPMediaItemArtwork crashed in iOS9?

答:
Theoretically, your original line:

```<code>MPMediaItemArtwork *media = [[[MPMediaItemArtwork alloc] init] initWithImage:image];  //crashed in this line,iOS9.
</code>```

should have worked.The main reason for breaking alloc from init in Objective-C, is to be able to re-initialize an (already initialized) object, like you did.

So you can file a bug with Apple, reporting the crash. The object returned from  [[MPMediaItemArtwork alloc] init] should support reinitializing with an image. At the very least - reinitialization should have returned nil (if failed).

However - given the state of things, a simpler, more traditional, and working way to do this would be simply to initialize with the image on the first place, right after alloc, like thus:

```<code>MPMediaItemArtwork *media = [[MPMediaItemArtwork alloc] initWithImage:image];
</code>```

Title: MPMediaItemArtwork crashed in iOS9

Body:
if (image) {
    MPMediaItemArtwork *media = [[[MPMediaItemArtwork alloc] init] initWithImage:image];  //crashed in this line,iOS9.
}

Error info:

ERROR:    258: CA_UISoundClientBase::StartPlaying: AddRunningClient failed (status = -66681).
  NSScanner: nil string argument

Why MPMediaItemArtwork crashed in iOS9?

Body:
Theoretically, your original line:

MPMediaItemArtwork *media = [[[MPMediaItemArtwork alloc] init] initWithImage:image];  //crashed in this line,iOS9.

should have worked.The main reason for breaking alloc from init in Objective-C, is to be able to re-initialize an (already initialized) object, like you did.

So you can file a bug with Apple, reporting the crash. The object returned from  [[MPMediaItemArtwork alloc] init] should support reinitializing with an image. At the very least - reinitialization should have returned nil (if failed).

However - given the state of things, a simpler, more traditional, and working way to do this would be simply to initialize with the image on the first place, right after alloc, like thus:

MPMediaItemArtwork *media = [[MPMediaItemArtwork alloc] initWithImage:image];


来源: stackexchange

问:
Iwant to insert if condition inside the table->addrow in codeigniter
Iwant to insert this code

```<code>if($transaction_user_define_fields->udf_type == 'Selectbox'){
    echo '<i class="fa fa-list fa-lg text-primary pull-left" data-toggle="tooltip" data-placement="right" title="View option" onclick="viewUDFOPT('.$transaction_user_define_fields->tran_udf_col_id.')"></i>';
}
</code>```

inside

```<code>$this->table->add_row()
</code>```

but im getting an error .please help

答:
```<code>  if($transaction_user_define_fields->udf_type == 'Selectbox'){
       $this->table->add_row('<i class="fa fa-list fa-lg text-primary pull-left" data-toggle="tooltip" data-placement="right" title="View option" onclick="viewUDFOPT('.$transaction_user_define_fields->tran_udf_col_id.')"></i>');
   }
</code>```

This would make the  tag clickable, if you want to make the entire cell clickable you will have to set it as a param in add row
as per codeigniter documentation

```<code> $cell = array('data' => 'Blue', 'class' => 'highlight', 'colspan' => 2);
 $this->table->add_row($cell, 'Red', 'Green');
 // generates
 // <td class='highlight' colspan='2'>Blue</td><td>Red</td><td>Green</td>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Iwant to insert this code

if($transaction_user_define_fields->udf_type == 'Selectbox'){
    echo 'tran_udf_col_id.')">';
}

inside

$this->table->add_row()

but im getting an error .please help

Body:
  if($transaction_user_define_fields->udf_type == 'Selectbox'){
       $this->table->add_row('<i class="fa fa-list fa-lg text-primary pull-left" data-toggle="tooltip" data-placement="right" title="View option" onclick="viewUDFOPT('.$transaction_user_define_fields->tran_udf_col_id.')"></i>');
   }

This would make the  tag clickable, if you want to make the entire cell clickable you will have to set it as a param in add row
as per codeigniter documentation

 $cell = array('data' => 'Blue', 'class' => 'highlight', 'colspan' => 2);
 $this->table->add_row($cell, 'Red', 'Green');
 // generates
 // <td class='highlight' colspan='2'>Blue</td><td>Red</td><td>Green</td>


问:
ID of an array element changes in IPython
Why does ID of array element keeps on changing?

```<code>    In [43]: x = np.array([[1,2,3],[4,5,6],[7,8,9]])
    In [44]: print id(x[0])
    30836416
    In [45]: print id(x[0])
    31121344
    In [46]: print id(x[0])
    31471808
</code>```

IPython Screenshot

This is not the case when it is written in a python script
When written in python script we get the same ID

And also other observation is in the below figure

aCopy is the copy of the array a.
id for the same element of both the arrays is printed twice.
According to the output,
id of all the array elements whether it may be of the same array or different  (copy) is same except for the FIRST print.
Why id of same element of two different arrays are same?
Why one of the id when printed multiple times is different?

答:
id(x[0]) is the pointer of the object created by x.__getitem__(0).  That object is created by numpy code each time you call this, and apart possible caching, will be different.  It is not the id of the bytes in x.data that represent the first array element.  array storage is by value.  List storage is by reference, ie.e. pointer.

This is a duplicate question, but finding the right SO link may be difficult.

From python docs for id

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

If you get repeats of id, check for non-overlapping lifetimes.

Body:
Why does ID of array element keeps on changing?

    In [43]: x = np.array([[1,2,3],[4,5,6],[7,8,9]])
    In [44]: print id(x[0])
    30836416
    In [45]: print id(x[0])
    31121344
    In [46]: print id(x[0])
    31471808

IPython Screenshot

This is not the case when it is written in a python script
When written in python script we get the same ID

And also other observation is in the below figure

aCopy is the copy of the array a.
id for the same element of both the arrays is printed twice.
According to the output,
id of all the array elements whether it may be of the same array or different  (copy) is same except for the FIRST print.
Why id of same element of two different arrays are same?
Why one of the id when printed multiple times is different?


问:
Error: Type or namespace not found
My code there is a errors like

```<code>"The type or namespace name 'ChannelData' could not be found (are you missing a using directive or an assembly reference?)"
</code>```

How I correct this.please give your help.

```<code>class ProcessCSV
    {
        public static string dateFormatString = "dd/MM/yyyy HH:mm:ss";
        private string prefix = "";
        ChannelData[] channelData = new ChannelData[4];

        private ChannelData[] loadChannelData(string[] valuesInCsvLine)
        {
            channelData[0] = new ChannelData();
            channelData[1] = new ChannelData();
            channelData[2] = new ChannelData();
            channelData[3] = new ChannelData();
      }
   }
</code>```

答:
There is .Net framework incompatibility issue between your projects. The project consisting of type ChannelData can be of different version than that of your current project.

Sometimes it is also a client profiling issue. Make sure that both the projects are using the same .Net framework.

If you are using ChannelData from external assembly or dll, then you can right click on ChannelData and just goto definition. It will show you the version and you can match it with your current project (if it's convenient to you).

But if you are not having the above issues then sometimes cleaning and rebuilding your solution simply helps. You can also restart your visual studio.
Hope it helps you.

Title: Error: Type or namespace not found

Body:
My code there is a errors like

"The type or namespace name 'ChannelData' could not be found (are you missing a using directive or an assembly reference?)"

How I correct this.please give your help.

class ProcessCSV
    {
        public static string dateFormatString = "dd/MM/yyyy HH:mm:ss";
        private string prefix = "";
        ChannelData[] channelData = new ChannelData[4];

        private ChannelData[] loadChannelData(string[] valuesInCsvLine)
        {
            channelData[0] = new ChannelData();
            channelData[1] = new ChannelData();
            channelData[2] = new ChannelData();
            channelData[3] = new ChannelData();
      }
   }


问:
login and signup tab does not work xml
I am trying to create login and signup tab on the same page. so everytime I press signup on the login screen, it change to the signup screen as expected, so does the signup screen. On the signup screen, everytime I press the login tab, it works too. But on the login screen, everytime I press login, it goes to signup screen but I want it to stay on login screen. The weird thing is that everytime I press signup, it stays on the signup screen . Can anyone help? any help would be appreciated.

Android classes

SignUpScreen.java

```<code> final Intent i = new Intent(SignUpScreen.this, LoginScreen.class);
    TextView b = (TextView) findViewById(R.id.text1);

    b.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {

            setContentView(R.layout.login_screen);
            SignUpScreen.this.startActivity(i);
        }
    });
</code>```

my LoginScreen.java

```<code>final Intent i = new Intent(LoginScreen.this,SignUpScreen.class);
    TextView c = (TextView) findViewById(R.id.text4);

    c.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {

            setContentView(R.layout.sign_up_screen);
            LoginScreen.this.startActivity(i);
        }
    });
</code>```

答:
You just have to create two activity one for login and another for signup, in login activity you have to give login form and two button one for login and one for signup.
and make the login activity as your launcher activity. on clicking the signup button just call the signup activity by using intent

public class LoginActivity extends Activity {

```<code>private EditText mEmail;
private EditText mPassword;

Button btn_login,btn_signup;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    btn_login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

                uid = mEmailView.getText().toString();
                pwd = mPasswordView.getText().toString();

                if(uid.equalsIgnoreCase("")){
                    mEmailView.setError("Please enter user id");
                }else if(pwd.equalsIgnoreCase("")){
                    mPasswordView.setError("Please enter password");
                }else  {
                    //do whaterver you want to do after login
                }

        }
    });

            btn_signup.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent i=new Intent(LoginActivity.this,Signup.class);
                    startActivity(i);
        }
    });
}
</code>```

}

and in Signup page when you signup the user successfully redirect him to the login page by using  intent

Intent i=new Intent(Signup.this,LoginActivity.class);
                        startActivity(i);

or you can redirect him into the other activity

Title: login and signup tab does not work xml

Body:
I am trying to create login and signup tab on the same page. so everytime I press signup on the login screen, it change to the signup screen as expected, so does the signup screen. On the signup screen, everytime I press the login tab, it works too. But on the login screen, everytime I press login, it goes to signup screen but I want it to stay on login screen. The weird thing is that everytime I press signup, it stays on the signup screen . Can anyone help? any help would be appreciated.

Android classes

SignUpScreen.java

 final Intent i = new Intent(SignUpScreen.this, LoginScreen.class);
    TextView b = (TextView) findViewById(R.id.text1);

    b.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {

            setContentView(R.layout.login_screen);
            SignUpScreen.this.startActivity(i);
        }
    });

my LoginScreen.java

final Intent i = new Intent(LoginScreen.this,SignUpScreen.class);
    TextView c = (TextView) findViewById(R.id.text4);

    c.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {

            setContentView(R.layout.sign_up_screen);
            LoginScreen.this.startActivity(i);
        }
    });

Body:
You just have to create two activity one for login and another for signup, in login activity you have to give login form and two button one for login and one for signup.
and make the login activity as your launcher activity. on clicking the signup button just call the signup activity by using intent

public class LoginActivity extends Activity {

private EditText mEmail;
private EditText mPassword;

Button btn_login,btn_signup;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    btn_login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

                uid = mEmailView.getText().toString();
                pwd = mPasswordView.getText().toString();

                if(uid.equalsIgnoreCase("")){
                    mEmailView.setError("Please enter user id");
                }else if(pwd.equalsIgnoreCase("")){
                    mPasswordView.setError("Please enter password");
                }else  {
                    //do whaterver you want to do after login
                }

        }
    });

            btn_signup.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent i=new Intent(LoginActivity.this,Signup.class);
                    startActivity(i);
        }
    });
}

}

and in Signup page when you signup the user successfully redirect him to the login page by using  intent

Intent i=new Intent(Signup.this,LoginActivity.class);
                        startActivity(i);

or you can redirect him into the other activity


问:
How can I horizontally and vertically center an  in a
?
I don't want to center a div, I want the contents of a div to be centered.  I would like horizontal and vertical alignment.

Sorry, if this is too easy or whatever, but this is kind of a hassle to get it right.

Grae

I am using IE7

答:
although the following is obsolete, it still works for almost all browsers

```<code><center>
<div>
your html
</div>
</center>
</code>```

however, visit this link

http://www.110mb.com/forum/vertical-horizontal-alignment-of-image-within-div-t31709.0.html

ContentLicense: CC BY-SA 2.5

Title: How can I horizontally and vertically center an <img> in a <div>?

Body:
although the following is obsolete, it still works for almost all browsers

<center>
<div>
your html
</div>
</center>

however, visit this link

http://www.110mb.com/forum/vertical-horizontal-alignment-of-image-within-div-t31709.0.html


问:
Wrap PHPWord on bundle
I just want to use PHPWord for Symfony 2. But Im new on Symfony 2.

I paste PHPWord source into my util folder bundle but there is an error loading autoloader class from PHPWord...

Question is simple, How can I "wrap" code (in this case PHPWord) in to bundle? or someway I can use it.

Any solution?

Thanks for answering, that gives me some light. Altough, This doen't work for me.
I download composer.phar and I edit my composer.json as you say: adding in my require region "phpword/phpword": "0.6.2" and creating new repository phpword...

Doesn't work, I run "php composer.phar" command but It doesn't download anything...

Any tutorial or tip to make this work?

Thank you

答:
You can use this simple bundle as wrapper for PhpWord:
https://packagist.org/packages/ggggino/wordbundle</p>

Title: Wrap PHPWord on bundle


问:
Echo the bottom line of a CSV
I am attempting to echo the bottom line only of a .csv file. I echo the file in reverse order (as shown below) but I'm not sure how to only echo the top line of this. Please note that the csv variable, constantly changing.

Here is my php:

<?php
$file = file("file.csv");
$file = array_reverse($file);
foreach($file as $f){
    echo $f."
";
}
?>```

答:
Simple solution is.</p>

```<code>$file = "file.csv";
$data = file($file);
$last_line = $data[count($data)-1];
</code>```

Title: Echo the bottom line of a CSV

Body:
Simple solution is.

$file = "file.csv";
$data = file($file);
$last_line = $data[count($data)-1];


问:
How to find out what's wrong with distributed transactions?
I have googled a lot the last days and checked data and the registry, but did not find a solution or even the root cause of the problem:

We have multiple WCF web services that talk to each other (and finally a SQL Server database) using distributed transactions as "Allowed" (not "Mandatory"). We have a Web Farm (2008R2, IIS7 with WFF) where on one node it works and on the other, it does not. Transactions are simply not routed through.

I wrote a test application that self-hosts a chain of three services that do nothing but calling each other. The last one returns true. This chain will have distributed transactions on one machine (as can be seen by printing out the distributed transaction ID) and no distributed transactions on the other. However, there are no errors. There simply is no transaction coming in.

I have checked the dialogs that open up when you call

dcomcnfg.exe => Computer => MyComputer => Distributed Transaction Controller => Local DTC => Properties

and they are exactly the same on both machines. Just to make sure I exported the registry keys below HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSDTC. The only differences between the machines were the
KtmRmTmIdentifier and the XAKeyCNGKeyDataBlob keys. Being different machines, I would have expected them to be different. All settings were the same.

Now with the very same binary executable working on one and failing on the other machine I strongly suspect our machine setup to be at fault but I'm really out of possible options where to look for differences or how to find out what's wrong.

Does anyone have any ideas what else I could check or what test I could run to find out what the problem is?

Additional Information:

The settings look like this:

答:
We had similar issue and found that BizTalk Adapter pack CU3 was missing, therefore the WCF Adapter was not working correctly.

https://support.microsoft.com/en-us/help/2617150/cumulative-update-package-3-for-biztalk-adapter-pack-2010


问:
What exactly are parameters in javascript (or any programming language for that matter)
I have this piece of code that I've written and read that in order for it to work correctly I must use parameters so I did and it works perfectly, however I cant figure out for the life of me what parameters are and how they work. I read through a ton of articles all over the web but I just couldn't figure out how parameters work. How does one parameter know to grab instructions from another. The whole idea is just really frustrating. Also this is kind of a side question. Can I getElementBy Class instead of Id or is there anything similar to get getElementById() for classes? Thanks so much in advance.

Below is the code that is in the script.js file:

```<code>function setValue(field)
{
    if(''!=field.defaultValue)
    {
        if(field.value==field.defaultValue)
        {
            field.value='';
        }
        else if(''==field.value)
        {
            field.value=field.defaultValue;
        }
    }
}
</code>```

and I called this script to run with the code below:

```<code><textarea  id="info"
           class="textArea"
           name="comment"
           cols="40" rows="10"
           onfocus="setValue(this)"
           onblur="setValue(this)">
               Whats Your Name
</textarea>
</code>```

答:
Parameters

If by "parameter" you mean "argument", it's not at all clear what you mean by "How does one parameter know to grab instructions from another." Arguments/parameters don't grab "instructions" from each other.

Since it's not at all clear what you're actually asking here, I won't go into any kind of detail, but I will warn that function arguments actually work a bit differently in JavaScript than in many other languages like C, C#, or Java.

The traditional model is a special memory area called a "stack": The caller pushes arguments onto the stack, and the callee (the function being called) pulls them off the stack.

JavaScript doesn't use the stack model, though. Instead, when a function is called, an object called an execution context is allocated, and along with it something called a variable object, and the arguments (and a few other things) end up being properties on the variable object. (This happens invisibly behind the scenes, you don't actually get direct references to either object, but the fact of them is clear from edge case behaviors.)

Getting Elements by Class Name

There's getElementsByClassName which is widely-supported except by IE. But if you search for "getElementsByClassName IE" you'll find a variety of implementations for IE that you can drop into your page.

Body:
I have this piece of code that I've written and read that in order for it to work correctly I must use parameters so I did and it works perfectly, however I cant figure out for the life of me what parameters are and how they work. I read through a ton of articles all over the web but I just couldn't figure out how parameters work. How does one parameter know to grab instructions from another. The whole idea is just really frustrating. Also this is kind of a side question. Can I getElementBy Class instead of Id or is there anything similar to get getElementById() for classes? Thanks so much in advance.

Below is the code that is in the script.js file:

function setValue(field)
{
    if(''!=field.defaultValue)
    {
        if(field.value==field.defaultValue)
        {
            field.value='';
        }
        else if(''==field.value)
        {
            field.value=field.defaultValue;
        }
    }
}

and I called this script to run with the code below:

<textarea  id="info"
           class="textArea"
           name="comment"
           cols="40" rows="10"
           onfocus="setValue(this)"
           onblur="setValue(this)">
               Whats Your Name
</textarea>


问:
Button color change when untouched

<!DOCTYPE html>

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Dummy form

<form name="myForm">
<input name="myInput" ng-model="myInput" required />

<input  type="button" ng-click="deleteRow($event,name)" value="Remove" class="btn" >

<input type="button"  ng-click="deleteRow($event,name)" value="Remove" class="btn btn-primary" >
</form>

```

When the inputs are touched I'm trying the change the remove button color.I tried with if else,it was not working.So, used ng-show where I'm getting two buttons and the one button with changed color is working only when I click outside the form.Can anyone help?

答:
Here is an example of using the ng-class directive to change the class when the input is valid:

<!DOCTYPE html>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Dummy form

<form name="myForm">
  <input name="myInput" ng-model="myInput" required />

  <input  type="button" ng-click="deleteRow($event,name)"
          value="Remove" class="btn"
          ng-class="{'btn-primary': myForm.myInput.$valid}" />

</form>

```

When the input is empty, the Remove button is gray. When the input is valid the btn-primary class is added to the button, changing its color to blue.

Title: Button color change when untouched

Body:
<!DOCTYPE html>

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Dummy form

<form name="myForm">
<input name="myInput" ng-model="myInput" required />

<input  type="button" ng-click="deleteRow($event,name)" value="Remove" class="btn" >

<input type="button"  ng-click="deleteRow($event,name)" value="Remove" class="btn btn-primary" >
</form>

When the inputs are touched I'm trying the change the remove button color.I tried with if else,it was not working.So, used ng-show where I'm getting two buttons and the one button with changed color is working only when I click outside the form.Can anyone help?

Body:
Here is an example of using the ng-class directive to change the class when the input is valid:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<body ng-app="">

<p>Dummy form</p>

<form name="myForm">
  <input name="myInput" ng-model="myInput" required />

  <input  type="button" ng-click="deleteRow($event,name)"
          value="Remove" class="btn"
          ng-class="{'btn-primary': myForm.myInput.$valid}" />

</form>
</body>
</html>

When the input is empty, the Remove button is gray. When the input is valid the btn-primary class is added to the button, changing its color to blue.


问:
Laravel 4.2 Vuejs
I am working in laravel 4.2 and I want to implement Vue.js into my application. When I put some testing code in my blade it only shows error that "Use of undefined constant message - assumed 'message'"I know that laravel read {{message}} like php code but do you know any solution how to add vue.js to my blade? Thanks for help.
Here is code</p>

```<code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<script>
new Vue({
    el: '#app',
    data: {
        message: 'hello from Vue.js 2.0'
    }
})
</script>
<div id="app">
<p>{{ message }}</p>
</div>
</code>```

答:
You can add @ before print message veriable

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
    <script>
        $(document).ready(function () {
            new Vue({
                el: '#app',
                data: {
                    message: 'hello from Vue.js 2.0'
                }
            })
        });
    </script>
    <div id="app">
        <p>@{{ message }}</p>
    </div>
</code>```

Title: Laravel 4.2 Vuejs

Body:
I am working in laravel 4.2 and I want to implement Vue.js into my application. When I put some testing code in my blade it only shows error that "Use of undefined constant message - assumed 'message'"I know that laravel read {{message}} like php code but do you know any solution how to add vue.js to my blade? Thanks for help.
Here is code

{{ message }}

Body:
You can add @ before print message veriable

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
    <script>
        $(document).ready(function () {
            new Vue({
                el: '#app',
                data: {
                    message: 'hello from Vue.js 2.0'
                }
            })
        });
    </script>
    <div id="app">
        <p>@{{ message }}</p>
    </div>


问:
In AWK, is it possible to specify "ranges" of fields?
In AWK, is it possible to specify "ranges" of fields?

Example. Given a tab-separated file "foo" with 100 fields per line, I want to print only the fields 32 to 57 for each line, and save the result in a file "bar". What I do now:

```<code>awk 'BEGIN{OFS="\t"}{print $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57}' foo > bar
</code>```

The problem with this is that it is tedious to type and prone to errors.

Is there some syntactic form which allows me to say the same in a more concise and less error prone fashion (like "$32..$57") ?

答:
I use this simple function, which does not check that the field range exists in the line.</p>

```<code>function subby(f,l, s) {
  s = $f
  for(i=f+1;i<=l;i++)
    s = sprintf("%s %s",s,$i)

  return s
}
</code>```

Body:
In AWK, is it possible to specify "ranges" of fields?

Example. Given a tab-separated file "foo" with 100 fields per line, I want to print only the fields 32 to 57 for each line, and save the result in a file "bar". What I do now:

awk 'BEGIN{OFS="\t"}{print $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57}' foo > bar

The problem with this is that it is tedious to type and prone to errors.

Is there some syntactic form which allows me to say the same in a more concise and less error prone fashion (like "$32..$57") ?

Body:
I use this simple function, which does not check that the field range exists in the line.

function subby(f,l, s) {
  s = $f
  for(i=f+1;i<=l;i++)
    s = sprintf("%s %s",s,$i)

  return s
}


问:
Django ORM Cannot filter by reversed foreign key
I have a weird behaviour on my production server. When I try to filter by reversed foreign key then I receive an error that it is not possible, but locally it works fine, e.g.:

```<code>class Foo(models.Model):
    pass

class Bar(models.Model):
    name = models.CharField()
    foo = models.ForeignKey('Foo', related_name='bars', blank=True, null=True, default=None)
</code>```

Now trying to do:

```<code>Foo.objects.filter(bars__name=xyz)
</code>```

will result with

Cannot resolve keyword 'bars' into field. Choices are: ...

I use Ubuntu 16.04 and django 1.8.7

EDIT 1:
can it be related to the fact that ForeignKeys are defined using string representation?

EDIT 2:
I have found relation which is defined using class not string, so it doesn't work for such relations as well.

Basically model Foo has many ForeignKey relations. Few in Foo, few in target models. These in target models do not exist on production when running query from Foo perspective. These in Foo can be used as query params.

EDIT 3:
I have received more detailed information of server configuration and when exactly error occurs.

Info about the production setup where the issue is seen:

apache version: 2.4.18-2ubuntu3.3

libapache2-mod-wsgi version: 4.3.0-1.1build1

Apache mpm_event config:

```<code>StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</code>```

Relevant part of apache site config:

```<code>WSGIDaemonProcess some_name group=some_name maximum-requests=1000 processes=2 threads=15 user=some_name
WSGIProcessGroup some_name
WSGIScriptAlias / "/usr/lib/python2.7/dist-packages/some_name/wsgi.py"
WSGIPassAuthorization On
</code>```

Basically error does not happen with every request. When it appears then it comes from one worker. Restarting apache fixes errors for some time.

One of the thoughts is that there may be a race condition in loading django models.

答:
You haven't defined the fk properly:

```<code>class Foo(models.Model):
    pass

class Bar(models.Model):
    name = models.CharField()
    foo = models.ForeignKey(Foo, related_name='bars', blank=True, null=True, default=None)
</code>```

To deal with circular imports:

```<code>foo = models.ForeignKey('<app_name>.Foo', related_name='bars', blank=True, null=True, default=None)
</code>```

Body:
I have a weird behaviour on my production server. When I try to filter by reversed foreign key then I receive an error that it is not possible, but locally it works fine, e.g.:

class Foo(models.Model):
    pass

class Bar(models.Model):
    name = models.CharField()
    foo = models.ForeignKey('Foo', related_name='bars', blank=True, null=True, default=None)

Now trying to do:

Foo.objects.filter(bars__name=xyz)

will result with

Cannot resolve keyword 'bars' into field. Choices are: ...

I use Ubuntu 16.04 and django 1.8.7

EDIT 1:
can it be related to the fact that ForeignKeys are defined using string representation?

EDIT 2:
I have found relation which is defined using class not string, so it doesn't work for such relations as well.

Basically model Foo has many ForeignKey relations. Few in Foo, few in target models. These in target models do not exist on production when running query from Foo perspective. These in Foo can be used as query params.

EDIT 3:
I have received more detailed information of server configuration and when exactly error occurs.

Info about the production setup where the issue is seen:

apache version: 2.4.18-2ubuntu3.3

libapache2-mod-wsgi version: 4.3.0-1.1build1

Apache mpm_event config:

StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0

Relevant part of apache site config:

WSGIDaemonProcess some_name group=some_name maximum-requests=1000 processes=2 threads=15 user=some_name
WSGIProcessGroup some_name
WSGIScriptAlias / "/usr/lib/python2.7/dist-packages/some_name/wsgi.py"
WSGIPassAuthorization On

Basically error does not happen with every request. When it appears then it comes from one worker. Restarting apache fixes errors for some time.

One of the thoughts is that there may be a race condition in loading django models.

Body:
You haven't defined the fk properly:

class Foo(models.Model):
    pass

class Bar(models.Model):
    name = models.CharField()
    foo = models.ForeignKey(Foo, related_name='bars', blank=True, null=True, default=None)

To deal with circular imports:

foo = models.ForeignKey('<app_name>.Foo', related_name='bars', blank=True, null=True, default=None)


答:
When I hear the word "parameter", I usually think of references that are passed into methods for execution.  Is that what you mean?  Whether it's a function or an object method, that's usually the name that we give to the object references that are passed in.  Is that what you have in mind?

Yes, it's possible to query for a DOM element using div names, as long as you've written your page to do so.  jQuery is the library that most people are using to manipulate the DOM in an HTML page.  It has lots of methods for querying for different DOM elements.  Perhaps that is what you want.

Title: What exactly are parameters in javascript (or any programming language for that matter)


问:
Random number generation in R with multiple conditions
I have this problem below to address. Your inputs/pointers are very much appreciated.Thanks in advance!

I have a data.table called Defect. And the first column is Length

```<code>Defect Table :

Length

6355
6236
1345
3123
</code>```

I want to add two more columns called DefectStarts and DefectEnds. I would like to use random function to determine where the defect starts and where it ends.

Basic criteria is as follows:

```<code> DefectStarts and DefectEnds <= Length

 DefectEnds > DefectStarts

 DefectEnds - DefectStarts <= Length
</code>```

Final data should something like this(values could be different as long as it satisfies above conditions)

```<code> Defect table:

Length     DefectStarts     DefectEnds

6355         1234             4356

6236         2000             4567

1345         500               689

3123         342               3120
</code>```

答:
runif(n, min, max) generates n random numbers with a range from min to max. The latter two arguments can be vectors.

```<code>n <- nrow(df)
df$start <- runif(n, max=df$Length)
df$end <- runif(n, min=df$start, max=df$Length)
</code>```

Using the dplyr package:

```<code>df <- mutate(df, start=runif(n(), max=Length), end=runif(n(), min=start, max=Length))
</code>```

Body:
I have this problem below to address. Your inputs/pointers are very much appreciated.Thanks in advance!

I have a data.table called Defect. And the first column is Length

Defect Table :

Length

6355
6236
1345
3123

I want to add two more columns called DefectStarts and DefectEnds. I would like to use random function to determine where the defect starts and where it ends.

Basic criteria is as follows:

 DefectStarts and DefectEnds <= Length

 DefectEnds > DefectStarts

 DefectEnds - DefectStarts <= Length

Final data should something like this(values could be different as long as it satisfies above conditions)

 Defect table:

Length     DefectStarts     DefectEnds

6355         1234             4356

6236         2000             4567

1345         500               689

3123         342               3120

Body:
runif(n, min, max) generates n random numbers with a range from min to max. The latter two arguments can be vectors.

n <- nrow(df)
df$start <- runif(n, max=df$Length)
df$end <- runif(n, min=df$start, max=df$Length)

Using the dplyr package:

df <- mutate(df, start=runif(n(), max=Length), end=runif(n(), min=start, max=Length))


问:
Find multiple set of routes from Google API
I have the bellow API endpoint to find the route between two locations,

https://maps.googleapis.com/maps/api/directions/json?origin=Brooklyn&destination=Queens&mode=driving

This works perfectly, but I have more than one set of origin and destinations like

```<code> origin1 to destination1
 origin2 to destination2
 origin2 to destination2
 originn to destinationn
</code>```

And I need to get the route at the same time, but Google prevents the consecutive requests from the same IP after a few requests.
My question is, is there any logic or method available to find the set of routes in a single request from Google?

答:
The Google Directions API web service doesn't support multiple origins and destinations. You can only send requests for one origin and one destination and indeed you should respect the allowed queries per second (QPS) limits established in the documentation:

https://developers.google.com/maps/documentation/directions/usage-limits

There are several libraries available at GitHub that implement throttling logic to stay within allowed limits. You can find libraries for Java, Python, Go and NodeJs:

https://github.com/googlemaps/google-maps-services-python

https://github.com/googlemaps/google-maps-services-java

https://github.com/googlemaps/google-maps-services-go

https://github.com/googlemaps/google-maps-services-js

Also, I noticed that attempts to request a batch functionality for web services were rejected by Google. You can see this feature request as a reference:

https://issuetracker.google.com/issues/35818254

Body:
I have the bellow API endpoint to find the route between two locations,

https://maps.googleapis.com/maps/api/directions/json?origin=Brooklyn&destination=Queens&mode=driving

This works perfectly, but I have more than one set of origin and destinations like

 origin1 to destination1
 origin2 to destination2
 origin2 to destination2
 originn to destinationn

And I need to get the route at the same time, but Google prevents the consecutive requests from the same IP after a few requests.
My question is, is there any logic or method available to find the set of routes in a single request from Google?


问:
onActivityResult is not calling between activites
Here I have tried to pass the some value to 2nd activity(Child) to 1st activity(Parent). I have noted that in API-21 above version of device onActivityResult is called but for API-19 and below of it, it is not called. Here I share snippets of my code.Please check it.

Your answer is more appreciated!!!

In parent activity:

STEP 1

```<code>Intent intent = new Intent(ABCAct.this, DEF.class);
                intent.putExtra("mapPickDrop", "1");
                intent.putExtra("location_lat", P_latitude);
                intent.putExtra("location_lng", P_longitude);
                intent.putExtra("address", pickupAddressFlag);
                startActivityForResult(intent, 2018);
</code>```

STEP 2:

```<code>protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

  if (requestCode == 2018) {
            if (resultCode == RESULT_OK) {
                Double lat = data.getDoubleExtra("location_lat", 0.0);
                Double lng = data.getDoubleExtra("location_lng", 0.0);
                String add = data.getStringExtra("location_address");
                String mapPickDrop = data.getStringExtra("mapPickDrop");

                if (mapPickDrop.equals("1")) {
                    P_latitude = lat;
                    P_longitude = lng;
                    pickupAddressFlag = add;
                    TaxiUtil.bookTaxiPickUpDrop = 1;
                    if (P_latitude != 0.0 && P_longitude != 0.0 && D_latitude == 0.0 && D_longitude == 0.0) {
                        setLocation(P_latitude, P_longitude, "");
                    }
                }
                if (mapPickDrop.equals("2")) {
                    TaxiUtil.bookTaxiPickUpDrop = 2;
                    D_latitude = lat;
                    D_longitude = lng;
                    DroplocEdt.setText("" + add);
                    showPickupDropMarkers();
                }
            }
        }
    }
</code>```

In Child activity

```<code>   Intent back = new Intent();
            back.putExtra("location_lat", P_latitude_new);
            back.putExtra("location_lng", P_longitude_new);
            back.putExtra("location_address",         PicklocEdt_1.getText().toString());

            back.putExtra("mapPickDrop", mapPickDrop);
            setResult(RESULT_OK, back);
            finish();
</code>```

Manifest

```<code><activity
            android:name=".ABCAct"
            android:configChanges="orientation|keyboardHidden"
            android:launchMode="singleTask"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="stateHidden|stateAlwaysHidden">

     <activity
            android:name=".DEF"
            android:configChanges="orientation|keyboardHidden"
            android:launchMode="singleTask"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="stateHidden|stateAlwaysHidden" />
</code>```

答:
1:Deleting android:noHistory="true" from the activity I was having problem with solved the issue for me

2: Change if you have android:launchMode=“singleTask” to android:launchMode=“standard”

hope it helps!!!!

Body:
Here I have tried to pass the some value to 2nd activity(Child) to 1st activity(Parent). I have noted that in API-21 above version of device onActivityResult is called but for API-19 and below of it, it is not called. Here I share snippets of my code.Please check it.

Your answer is more appreciated!!!

In parent activity:

STEP 1

Intent intent = new Intent(ABCAct.this, DEF.class);
                intent.putExtra("mapPickDrop", "1");
                intent.putExtra("location_lat", P_latitude);
                intent.putExtra("location_lng", P_longitude);
                intent.putExtra("address", pickupAddressFlag);
                startActivityForResult(intent, 2018);

STEP 2:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

  if (requestCode == 2018) {
            if (resultCode == RESULT_OK) {
                Double lat = data.getDoubleExtra("location_lat", 0.0);
                Double lng = data.getDoubleExtra("location_lng", 0.0);
                String add = data.getStringExtra("location_address");
                String mapPickDrop = data.getStringExtra("mapPickDrop");

                if (mapPickDrop.equals("1")) {
                    P_latitude = lat;
                    P_longitude = lng;
                    pickupAddressFlag = add;
                    TaxiUtil.bookTaxiPickUpDrop = 1;
                    if (P_latitude != 0.0 && P_longitude != 0.0 && D_latitude == 0.0 && D_longitude == 0.0) {
                        setLocation(P_latitude, P_longitude, "");
                    }
                }
                if (mapPickDrop.equals("2")) {
                    TaxiUtil.bookTaxiPickUpDrop = 2;
                    D_latitude = lat;
                    D_longitude = lng;
                    DroplocEdt.setText("" + add);
                    showPickupDropMarkers();
                }
            }
        }
    }

In Child activity

   Intent back = new Intent();
            back.putExtra("location_lat", P_latitude_new);
            back.putExtra("location_lng", P_longitude_new);
            back.putExtra("location_address",         PicklocEdt_1.getText().toString());

            back.putExtra("mapPickDrop", mapPickDrop);
            setResult(RESULT_OK, back);
            finish();

Manifest

<activity
            android:name=".ABCAct"
            android:configChanges="orientation|keyboardHidden"
            android:launchMode="singleTask"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="stateHidden|stateAlwaysHidden">

     <activity
            android:name=".DEF"
            android:configChanges="orientation|keyboardHidden"
            android:launchMode="singleTask"
            android:screenOrientation="portrait"
            android:windowSoftInputMode="stateHidden|stateAlwaysHidden" />


问:
Avoiding an incomplete pattern match
Consider the following code:

```<code>data A
data B

f :: A -> B
f = undefined

data T = TA A | TB B
data ListT = ListTA [A] | ListTB [B]

g :: [T] -> ListT
g l =
  let
    f' :: T -> B
    f' (TA x) = f x
    f' (TB x) = x
    isA :: T -> Bool
    isA TA{} = True
    isA TB{} = False
  in
    case (all isA l) of
      True -> ListTA (map (\(TA x) -> x) l)
      False -> ListTB (map f' l)

main = pure ()
</code>```

The idea behind this is I've got a list of either As or Bs mixed together. I can convert A -> B but not the other way around. Based on this list, I want to make either a list of As or list of Bs, the former if all my original list elements are As, the latter if at least one is a B.

The above code compiles (and I'm guessing will work) but the incomplete pattern match in the map (\(TA x) -> x) l makes me just a little uncomfortable. Is such an incomplete match just a necessity of what I'm doing here? Also, am I reinventing the wheel, is there something that generalises what I'm doing here?

答:
I'd structure it like this: build two lists - one full of As and one full of Bs - with the effect that building the list of As could fail. One can build a Monoid which implements this logic and foldMap into it.

Since one could fail to build a list of As, we'll need to build this  Monoid on top of Maybe. The behaviour we want comes from Maybe's Applicative instance: if either of mappend's arguments is Nothing then the whole thing fails, otherwise we want to use mappend to combine the two results. This is a general recipe for combining an Applicative and a Monoid. Concretely:

```<code>newtype WrappedApplicative f a = Wrap { unWrap :: f a }

instance (Applicative f, Monoid m) => Monoid (WrappedApplicative f m) where
    mempty = pure mempty
    Wrap x `mappend` Wrap y = Wrap $ liftA2 mappend x y
</code>```

I don't know if this newtype is somewhere in base. It seems like the sort of thing that would be there but I couldn't find it.

Without further ado, here's the Monoid we'll be foldMapping into:

```<code>type Result = ([B], WrappedApplicative Maybe [A])
</code>```

I'm borrowing (a, b)'s Monoid instance, which delegates in parallel to a and b's Monoid instances.

```<code>getAsOrToBs :: [Either A B] -> Either [A] [B]
getAsOrToBs = fromResult . foldMap toResult
    where toResult (Left a) = ([aToB a], Wrap (Just [a]))
          toResult (Right b) = ([b], Wrap Nothing)
          fromResult (_, Wrap (Just as)) = Left as
          fromResult (bs, Wrap Nothing) = Right bs
</code>```

Alternatively, with foldr:

```<code>getAsOrToBs :: [Either A B] -> Either [A] [B]
getAsOrToBs = fromResult . foldr f ([], Just [])
    where f (Left a) (bs, mas) = (aToB a : bs, fmap (a:) mas)
          f (Right b) (bs, _) = (b:bs, Nothing)
          fromResult (_, Just as) = Left as
          fromResult (bs, Nothing) = Right bs
</code>```

Look, ma, no partial functions!

Title: Avoiding an incomplete pattern match

Body:
Consider the following code:

data A
data B

f :: A -> B
f = undefined

data T = TA A | TB B
data ListT = ListTA [A] | ListTB [B]

g :: [T] -> ListT
g l =
  let
    f' :: T -> B
    f' (TA x) = f x
    f' (TB x) = x
    isA :: T -> Bool
    isA TA{} = True
    isA TB{} = False
  in
    case (all isA l) of
      True -> ListTA (map (\(TA x) -> x) l)
      False -> ListTB (map f' l)

main = pure ()

The idea behind this is I've got a list of either As or Bs mixed together. I can convert A -> B but not the other way around. Based on this list, I want to make either a list of As or list of Bs, the former if all my original list elements are As, the latter if at least one is a B.

The above code compiles (and I'm guessing will work) but the incomplete pattern match in the map (\(TA x) -> x) l makes me just a little uncomfortable. Is such an incomplete match just a necessity of what I'm doing here? Also, am I reinventing the wheel, is there something that generalises what I'm doing here?

Body:
I'd structure it like this: build two lists - one full of As and one full of Bs - with the effect that building the list of As could fail. One can build a Monoid which implements this logic and foldMap into it.

Since one could fail to build a list of As, we'll need to build this  Monoid on top of Maybe. The behaviour we want comes from Maybe's Applicative instance: if either of mappend's arguments is Nothing then the whole thing fails, otherwise we want to use mappend to combine the two results. This is a general recipe for combining an Applicative and a Monoid. Concretely:

newtype WrappedApplicative f a = Wrap { unWrap :: f a }

instance (Applicative f, Monoid m) => Monoid (WrappedApplicative f m) where
    mempty = pure mempty
    Wrap x `mappend` Wrap y = Wrap $ liftA2 mappend x y

I don't know if this newtype is somewhere in base. It seems like the sort of thing that would be there but I couldn't find it.

Without further ado, here's the Monoid we'll be foldMapping into:

type Result = ([B], WrappedApplicative Maybe [A])

I'm borrowing (a, b)'s Monoid instance, which delegates in parallel to a and b's Monoid instances.

getAsOrToBs :: [Either A B] -> Either [A] [B]
getAsOrToBs = fromResult . foldMap toResult
    where toResult (Left a) = ([aToB a], Wrap (Just [a]))
          toResult (Right b) = ([b], Wrap Nothing)
          fromResult (_, Wrap (Just as)) = Left as
          fromResult (bs, Wrap Nothing) = Right bs

Alternatively, with foldr:

getAsOrToBs :: [Either A B] -> Either [A] [B]
getAsOrToBs = fromResult . foldr f ([], Just [])
    where f (Left a) (bs, mas) = (aToB a : bs, fmap (a:) mas)
          f (Right b) (bs, _) = (b:bs, Nothing)
          fromResult (_, Just as) = Left as
          fromResult (bs, Nothing) = Right bs

Look, ma, no partial functions!


问:
Aggregation Strategy based on message size of aggregate
I would like to aggregate exchanges, and when then exchange hits a certain size (say 20KB) I would like to mark the exchange as closed.

I have a rudimentary implementation that checks size of the exchange and if it is 18KB I return true from my predicate.  However, if a messages comes in that is 4KB and it is currently 17KB that will mean I will complete the aggregation when it is 21KB which is too big.

Any ideas on how to solve this?  Can I do something in the aggregation strategy to reject the join and start a new Exchange to aggregate on?

I figured I could put it through another process to check actual size remove messages off the end of the message to fit the size, and for each removed message, push them back through...but that seems a little ugly because I have a constantly compensating routine that would likely execute.

Thanks in advance for any tips.

答:
I think there is an eager complete option you can use to mark it as complete when you have that 17 + 4 > 20 situation. Then it will complete the 17, and start a new group with the 4.

See the docs at: https://github.com/apache/camel/blob/master/camel-core/src/main/docs/eips/aggregate-eip.adoc

And you would also likely need to use `PreCompleteAggregationStrategy' and return true in that 17 + 4 > 20 situation, as otherwise it would group them together first and complete, eg so it becomes 21. But by using both the eager completion check option and this interface you can do as you want.

https://github.com/apache/camel/blob/master/camel-core/src/main/java/org/apache/camel/processor/aggregate/PreCompletionAwareAggregationStrategy.java


问:
Show the three lines at navigation drawer
I recently updated my app to use navigation drawer in 2 activities (instead of only one, as it used to be). For this, made an DrawerActivity parent class, and I extend this class on the two activities I want to use it on. The problem is, instead of showing the three lines symbol, it shows the back arrow symbol. Previously, when I used only in the main activity the navigation drawer, it was shown as it should (with the three lines), like this:

Here's the code that I use for this:

```<code>drawerListener = new ActionBarDrawerToggle(this, drawerLayout,
            R.drawable.ic_navigation_drawer, R.string.navigation_drawer_open,
            R.string.navigation_drawer_close) {
        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
        }

        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
        }
    }
    getActionBar().setHomeButtonEnabled(true);
    getActionBar().setDisplayHomeAsUpEnabled(true);
</code>```

Any ideas why it shows the back button, instead of the three lines ? Thank you.

答:
In my case, removing the line actionBarDrawerToggle.setDrawerIndicatorEnabled(false); worked and replaced the back arrow with three lines again.

setDrawerIndicatorEnabled is true by default. By mistake, I had made it false.

Body:
I recently updated my app to use navigation drawer in 2 activities (instead of only one, as it used to be). For this, made an DrawerActivity parent class, and I extend this class on the two activities I want to use it on. The problem is, instead of showing the three lines symbol, it shows the back arrow symbol. Previously, when I used only in the main activity the navigation drawer, it was shown as it should (with the three lines), like this:

Here's the code that I use for this:

drawerListener = new ActionBarDrawerToggle(this, drawerLayout,
            R.drawable.ic_navigation_drawer, R.string.navigation_drawer_open,
            R.string.navigation_drawer_close) {
        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
        }

        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
        }
    }
    getActionBar().setHomeButtonEnabled(true);
    getActionBar().setDisplayHomeAsUpEnabled(true);

Any ideas why it shows the back button, instead of the three lines ? Thank you.


问:
Run-Jetty-Run (RJR) with Jetty 8 and Servlet 3.0 scanns all JAR files ignoring WebInfIncludeJarPattern in jetty-web.xml
I'm using Servlet 3.0 without any web.xml just using Spring WebApplicationInitializer. When I start the Webapplication with Run-Jetty-Run in eclipse, the JARScanning takes about 40 seconds since it tries to find HandlesTypes annotations in all jars.

Thus, I tried to set the WebInfIncludeJarPattern in the jetty-web.xml (I also tried jetty-context.xml) and put it in the webapp/WEB-INF folder as described in http://wiki.eclipse.org/Jetty/Howto/Avoid_slow_deployment. I also set metadata-complete="true". The content of the jetty-web.xml file is:

```<code><Configure class="org.eclipse.jetty.webapp.WebAppContext">
    <Call name="setAttribute">
      <Arg>org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern</Arg>
      <Arg>.*/.*foo-api-[^/]\.jar$|./.*bar-[^/]\.jar$|./.*wibble[^/]*\.jar$</Arg>
    </Call>
</Configure>
</code>```

However, the JarScanner still scans all the JAR files. In the debug output I can see, that the jetty-web.xml file is parsed AFTER all the JARScanning is done:

OUTPUT:

```<code>2013-08-30 09:09:52.836:DBUG:oejw.WebAppContext:preConfigure o.e.j.w.WebAppContext{/admin2,[file:/C:/....../src/main/webapp/]} with runjettyrun.webapp.RJRWebInfConfiguration@1cdc4a5
......
2013-08-30 09:09:52.979:DBUG:oejw.WebAppContext:preConfigure o.e.j.w.WebAppContext{/admin2,[file:/C:/..../src/main/webapp/]} with org.eclipse.jetty.webapp.WebXmlConfiguration@136f39e
2013-08-30 09:09:53.076:DBUG:oejw.WebDescriptor:file:/C:/......../src/main/webapp/WEB-INF/web.xml: Calculated metadatacomplete = True with version=3.0
2013-08-30 09:09:53.076:DBUG:oejw.WebAppContext:preConfigure o.e.j.w.WebAppContext{/admin2,[file:/C:/....../src/main/webapp/]} with runjettyrun.webapp.RJRMetaInfoConfiguration@164de63
... <LOTS OF JARSCANNING>
2013-08-30 09:10:36.677:DBUG:oejw.JarScanner:Search of file:/C:/......./httpclient-cache-4.1.2.jar
2013-08-30 09:10:36.710:DBUG:oejw.WebAppContext:configure o.e.j.w.WebAppContext{/.................} with org.eclipse.jetty.webapp.JettyWebXmlConfiguration@803365
2013-08-30 09:10:36.711:DBUG:oejw.JettyWebXmlConfiguration:Configuring web-jetty.xml
2013-08-30 09:10:36.715:DBUG:oejw.JettyWebXmlConfiguration:Configure: file:/C:/......./src/main/webapp/WEB-INF/jetty-web.xml
</code>```

How can I force RJR to pick up the jetty-web.xml earlier and only scan the files specified in there? Or is there any other way in RJR to specify the JARS to be scanned?

I am using following versions: Eclipse: Kepler Release 4.3 Build id: 20130614-0229 RJR:  1.3.3.201301020723  Jetty: 8.1.8.v20121106

WINDOWS: 64 bit

Thank you

答:
Looking through the RJR source code I came across this undocumented flag rjrDisableannotation which speeds up the startup time significantly in all Jetty 8/9/9.3.6 (so far I haven't noticed any unwanted side effects - of course as its name suggests it doesn't scan for annotations anymore).

It can be enabled as a "VM argument" in the "Run/Debug configuration" for a "Jetty Webapp".

e.g.:

```<code>-DrjrDisableannotation=true
</code>```

Here the related source code for reference:

https://github.com/xzer/run-jetty-run/blob/rjr1.3.4/Jetty8Support/plugin-jetty8/bootstrap/runjettyrun/Configs.java#L210-L212

Body:
I'm using Servlet 3.0 without any web.xml just using Spring WebApplicationInitializer. When I start the Webapplication with Run-Jetty-Run in eclipse, the JARScanning takes about 40 seconds since it tries to find HandlesTypes annotations in all jars.

Thus, I tried to set the WebInfIncludeJarPattern in the jetty-web.xml (I also tried jetty-context.xml) and put it in the webapp/WEB-INF folder as described in http://wiki.eclipse.org/Jetty/Howto/Avoid_slow_deployment. I also set metadata-complete="true". The content of the jetty-web.xml file is:

<Configure class="org.eclipse.jetty.webapp.WebAppContext">
    <Call name="setAttribute">
      <Arg>org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern</Arg>
      <Arg>.*/.*foo-api-[^/]\.jar$|./.*bar-[^/]\.jar$|./.*wibble[^/]*\.jar$</Arg>
    </Call>
</Configure>

However, the JarScanner still scans all the JAR files. In the debug output I can see, that the jetty-web.xml file is parsed AFTER all the JARScanning is done:

OUTPUT:

2013-08-30 09:09:52.836:DBUG:oejw.WebAppContext:preConfigure o.e.j.w.WebAppContext{/admin2,[file:/C:/....../src/main/webapp/]} with runjettyrun.webapp.RJRWebInfConfiguration@1cdc4a5
......
2013-08-30 09:09:52.979:DBUG:oejw.WebAppContext:preConfigure o.e.j.w.WebAppContext{/admin2,[file:/C:/..../src/main/webapp/]} with org.eclipse.jetty.webapp.WebXmlConfiguration@136f39e
2013-08-30 09:09:53.076:DBUG:oejw.WebDescriptor:file:/C:/......../src/main/webapp/WEB-INF/web.xml: Calculated metadatacomplete = True with version=3.0
2013-08-30 09:09:53.076:DBUG:oejw.WebAppContext:preConfigure o.e.j.w.WebAppContext{/admin2,[file:/C:/....../src/main/webapp/]} with runjettyrun.webapp.RJRMetaInfoConfiguration@164de63
... <LOTS OF JARSCANNING>
2013-08-30 09:10:36.677:DBUG:oejw.JarScanner:Search of file:/C:/......./httpclient-cache-4.1.2.jar
2013-08-30 09:10:36.710:DBUG:oejw.WebAppContext:configure o.e.j.w.WebAppContext{/.................} with org.eclipse.jetty.webapp.JettyWebXmlConfiguration@803365
2013-08-30 09:10:36.711:DBUG:oejw.JettyWebXmlConfiguration:Configuring web-jetty.xml
2013-08-30 09:10:36.715:DBUG:oejw.JettyWebXmlConfiguration:Configure: file:/C:/......./src/main/webapp/WEB-INF/jetty-web.xml

How can I force RJR to pick up the jetty-web.xml earlier and only scan the files specified in there? Or is there any other way in RJR to specify the JARS to be scanned?

I am using following versions: Eclipse: Kepler Release 4.3 Build id: 20130614-0229 RJR:  1.3.3.201301020723  Jetty: 8.1.8.v20121106

WINDOWS: 64 bit

Thank you

Body:
Looking through the RJR source code I came across this undocumented flag rjrDisableannotation which speeds up the startup time significantly in all Jetty 8/9/9.3.6 (so far I haven't noticed any unwanted side effects - of course as its name suggests it doesn't scan for annotations anymore).

It can be enabled as a "VM argument" in the "Run/Debug configuration" for a "Jetty Webapp".

e.g.:

-DrjrDisableannotation=true

Here the related source code for reference:

https://github.com/xzer/run-jetty-run/blob/rjr1.3.4/Jetty8Support/plugin-jetty8/bootstrap/runjettyrun/Configs.java#L210-L212


问:
Using Do/Catch in Swift
I am working on an app and want to get data back from a function. However sometimes data is missing or is different from the kind of that I want to retrieve. I am new to Swift and I can't find a way to write a function that does a little bit of processing and returns this data. When this data is missing, the function should give back a string "Not Found". Like this:

```<code>func processData(data:String) {
    do {
        //processing
        var result = processedData
    } catch {
        var result = "Not Found"
    }

    return result
}
</code>```

It would be very nice if somebody could help me.

答:
The most concise way of doing it would be using the guard-let construct:

```<code>func processData(data: String?) -> String {
    // Assuming getProcessedData(:) returns your processed data
    guard let result = getProcessedData(data) else {
        return "Not found"
    }
    return result
}
</code>```

Also, your function is missing a return type. You must specify the return type like -> TYPE in all functions that return some value.

Title: Using Do/Catch in Swift

Body:
I am working on an app and want to get data back from a function. However sometimes data is missing or is different from the kind of that I want to retrieve. I am new to Swift and I can't find a way to write a function that does a little bit of processing and returns this data. When this data is missing, the function should give back a string "Not Found". Like this:

func processData(data:String) {
    do {
        //processing
        var result = processedData
    } catch {
        var result = "Not Found"
    }

    return result
}

It would be very nice if somebody could help me.

Body:
The most concise way of doing it would be using the guard-let construct:

func processData(data: String?) -> String {
    // Assuming getProcessedData(:) returns your processed data
    guard let result = getProcessedData(data) else {
        return "Not found"
    }
    return result
}

Also, your function is missing a return type. You must specify the return type like -> TYPE in all functions that return some value.


问:
how to check if any subarray doesn't contain an item from other subarray? Ruby
I have an array

```<code>animals = [
  [{"name" => "Alex", "spices" => "dog", "vname" => "colour", "value" => "black"},
   {"name" => "Alf", "spices" => "dog", "vname" => "colour", "value" => "white"},
   {"name" => "Sonia", "spices" => "dog", "vname" => "colour", "value" => "white"}],

  [{"name" => "Alex", "spices" => "dog", "vname" => "health", "value" => "80"},
   {"name" => "Alf", "spices" => "dog", "vname" => "health", "value" => "98"}],

  [{"name" => "Alex", "spices" => "dog", "vname" => "age", "value" => "12"}]
]
</code>```

Every animal (Alex, Alf and Sonia) is described by colour, health and age (vname values), but Alf does not have his hash with age in third subarray and Sonia does not have her hashes with health (second subarray) and age (third subarray). I want to check if any subarray does not have "vname" pair for some dog and if doesn't to add hash like this

```<code>{"name" => "Alf", "spices" => "dog", "vname" => "age", "value" => "unknown"}
</code>```

to get an array

```<code>animals = [
 [{"name" => "Alex", "spices" => "dog", "vname" => "colour", "value" => "black"},
  {"name" => "Alf", "spices" => "dog", "vname" => "colour", "value" => "white"},
  {"name" => "Sonia", "spices" => "dog", "vname" => "colour", "value" => "white"}],

 [{"name" => "Alex", "spices" => "dog", "vname" => "health", "value" => "80"},
  {"name" => "Alf", "spices" => "dog", "vname" => "health", "value" => "98"},
  {"name" => "Sonia", "spices" => "dog", "vname" => "health", "value" => "unknown"}],

 [{"name" => "Alex", "spices" => "dog", "vname" => "age", "value" => "12"},
  {"name" => "Alf", "spices" => "dog", "vname" => "age", "value" => "unknown"},
  {"name" => "Sonia", "spices" => "dog", "vname" => "age", "value" => "unknown"}]
]
</code>```

Can You help me with this?

答:
Your data format is very hard to work with.

You could define an Animal class, keep an Animal.all hash and write your data in this structure:

```<code>data = [
  [{ 'name' => 'Alex', 'spices' => 'dog', 'vname' => 'colour', 'value' => 'black' },
   { 'name' => 'Alf', 'spices' => 'dog', 'vname' => 'colour', 'value' => 'white' },
   { 'name' => 'Sonia', 'spices' => 'dog', 'vname' => 'colour', 'value' => 'white' }],

  [{ 'name' => 'Alex', 'spices' => 'dog', 'vname' => 'health', 'value' => '80' },
   { 'name' => 'Alf', 'spices' => 'dog', 'vname' => 'health', 'value' => '98' }],

  [{ 'name' => 'Alex', 'spices' => 'dog', 'vname' => 'age', 'value' => '12' }]
]

class Animal
  attr_accessor :name, :species, :health, :age, :colour
  @all = {}

  class << self
    attr_reader :all

    def find_or_create_by_name(params)
      all[params['name']] ||= Animal.new(params)
    end
  end

  def initialize(params)
    @name = params['name']
    @species = params['spices']
  end

  def to_h
    {
      name: name,
      species: species,
      age: age || 'unknown',
      colour: colour || 'unknown',
      health: health || 'unknown'
    }
  end

  def to_s
    to_h.to_s
  end

  alias inspect to_s
end

data.each do |info|
  info.each do |params|
    animal = Animal.find_or_create_by_name(params)
    animal.instance_variable_set("@#{params['vname']}", params['value'])
  end
end

require 'pp'
pp Animal.all
# {"Alex"=>
#   {:name=>"Alex", :species=>"dog", :age=>"12", :colour=>"black", :health=>"80"},
#  "Alf"=>
#   {:name=>"Alf", :species=>"dog", :age=>"unknown", :colour=>"white", :health=>"98"},
#  "Sonia"=>
#   {:name=>"Sonia", :species=>"dog", :age=>"unknown", :colour=>"white", :health=>"unknown"}}
</code>```

Body:
I have an array

animals = [
  [{"name" => "Alex", "spices" => "dog", "vname" => "colour", "value" => "black"},
   {"name" => "Alf", "spices" => "dog", "vname" => "colour", "value" => "white"},
   {"name" => "Sonia", "spices" => "dog", "vname" => "colour", "value" => "white"}],

  [{"name" => "Alex", "spices" => "dog", "vname" => "health", "value" => "80"},
   {"name" => "Alf", "spices" => "dog", "vname" => "health", "value" => "98"}],

  [{"name" => "Alex", "spices" => "dog", "vname" => "age", "value" => "12"}]
]

Every animal (Alex, Alf and Sonia) is described by colour, health and age (vname values), but Alf does not have his hash with age in third subarray and Sonia does not have her hashes with health (second subarray) and age (third subarray). I want to check if any subarray does not have "vname" pair for some dog and if doesn't to add hash like this

{"name" => "Alf", "spices" => "dog", "vname" => "age", "value" => "unknown"}

to get an array

animals = [
 [{"name" => "Alex", "spices" => "dog", "vname" => "colour", "value" => "black"},
  {"name" => "Alf", "spices" => "dog", "vname" => "colour", "value" => "white"},
  {"name" => "Sonia", "spices" => "dog", "vname" => "colour", "value" => "white"}],

 [{"name" => "Alex", "spices" => "dog", "vname" => "health", "value" => "80"},
  {"name" => "Alf", "spices" => "dog", "vname" => "health", "value" => "98"},
  {"name" => "Sonia", "spices" => "dog", "vname" => "health", "value" => "unknown"}],

 [{"name" => "Alex", "spices" => "dog", "vname" => "age", "value" => "12"},
  {"name" => "Alf", "spices" => "dog", "vname" => "age", "value" => "unknown"},
  {"name" => "Sonia", "spices" => "dog", "vname" => "age", "value" => "unknown"}]
]

Can You help me with this?

Body:
Your data format is very hard to work with.

You could define an Animal class, keep an Animal.all hash and write your data in this structure:

data = [
  [{ 'name' => 'Alex', 'spices' => 'dog', 'vname' => 'colour', 'value' => 'black' },
   { 'name' => 'Alf', 'spices' => 'dog', 'vname' => 'colour', 'value' => 'white' },
   { 'name' => 'Sonia', 'spices' => 'dog', 'vname' => 'colour', 'value' => 'white' }],

  [{ 'name' => 'Alex', 'spices' => 'dog', 'vname' => 'health', 'value' => '80' },
   { 'name' => 'Alf', 'spices' => 'dog', 'vname' => 'health', 'value' => '98' }],

  [{ 'name' => 'Alex', 'spices' => 'dog', 'vname' => 'age', 'value' => '12' }]
]

class Animal
  attr_accessor :name, :species, :health, :age, :colour
  @all = {}

  class << self
    attr_reader :all

    def find_or_create_by_name(params)
      all[params['name']] ||= Animal.new(params)
    end
  end

  def initialize(params)
    @name = params['name']
    @species = params['spices']
  end

  def to_h
    {
      name: name,
      species: species,
      age: age || 'unknown',
      colour: colour || 'unknown',
      health: health || 'unknown'
    }
  end

  def to_s
    to_h.to_s
  end

  alias inspect to_s
end

data.each do |info|
  info.each do |params|
    animal = Animal.find_or_create_by_name(params)
    animal.instance_variable_set("@#{params['vname']}", params['value'])
  end
end

require 'pp'
pp Animal.all
# {"Alex"=>
#   {:name=>"Alex", :species=>"dog", :age=>"12", :colour=>"black", :health=>"80"},
#  "Alf"=>
#   {:name=>"Alf", :species=>"dog", :age=>"unknown", :colour=>"white", :health=>"98"},
#  "Sonia"=>
#   {:name=>"Sonia", :species=>"dog", :age=>"unknown", :colour=>"white", :health=>"unknown"}}


问:
use command:ionic cordova build android --prod --release;failed and The ionic3 app starts too long and fails
I hava two question:

Use the command：ionic cordova build android --prod --release. Failed
like this:

build failed.

The ionic3 app starts too long and fails

答:
the answer for second question is,
The APK that you installed is not the output of

```<code>ionic cordova build android --prod --release
</code>```

or any build command

its the output of

```<code>ionic cordova run android -l -c
</code>```

(run APK works when the server is 'on' from the computer).

Body:
the answer for second question is,
The APK that you installed is not the output of

ionic cordova build android --prod --release

or any build command

its the output of

ionic cordova run android -l -c

(run APK works when the server is 'on' from the computer).


问:
Dump keystore content: Permission denied keytool java_cacerts
I am trying to get a dump of my Java keystore content, I am trying with the following query in terminal:

keytool -list -v -keystore /Library/Java/JavaVirtualMachines/jdk1.8.0_92.jdk/Contents/Home/jre/lib/security/cacerts > java_cacerts.txt

it throws the following error:

-bash: java_cacerts.txt: Permission denied

I already tried changing permissions on several folders also on the cacerts file itself but without any results.

What could be the problem?

答:
I've run recently into a similar problem.

If you run the same command with Administrator rights, you'll be able to generate the file without problems.


问:
Php - check if string is not empty or has a first character not equal to
How can I check in php if the string is empty or has a first character not equal to something.
If I do this to an empty string $key = '':

```<code>if ($key != '' || $key[0] != '_')
</code>```

I get:

Uninitialized string offset: 0

答:
isset for not having offset[0]

```<code>if ($key != '' || (isset($key[0]) && $key[0] != '_' )) {
   echo "First Character not equal with _";
}
</code>```

Body:
How can I check in php if the string is empty or has a first character not equal to something.
If I do this to an empty string $key = '':

if ($key != '' || $key[0] != '_')

I get:

Uninitialized string offset: 0

Body:
isset for not having offset[0]

if ($key != '' || (isset($key[0]) && $key[0] != '_' )) {
   echo "First Character not equal with _";
}


问:
text with input in one row
I have div with input field and text

Here is code

.form-control {
    display: block;
    width: 100%;
    height: 34px;
    position: relative;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.42857143;
    color: #555;
    margin: 0 auto;
    background-color: #fff;
    border-color: #1f66b4;
    border-style: solid;
    border-width: 3px;
    background-image: none;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
    -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
    transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="width:50%;height:100%;float: left;padding-left:20%">
            <form style="text-align:center;">
                <b>dfsdfsdfsdf</b>
                <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="margin: 30px auto 0;border-radius:50px;border-width: 1px;">
            </form>
        </div></code>```

But text is over input.

I need to make text in one row with input.
How I can do this?

答:
You can add padding for the placeholder but browser support requires prefixes.

::-webkit-input-placeholder { /* Chrome/Opera/Safari */
  padding-left: .3em;
}
::-moz-placeholder { /* Firefox 19+ */
  padding-left: .3em;
}
:-ms-input-placeholder { /* IE 10+ */
  padding-left: .3em;
}
:-moz-placeholder { /* Firefox 18- */
  padding-left: .3em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="width:50%;height:100%;float: left;padding-left:20%">
  <form style="text-align:center;">
    <b>dfsdfsdfsdf</b>
    <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="margin: 30px auto 0;border-radius:50px;border-width: 1px;">
  </form>
</div></code>```

Title: text with input in one row

Body:
I have div with input field and text

Here is code

.form-control {
    display: block;
    width: 100%;
    height: 34px;
    position: relative;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.42857143;
    color: #555;
    margin: 0 auto;
    background-color: #fff;
    border-color: #1f66b4;
    border-style: solid;
    border-width: 3px;
    background-image: none;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
    -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
    transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}

            <form style="text-align:center;">
                dfsdfsdfsdf
                <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="margin: 30px auto 0;border-radius:50px;border-width: 1px;">
            </form>

But text is over input.

I need to make text in one row with input.
How I can do this?

Body:
You can add padding for the placeholder but browser support requires prefixes.

::-webkit-input-placeholder { /* Chrome/Opera/Safari */
  padding-left: .3em;
}
::-moz-placeholder { /* Firefox 19+ */
  padding-left: .3em;
}
:-ms-input-placeholder { /* IE 10+ */
  padding-left: .3em;
}
:-moz-placeholder { /* Firefox 18- */
  padding-left: .3em;
}

<div style="width:50%;height:100%;float: left;padding-left:20%">
  <form style="text-align:center;">
    <b>dfsdfsdfsdf</b>
    <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="margin: 30px auto 0;border-radius:50px;border-width: 1px;">
  </form>
</div>


问:
Hash table of templated functor
I want to create a hastable to member templated functor, I explain.
Here is my exemple which does'nt work:

```<code>#include <iostream>
#include <unordered_map>

using namespace std;
class MyFirstClass
{
    int i_;

public:
    MyFirstClass(): i_(0) {}

    void setI(int i) { i_ = i; }
    int getI() { return i_; }
};

class MySecondClass
{
    bool b_;

public:

    MySecondClass(): b_(0) {}

    void setB(bool b) { b_ = b; }
    bool getB() { return b_; }
};

template<class X, void (X::*p)()>
class MyFunctor
{
    X& _x;
public:
    MyFunctor(X& x) : _x( x ) {}
    void operator()() const { (_x.*p)(); }
};

int main(int argc, char *argv[])
{
    unordered_map<string,MyFunctor> myHashTable;

    MyFirstClass first;
    MyFirstClass second;

    myHashTable["int"] = first::setI;
    myHashTable["bool"] = second::setB;

    //
    string key = "bool";
    int value = 1;

    myHashTable[key](value);

    return 0;
}
</code>```

I have multiple class with their own setter . I would like to be able thanks to the has table and a command {string,int} change the value of the corresponding class.

The previous code is not working for the moment and I am stuck.

答:
There are a few problems with your code, as it stands.

Firstly, from your example unordered_map<string,MyFunctor> doesn't name a type, because MyFunctor doesn't name a type. You could create a non-template base class with a virtual operator(), and then have MyFunctor inherit from it.

Second, you aren't using compatible method pointers, MyFirstClass::setI and MySecondClass::setB both take a parameter.

Third, related to the first, you have to specify the template parameters when constructing an object from a class template. (until c++17's class template deduction guides). You also have ungrammatical syntax that I assume is trying to specify the object argument to the MyFunctor constructor alongside the method-pointer template argument.

You would have something like

```<code>class MyFunctorBase {
    virtual void operator()(void * i) const = 0;
}

template<class T, class X, void (X::*p)(T)>
class MyFunctor : public MyFunctorBase
{
    X& _x;
public:
    MyFunctor(X& x) : _x( x ) {}
    void operator()(void * i) const override { (_x.*p)(*static_cast<T*>(i)); }
};

int main(int argc, char *argv[])
{
    unordered_map<string,shared_ptr<MyFunctorBase>> myHashTable;

    MyFirstClass first;
    MyFirstClass second;

    myHashTable["int"] = make_shared<MyFunctor<int, MyFirstClass, &MyFirstClass::setI>>(first);
    myHashTable["bool"] = make_shared<MyFunctor<bool, MySecondClass, &MySecondClass::setB>>(second);

    //
    string key = "bool";
    bool value = true;

    (*myHashTable[key])(static_cast<void *>(&value));

    return 0;
}
</code>```

Or, much more easily, use the existing std::function, which does that for you

```<code>int main(int argc, char *argv[])
{
    unordered_map<string,function<void(void *)>> myHashTable;

    MyFirstClass first;
    MyFirstClass second;

    myHashTable["int"] = [first](void * i) { first.setI(*static_cast<int *>(i)); };
    myHashTable["bool"] = [second](void * i) { second.setB(*static_cast<bool *>(i)); };

    //
    string key = "bool";
    bool value = true;

    myHashTable[key](static_cast<void *>(&value));

    return 0;
}
</code>```

Title: Hash table of templated functor

Body:
I want to create a hastable to member templated functor, I explain.
Here is my exemple which does'nt work:

#include <iostream>
#include <unordered_map>

using namespace std;
class MyFirstClass
{
    int i_;

public:
    MyFirstClass(): i_(0) {}

    void setI(int i) { i_ = i; }
    int getI() { return i_; }
};

class MySecondClass
{
    bool b_;

public:

    MySecondClass(): b_(0) {}

    void setB(bool b) { b_ = b; }
    bool getB() { return b_; }
};

template<class X, void (X::*p)()>
class MyFunctor
{
    X& _x;
public:
    MyFunctor(X& x) : _x( x ) {}
    void operator()() const { (_x.*p)(); }
};

int main(int argc, char *argv[])
{
    unordered_map<string,MyFunctor> myHashTable;

    MyFirstClass first;
    MyFirstClass second;

    myHashTable["int"] = first::setI;
    myHashTable["bool"] = second::setB;

    //
    string key = "bool";
    int value = 1;

    myHashTable[key](value);

    return 0;
}

I have multiple class with their own setter . I would like to be able thanks to the has table and a command {string,int} change the value of the corresponding class.

The previous code is not working for the moment and I am stuck.

Body:
There are a few problems with your code, as it stands.

Firstly, from your example unordered_map<string,MyFunctor> doesn't name a type, because MyFunctor doesn't name a type. You could create a non-template base class with a virtual operator(), and then have MyFunctor inherit from it.

Second, you aren't using compatible method pointers, MyFirstClass::setI and MySecondClass::setB both take a parameter.

Third, related to the first, you have to specify the template parameters when constructing an object from a class template. (until c++17's class template deduction guides). You also have ungrammatical syntax that I assume is trying to specify the object argument to the MyFunctor constructor alongside the method-pointer template argument.

You would have something like

class MyFunctorBase {
    virtual void operator()(void * i) const = 0;
}

template<class T, class X, void (X::*p)(T)>
class MyFunctor : public MyFunctorBase
{
    X& _x;
public:
    MyFunctor(X& x) : _x( x ) {}
    void operator()(void * i) const override { (_x.*p)(*static_cast<T*>(i)); }
};

int main(int argc, char *argv[])
{
    unordered_map<string,shared_ptr<MyFunctorBase>> myHashTable;

    MyFirstClass first;
    MyFirstClass second;

    myHashTable["int"] = make_shared<MyFunctor<int, MyFirstClass, &MyFirstClass::setI>>(first);
    myHashTable["bool"] = make_shared<MyFunctor<bool, MySecondClass, &MySecondClass::setB>>(second);

    //
    string key = "bool";
    bool value = true;

    (*myHashTable[key])(static_cast<void *>(&value));

    return 0;
}

Or, much more easily, use the existing std::function, which does that for you

int main(int argc, char *argv[])
{
    unordered_map<string,function<void(void *)>> myHashTable;

    MyFirstClass first;
    MyFirstClass second;

    myHashTable["int"] = [first](void * i) { first.setI(*static_cast<int *>(i)); };
    myHashTable["bool"] = [second](void * i) { second.setB(*static_cast<bool *>(i)); };

    //
    string key = "bool";
    bool value = true;

    myHashTable[key](static_cast<void *>(&value));

    return 0;
}


问:
Newbie SQL error; missing expression
Newbie to sql here

I am attempting return sa_id from the query below but I am getting a 'missing expression' error.

```<code>select s.sa_id
    from cisadm.ci_sa s
    where s.sa_status_flg = '20'
    and s.sa_type_cd = 'LEURIBIL'
    and s.sa_id in {
      select *
      from cisadm.ci_intv_pf pf
      where pf.intv_pf_typ_cd = 'SMPCHGRI'}
    ;
</code>```

The sa_id exists in both tables; ci_sa and ci_intv_pf.

I need the sa_id to have a intv_pf_typ_cd of 'SMPCHGRI' in the ci_intv_pf table.
And I need the matching sa_id to have an sa_type_cd of 'LEURIBIL' from the ci_sa table.

Have tried ending the query with group by and having but not having any luck.

Any help much appreciated

答:
Just return the sa_id in the inner SQL:</p>

```<code>select s.sa_id
    from cisadm.ci_sa s
    where s.sa_status_flg = '20'
    and s.sa_type_cd = 'LEURIBIL'
    and s.sa_id in (
      select pf.sa_id
      from cisadm.ci_intv_pf pf
      where pf.intv_pf_typ_cd = 'SMPCHGRI')
    ;
</code>```

Title: Newbie SQL error; missing expression

Body:
Newbie to sql here

I am attempting return sa_id from the query below but I am getting a 'missing expression' error.

select s.sa_id
    from cisadm.ci_sa s
    where s.sa_status_flg = '20'
    and s.sa_type_cd = 'LEURIBIL'
    and s.sa_id in {
      select *
      from cisadm.ci_intv_pf pf
      where pf.intv_pf_typ_cd = 'SMPCHGRI'}
    ;

The sa_id exists in both tables; ci_sa and ci_intv_pf.

I need the sa_id to have a intv_pf_typ_cd of 'SMPCHGRI' in the ci_intv_pf table.
And I need the matching sa_id to have an sa_type_cd of 'LEURIBIL' from the ci_sa table.

Have tried ending the query with group by and having but not having any luck.

Any help much appreciated

Body:
Just return the sa_id in the inner SQL:

select s.sa_id
    from cisadm.ci_sa s
    where s.sa_status_flg = '20'
    and s.sa_type_cd = 'LEURIBIL'
    and s.sa_id in (
      select pf.sa_id
      from cisadm.ci_intv_pf pf
      where pf.intv_pf_typ_cd = 'SMPCHGRI')
    ;


问:
Requesting parameters are not sent over API in ionic 2
I am trying to send the the parameters using a post request but the parameters are not reaching to provide back the desired result and printing null as a result in console. here is my code

 var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded' );
    let options = new RequestOptions({ headers: headers });

    let postParams = {
      acesscode: 'XXXXXXXXXXX',
      productCode:'XXXXXXXXXX'
    };

    this.http.post("http://www.ebiebook.com/drmapi/v1/details", JSON.stringify(postParams), options)
      .subscribe(data => {
        console.log(data['_body']);
       }, error => {
        console.log(error);// Error getting the data
      });

}```

and the output screen is attached, It shows API is hitting well but the parameters data is unable to reach to provide the corresponding result. Please suggest.

答:
This print you have attached does not show what is being sent by the request, instead it shows only the response your browser received from the server.

You better take a look at this thread here to see in this thread more about. You have to check the 'Headers' tab from Chrome's console -> Network.

Body:
I am trying to send the the parameters using a post request but the parameters are not reaching to provide back the desired result and printing null as a result in console. here is my code

 var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded' );
    let options = new RequestOptions({ headers: headers });

    let postParams = {
      acesscode: 'XXXXXXXXXXX',
      productCode:'XXXXXXXXXX'
    };

    this.http.post("http://www.ebiebook.com/drmapi/v1/details", JSON.stringify(postParams), options)
      .subscribe(data => {
        console.log(data['_body']);
       }, error => {
        console.log(error);// Error getting the data
      });

}

and the output screen is attached, It shows API is hitting well but the parameters data is unable to reach to provide the corresponding result. Please suggest.