问:
Unable to download application in device with ios 11
I have build my application two years ago but not submitted on App Store. Now I want to submit the app on App store. But when I try to install app using Xcode or through diawi link of its Ad hoc build, app is not installing on device.

When I try to install app through Xcode, sometimes it shows

this application does not support this device's cpu type

and sometimes

Could not write to the device

and when I try to install app through diawi link of its Ad hoc build, it shows

Unable to download application, <app-name> could not be installed at this time

This issue is only occurring in device with ios 11. I have checked my certificates as well as UDID of device in which i am trying to install. Also I have set Architectures of Build Setting of Xcode to Standard architectures (arm7, arm64) - $(ARCHS_STANDARD).  It is completely working fine in device with iOS version below 11.

答:
Finally I have find the solution of my issue. In my case I have to remove some old libraries which is not supporting in ios 11 and have to change some deprecated code.

If your code is deprecated or some libraries are stop working then Xcode will show you only error of

this application does not support this device's cpu type

or

Could not write to the device

So you have to check that which library is deprecated after launching of ios 11.

Also you have to check all other details like Build Active Architectures Only, Architectures, Valid Architectures, Required device capabilities from Info.plist.


来源: stackexchange

问:
Other ways to search a ListView
I am trying to use TextChangedListener to implement search functionality on my ListView. But after adding some character in EditText; the ListView goes blank. I have implemented filter method in my ArrayAdapter class.

I am getting my data from JSON.

My Logcat shows: getSlotFromBufferLocked: unknown buffer

Is there any other way to search ListView?

Here's my code:

UserList.java

```<code>public class UserList extends AppCompatActivity {

private ListView listView;
private ArrayList<MyDataModel> list;
private MyArrayAdapter adapter;
private EditText search;

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

    search = (EditText) findViewById(R.id.search);

    //Array List for Binding Data from JSON to this List
    list = new ArrayList<>();

    //Binding that List to Adapter
    adapter = new MyArrayAdapter(this, list);

    //Getting List and Setting List Adapter
    listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(adapter);

    listView.setTextFilterEnabled(true);
    search.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            String text = search.getText().toString().toLowerCase(Locale.getDefault());
            adapter.filter(text);
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

    //Checking Internet Connection
    if (InternetConnection.checkConnection(getApplicationContext())) {
        new GetDataTask().execute();
    } else {
        Snackbar.make(findViewById(R.id.parentLayout),"Internet Connection Not Available", Snackbar.LENGTH_LONG).show();
    }
}

//Creating Get Data Task for Getting Data From Web
class GetDataTask extends AsyncTask<Void, Void, Void> {

    ProgressDialog dialog;
    int jIndex;
    int x;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //Progress Dialog for User Interaction
        x=list.size();

        if(x==0)
            jIndex=0;
        else
            jIndex=x;

        dialog = new ProgressDialog(UserList.this);
        dialog.setTitle("Please Wait..."+x);
        dialog.setMessage("Retrieving Data");
        dialog.show();

    }

    @Nullable
    @Override
    protected Void doInBackground(Void... params) {

        //Getting JSON Object from Web Using okHttp
        JSONObject jsonObject = JSONParser.getDataFromWeb();

        try {

            if (jsonObject != null) {

                if(jsonObject.length() > 0) {

                    JSONArray array = jsonObject.getJSONArray(Keys.KEY_CONTACTS);

                    //Check Length of Array...
                    int lenArray = array.length();
                    if(lenArray > 0) {
                        for( ; jIndex < lenArray; jIndex++) {

                            //Creating Every time New Object and adding to List
                            MyDataModel model = new MyDataModel();

                            JSONObject innerObject = array.getJSONObject(jIndex);
                            String name = innerObject.getString(Keys.KEY_NAME);

                            model.setName(name);
                            list.add(model);
                        }
                    }
                }
            } else {

            }
        } catch (JSONException je) {
            Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        dialog.dismiss();

        //Checking if List size if more than zero then update ListView
        if(list.size() > 0) {
            adapter.notifyDataSetChanged();

        } else {
            Snackbar.make(findViewById(R.id.parentLayout), "No Data Found", Snackbar.LENGTH_LONG).show();
        }

    }
}
}
</code>```

I have implemented the filter method in my ArrayAdapter class.

Here's my ArrayAdapter class:

MyArrayAdapter.java

```<code>public class MyArrayAdapter extends ArrayAdapter<MyDataModel> implements Filterable{

List<MyDataModel> modelList;
Context context;
private LayoutInflater mInflater;
private ArrayList<MyDataModel> arrayList;

public MyArrayAdapter(Context context, List<MyDataModel> objects) {
    super(context, 0, objects);
    this.context = context;
    this.mInflater = LayoutInflater.from(context);
    modelList = objects;

    this.arrayList = new ArrayList<MyDataModel>();
    this.arrayList.addAll(modelList);
}

@Override
public MyDataModel getItem(int position) {
    return modelList.get(position);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHolder vh;
    if (convertView == null) {
        View view = mInflater.inflate(R.layout.layout_row_view, parent, false);
        vh = ViewHolder.create((RelativeLayout) view);
        view.setTag(vh);
    } else {
        vh = (ViewHolder) convertView.getTag();
    }

    MyDataModel item = getItem(position);

    vh.textViewName.setText(item.getName());
    return vh.rootView;
}

private static class ViewHolder {
    public final RelativeLayout rootView;

    public final TextView textViewName;

    private ViewHolder(RelativeLayout rootView, TextView textViewName) {
        this.rootView = rootView;
        this.textViewName = textViewName;
    }

    public static ViewHolder create(RelativeLayout rootView) {
        TextView textViewName = (TextView) rootView.findViewById(R.id.textViewName);
        return new ViewHolder(rootView, textViewName);
    }
}

// Filter Class
public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    modelList.clear();
    if (charText.length() == 0) {
        modelList.addAll(arrayList);
    } else {
        for (MyDataModel wp : arrayList) {
            if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
                modelList.add(wp);
            }
        }
    }
    notifyDataSetChanged();
}
</code>```

答:
Go with this link, and follow steps for implementing the same:

and the problem with buffer is called every textchanged listener will call everytime if you add or delete any character or space in it. So avoid using that. It will cause memory leak problems.

ContentLicense: CC BY-SA 3.0

Title: Other ways to search a ListView

Body:
I am trying to use TextChangedListener to implement search functionality on my ListView. But after adding some character in EditText; the ListView goes blank. I have implemented filter method in my ArrayAdapter class.

I am getting my data from JSON.

My Logcat shows: getSlotFromBufferLocked: unknown buffer

Is there any other way to search ListView?

Here's my code:

UserList.java

public class UserList extends AppCompatActivity {

private ListView listView;
private ArrayList<MyDataModel> list;
private MyArrayAdapter adapter;
private EditText search;

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

    search = (EditText) findViewById(R.id.search);

    //Array List for Binding Data from JSON to this List
    list = new ArrayList<>();

    //Binding that List to Adapter
    adapter = new MyArrayAdapter(this, list);

    //Getting List and Setting List Adapter
    listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(adapter);

    listView.setTextFilterEnabled(true);
    search.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            String text = search.getText().toString().toLowerCase(Locale.getDefault());
            adapter.filter(text);
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

    //Checking Internet Connection
    if (InternetConnection.checkConnection(getApplicationContext())) {
        new GetDataTask().execute();
    } else {
        Snackbar.make(findViewById(R.id.parentLayout),"Internet Connection Not Available", Snackbar.LENGTH_LONG).show();
    }
}

//Creating Get Data Task for Getting Data From Web
class GetDataTask extends AsyncTask<Void, Void, Void> {

    ProgressDialog dialog;
    int jIndex;
    int x;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //Progress Dialog for User Interaction
        x=list.size();

        if(x==0)
            jIndex=0;
        else
            jIndex=x;

        dialog = new ProgressDialog(UserList.this);
        dialog.setTitle("Please Wait..."+x);
        dialog.setMessage("Retrieving Data");
        dialog.show();

    }

    @Nullable
    @Override
    protected Void doInBackground(Void... params) {

        //Getting JSON Object from Web Using okHttp
        JSONObject jsonObject = JSONParser.getDataFromWeb();

        try {

            if (jsonObject != null) {

                if(jsonObject.length() > 0) {

                    JSONArray array = jsonObject.getJSONArray(Keys.KEY_CONTACTS);

                    //Check Length of Array...
                    int lenArray = array.length();
                    if(lenArray > 0) {
                        for( ; jIndex < lenArray; jIndex++) {

                            //Creating Every time New Object and adding to List
                            MyDataModel model = new MyDataModel();

                            JSONObject innerObject = array.getJSONObject(jIndex);
                            String name = innerObject.getString(Keys.KEY_NAME);

                            model.setName(name);
                            list.add(model);
                        }
                    }
                }
            } else {

            }
        } catch (JSONException je) {
            Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        dialog.dismiss();

        //Checking if List size if more than zero then update ListView
        if(list.size() > 0) {
            adapter.notifyDataSetChanged();

        } else {
            Snackbar.make(findViewById(R.id.parentLayout), "No Data Found", Snackbar.LENGTH_LONG).show();
        }

    }
}
}

I have implemented the filter method in my ArrayAdapter class.

Here's my ArrayAdapter class:

MyArrayAdapter.java

public class MyArrayAdapter extends ArrayAdapter<MyDataModel> implements Filterable{

List<MyDataModel> modelList;
Context context;
private LayoutInflater mInflater;
private ArrayList<MyDataModel> arrayList;

public MyArrayAdapter(Context context, List<MyDataModel> objects) {
    super(context, 0, objects);
    this.context = context;
    this.mInflater = LayoutInflater.from(context);
    modelList = objects;

    this.arrayList = new ArrayList<MyDataModel>();
    this.arrayList.addAll(modelList);
}

@Override
public MyDataModel getItem(int position) {
    return modelList.get(position);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final ViewHolder vh;
    if (convertView == null) {
        View view = mInflater.inflate(R.layout.layout_row_view, parent, false);
        vh = ViewHolder.create((RelativeLayout) view);
        view.setTag(vh);
    } else {
        vh = (ViewHolder) convertView.getTag();
    }

    MyDataModel item = getItem(position);

    vh.textViewName.setText(item.getName());
    return vh.rootView;
}

private static class ViewHolder {
    public final RelativeLayout rootView;

    public final TextView textViewName;

    private ViewHolder(RelativeLayout rootView, TextView textViewName) {
        this.rootView = rootView;
        this.textViewName = textViewName;
    }

    public static ViewHolder create(RelativeLayout rootView) {
        TextView textViewName = (TextView) rootView.findViewById(R.id.textViewName);
        return new ViewHolder(rootView, textViewName);
    }
}

// Filter Class
public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    modelList.clear();
    if (charText.length() == 0) {
        modelList.addAll(arrayList);
    } else {
        for (MyDataModel wp : arrayList) {
            if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
                modelList.add(wp);
            }
        }
    }
    notifyDataSetChanged();
}


问:
Alternative to finding elements using hard coded Xpath
I have a html below that contains simply div tags that within contain text fields and a display for validation messages:

```<code><div class="payment-form">
   <div class="payment-form__payment-type">
      <div class="false-label">Payment type</div>
      <div class="form-column">
         <div class="false-label">Name on card</div>
         <div class="form-element-wrapper form-element-wrapper--input-text clearfix form-element-wrapper--error form-element-wrapper--show-label"><label for="name-on-card">Name on card</label> <input name="name-on-card" data-payment-jet2="holderName" id="name-on-card" type="text" maxlength="32" data-vv-id="_0zd5ajemk" aria-required="true" aria-invalid="true"></div>
         <p class="validation-message validation-message--active" style="">Please correct the name on card</p>
      </div>
      <div class="form-column">
         <div class="false-label">Card number</div>
         <div class="form-element-wrapper form-element-wrapper--input-text clearfix form-element-wrapper--error form-element-wrapper--show-label"><label for="card-number">e.g 1111-2222-3333-4444</label> <input type="hidden" data-payment-jet2="number"> <input name="card-number" id="card-number" type="tel" maxlength="23" class="js-payment-card-number" data-vv-id="_wn4jqw3yg" aria-required="true" aria-invalid="true"></div>
         <p class="validation-message validation-message--active" style="">Please correct the card number</p>
      </div>
   </div>
</div>
</code>```

Now the problem I am having is with the validation messages which are the same class:

```<code><p class="validation-message validation-message--active" style="">
</code>```

In my selenium I want to ensure the correct validation is displayed but because they have the same class, I cannot differentiate between then unless I use a hard coded dirty xpath like:

```<code>public static By NameOnCardValidation => By.XPath("/html/body/div[1]/div[3]/section/div[6]/div[2]/div/div/div/div/div[3]/p");
public static By CardNumberValidation => By.XPath("/html/body/div[1]/div[3]/section/div[6]/div[2]/div/div/div/div/div[4]/p");
</code>```

Thus makes maintenance difficult as if there are any changes to the website, then I will have to keep updating these xpaths.

My question is that can you see a way where I can locate the validation messages a lot easier without entering a hard coded xpath like above? Just to let you know the messages in the validation may change so it would not be a good idea to look for the text within the validation message.

Thanks,

答:
My question is that can you see a way where I can locate the
  validation messages a lot easier without entering a hard coded xpath
  like above?

In such cases we do it in a simple and general way (using JBehave and java, but that's implementation details that do not matter)

At the story level there is simple Then step:

```<code>When an user performs some action
Then a message appears on the screen: some message
</code>```

and it's implementation looks like this:

```<code>@Then("a message appears on the screen: $message")
public void shoudMeassageAppearOnTheScreen( String message ){
      String xpath = String.format(
           "//*[contains( @class, 'validation-message' ) and text() = '%s' ]", message
      );

       WebDriverWait wait = new WebDriverWait( driver, 5 );
       try{
          wait.until( ExpecedConditions.visibilityOfElementLocated( By.xpath( xpath ));
      }catch( Exception e ){
         throw new RuntimeException( "Message is not visible: " + message, e );
      }
}
</code>```

so we are waiting 5 seconds for the message, if it is not visible, then an exception is thrown with a understandable error message, and a test fails (due to the exception thrown to the log).

Body:
I have a html below that contains simply div tags that within contain text fields and a display for validation messages:

Payment type

Name on card

Name on card <input name="name-on-card" data-payment-jet2="holderName" id="name-on-card" type="text" maxlength="32" data-vv-id="_0zd5ajemk" aria-required="true" aria-invalid="true">

Please correct the name on card

Card number

e.g 1111-2222-3333-4444 <input type="hidden" data-payment-jet2="number"> <input name="card-number" id="card-number" type="tel" maxlength="23" class="js-payment-card-number" data-vv-id="_wn4jqw3yg" aria-required="true" aria-invalid="true">

Please correct the card number

Now the problem I am having is with the validation messages which are the same class:

In my selenium I want to ensure the correct validation is displayed but because they have the same class, I cannot differentiate between then unless I use a hard coded dirty xpath like:

public static By NameOnCardValidation => By.XPath("/html/body/div[1]/div[3]/section/div[6]/div[2]/div/div/div/div/div[3]/p");
public static By CardNumberValidation => By.XPath("/html/body/div[1]/div[3]/section/div[6]/div[2]/div/div/div/div/div[4]/p");

Thus makes maintenance difficult as if there are any changes to the website, then I will have to keep updating these xpaths.

My question is that can you see a way where I can locate the validation messages a lot easier without entering a hard coded xpath like above? Just to let you know the messages in the validation may change so it would not be a good idea to look for the text within the validation message.

Thanks,

Body:
My question is that can you see a way where I can locate the
  validation messages a lot easier without entering a hard coded xpath
  like above?

In such cases we do it in a simple and general way (using JBehave and java, but that's implementation details that do not matter)

At the story level there is simple Then step:

When an user performs some action
Then a message appears on the screen: some message

and it's implementation looks like this:

@Then("a message appears on the screen: $message")
public void shoudMeassageAppearOnTheScreen( String message ){
      String xpath = String.format(
           "//*[contains( @class, 'validation-message' ) and text() = '%s' ]", message
      );

       WebDriverWait wait = new WebDriverWait( driver, 5 );
       try{
          wait.until( ExpecedConditions.visibilityOfElementLocated( By.xpath( xpath ));
      }catch( Exception e ){
         throw new RuntimeException( "Message is not visible: " + message, e );
      }
}

so we are waiting 5 seconds for the message, if it is not visible, then an exception is thrown with a understandable error message, and a test fails (due to the exception thrown to the log).


问:
vim not working when calling git commit within cygwin
I am using git within Cygwin 64 under windows. The default editor vi and git uses the default editor. When I call 'git commit' following messages will be prompted before vim is started:

```<code>git commit
Vim warning: output is not to a terminal
Vim warning: input is not from a terminal
</code>```

After that, vi will started but can't be controlled, 'ESC',  ':' can't be used and I have to kill the cygwin window.

How can I use vim for the 'git commit'?

答:
This might be cause by mintty, see this issue.

There are two ways to fix:

Use bash.exe instead of mintty:

Right click on the shortcut of cygwin, change it from C:\cygwin64\bin\mintty.exe -i /Cygwin-Terminal.ico - to C:\cygwin64\bin\bash.exe --login -i

Add the correct vim path to git config:

git config --global core.editor "C:/cygwin64/bin/vim.exe"

Note that don't use cygdrive in the path as .gitconfig can't recognize it. And if you are using 32-bit vim, then the path should be C:/cygwin/bin/

Body:
I am using git within Cygwin 64 under windows. The default editor vi and git uses the default editor. When I call 'git commit' following messages will be prompted before vim is started:

git commit
Vim warning: output is not to a terminal
Vim warning: input is not from a terminal

After that, vi will started but can't be controlled, 'ESC',  ':' can't be used and I have to kill the cygwin window.

How can I use vim for the 'git commit'?


问:
How can I retain existing log file permissions with Log4J DailyRollingFileAppender
I have a jar file which internally use log file to write messages. Using this jar I have developed a Perl module. The usage of this module is across out firm. So I have given 666 permissions on all the log files so that everyone can use the module. The issue is the jar file internally uses log4j and the appender is DailyRollingFileAppender which is resetting the permissions on the log files to 664 after rolling and certain people are not able to use the module.

Is there a way to mention to log4j to retain the existing permissions of the log file ? If not, can anyone suggest alternative ?

答:
This is the responsibility of the operating system. When Log4j rolls a log, the OS will create that new file according to its own rules.

You should be able to reproduce this manually, by opening a shell in the log directory and running touch testfile - the file testfile should exhibit the same permissions as new log4j files.

You need to look at the file permissions on the directory, those that are inherited by new files in that directory. You may also need to tinker with the user's umask setting.

If you can reproduce the problem without using log4j or java, then it becomes easier to solve, but would be best asked on superuser.com.

ContentLicense: CC BY-SA 2.5


问:
How to read two IMEI, from Cell phone Dual SIM? (In Android Studio)
I used this line in Android Studio to get IMEI number,

```<code>"android.telephony.TelephonyManager.getDeviceId()"
</code>```

and I can see the first IMEI, but I need see the second IMEI.

Update: I checked this link
Android : Check whether the phone is dual SIM

but I cant resolve the second IMEI.

答:
Try using getDeviceId(int slotId) added in API level 23.

```<code>TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String imeiNumber1 = tm.getDeviceId(0);
String imeiNumber2 = tm.getDeviceId(1);
</code>```

Requires Permission: READ_PHONE_STATE

Body:
I used this line in Android Studio to get IMEI number,

"android.telephony.TelephonyManager.getDeviceId()"

and I can see the first IMEI, but I need see the second IMEI.

Update: I checked this link
Android : Check whether the phone is dual SIM

but I cant resolve the second IMEI.

Body:
Try using getDeviceId(int slotId) added in API level 23.

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String imeiNumber1 = tm.getDeviceId(0);
String imeiNumber2 = tm.getDeviceId(1);

Requires Permission: READ_PHONE_STATE


问:
HTML/CSS nav bar spacing issues with flexbox
Could not yet find this exact issue that I am having addressed, so it here goes:

I am trying to create a nav bar with a heading on the left-hand side, and some nav items on the right.  I also want the nav to be centered on the page, with a width of 960px.  I am trying to accomplish 2 additional things:

1.) The nav bar should be fixed to the top so that it does not disappear when you scroll.

2.) The spacing between the heading and the nav items should be the first to disappear when you minimize the screen.  Currently, the items do not flex at all.

I am able to get one of these two things accomplished at a time, but not both at the same time.  Any help would be most welcome, thank you.

html {
  font-family: helvetica;
  font-size: 18px;
}

.container {
  max-width: 960px;
  margin: 0 auto;
}

.banner {
  background-color: aqua;
  opacity: .5;
  border-radius: 10px;
  position: fixed;
}

.header {
  display: flex;
  justify-content: space-between;
  height: 4rem;
  align-items: center;
  width: 960px;
}

.container .banner .header h1 {
  margin-left: 2.5rem;
}

.container .banner .header .nav ul {
  display: flex;
  width: 200px;
  justify-content: space-between;
  text-decoration: none;
  margin-right: 2.5rem;
}

.container .banner .header .nav ul a {
  color: black;
  list-style-type: none;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="banner">
    <div class="header">
      <h1>My Sweet Sweet Georgia</h1>
      <div class="nav">
        <ul>
          <li>doggy</li>
          <li>puppy</li>
          <li>toys</li>
        </ul>
      </div>
    </div>
  </div>
</div></code>```

答:
You can use align-items: left for your heading and align-items: right instead of using margin

* {
  padding: 0;
  margin: 0;
}

html {
  font-family: helvetica;
  font-size: 18px;
}

.container .header {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  flex-direction: row;
  height: 4rem;
  align-items: center;
  width: 100%;
  position: fixed;
  background: aqua;
  opacity: .7;
  border-radius: 10px;
}

.container .header .nav ul li {
  display: inline-flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title>My Puppy</title>
  <link href="./resources/reset.css" type="text/css" rel="stylesheet">
  <link href="./resources/style.css" type="text/css" rel="stylesheet">
</head>

<body>
  <div class="container">
    <div class="header">
      <h1>My Sweet Sweet Georgia</h1>
      <div class="nav">
        <ul>
          <li>doggy</li>
          <li>puppy</li>
          <li>toys</li>
        </ul>
      </div>
    </div>
  </div>
</body></code>```

Body:
Could not yet find this exact issue that I am having addressed, so it here goes:

I am trying to create a nav bar with a heading on the left-hand side, and some nav items on the right.  I also want the nav to be centered on the page, with a width of 960px.  I am trying to accomplish 2 additional things:

1.) The nav bar should be fixed to the top so that it does not disappear when you scroll.

2.) The spacing between the heading and the nav items should be the first to disappear when you minimize the screen.  Currently, the items do not flex at all.

I am able to get one of these two things accomplished at a time, but not both at the same time.  Any help would be most welcome, thank you.

html {
  font-family: helvetica;
  font-size: 18px;
}

.container {
  max-width: 960px;
  margin: 0 auto;
}

.banner {
  background-color: aqua;
  opacity: .5;
  border-radius: 10px;
  position: fixed;
}

.header {
  display: flex;
  justify-content: space-between;
  height: 4rem;
  align-items: center;
  width: 960px;
}

.container .banner .header h1 {
  margin-left: 2.5rem;
}

.container .banner .header .nav ul {
  display: flex;
  width: 200px;
  justify-content: space-between;
  text-decoration: none;
  margin-right: 2.5rem;
}

.container .banner .header .nav ul a {
  color: black;
  list-style-type: none;
  text-decoration: none;
}

My Sweet Sweet Georgia

doggy

puppy

toys

Body:
You can use align-items: left for your heading and align-items: right instead of using margin

* {
  padding: 0;
  margin: 0;
}

html {
  font-family: helvetica;
  font-size: 18px;
}

.container .header {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  flex-direction: row;
  height: 4rem;
  align-items: center;
  width: 100%;
  position: fixed;
  background: aqua;
  opacity: .7;
  border-radius: 10px;
}

.container .header .nav ul li {
  display: inline-flex;
}

<!DOCTYPE html>
<html>

<head>
  <title>My Puppy</title>
  <link href="./resources/reset.css" type="text/css" rel="stylesheet">
  <link href="./resources/style.css" type="text/css" rel="stylesheet">
</head>

<body>
  <div class="container">
    <div class="header">
      <h1>My Sweet Sweet Georgia</h1>
      <div class="nav">
        <ul>
          <li><a href="#">doggy</a></li>
          <li><a href="#">puppy</a></li>
          <li><a href="#">toys</a></li>
        </ul>
      </div>
    </div>
  </div>
</body>


问:
css drop down menu links are being pushed right
I'm creating a drop down menu, and instead of another UL after a closing LI tag, I'm using a DIV tag instead, because I'm not displaying another unordered list, I'm displaying a login.

Here is a picture of the issue, the link is being pushed over when hovered over.

If anyone knows a solution, that would be greatly appreciated! Thanks in advance.

Code:s

.menu {
  height: 60px;
  width: 100%;
  background-color: #fcfcfc;
  padding: 1px;
}

.menu nav ul {
  list-style: none;
  list-style-type: none;
}

.menu nav ul li {
  float: left;
}

.menu nav ul li a {
  font-size: 18px;
  color: #555;
  text-decoration: none;
  text-transform: uppercase;
  padding: 21px 20px;
}

.menu nav ul li a:hover {
  transition: all .3s ease;
  -o-transition: all .3s ease;
  -ms-transition: all .3s ease;
  -moz-transition: all .3s ease;
  -webkit-transition: all .3s ease;
  background-color: rgba(0, 0, 0, .3);
  color: #333;
}

.menu nav ul li>.glob-auth {
  width: 300px;
  background-color: #fcfcfc;
  display: none;
  margin-top: 28px;
  padding: 0;
  border-radius: 20px;
  -o-border-radius: 20px;
  -ms-border-radius: 20px;
  -moz-border-radius: 20px;
  -webkit-border-radius: 20px;
  z-index: 3;
}

.menu nav ul li>.glob-auth .glob-auth-top {
  padding: 1px;
  background-color: #00B16A;
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
}

.menu nav ul li>.glob-auth .glob-auth-top header h1 {
  padding: 0;
  margin: 0;
  color: #fcfcfc;
  padding-left: 10px;
}

.menu nav ul li>.glob-auth .glob-auth-body {
  padding: 10px;
}

.menu nav ul li>.glob-auth .glob-auth-body input {
  padding: 10px;
  width: 260px;
  border-style: none;
  background-color: rgba(0, 0, 0, .1);
  font-family: 'Open Sans', sans-serif;
  font-size: 16px;
  border-radius: 3px;
  -o-border-radius: 3px;
  -ms-border-radius: 3px;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
}

.menu nav ul li>.glob-auth .glob-auth-body input:focus {
  outline: none;
}

.menu nav ul li>.glob-auth .glob-auth-body input:nth-child(2) {
  margin-top: 10px;
  margin-bottom: 10px;
}

.menu nav ul li>.glob-auth .glob-auth-body button {
  padding: 10px;
  font-size: 18px;
  background-color: #009157;
  border-style: none;
  width: 100%;
  color: #fcfcfc;
  font-family: 'Open Sans', sans-serif;
  border-radius: 4px;
  -o-border-radius: 4px;
  -ms-border-radius: 4px;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  border-bottom: 4px solid rgba(0, 0, 0, .3);
  cursor: pointer;
}

.menu nav ul li>.glob-auth .glob-auth-body button:focus {
  outline: none;
}

.menu nav ul li:hover>.glob-auth {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu">
  <nav>
    <ul>
      <li>Login
        <div class="glob-auth">
          <div class="glob-auth-top">
            <header>
              <h1>Login</h1>
            </header>
          </div>
          <div class="glob-auth-body">
            <form method="post">
              <input type="text" name="l_user" placeholder="Enter username" autocomplete="off" maxlength="20">
              <input type="password" name="l_pass" placeholder="Enter password" autocomplete="off" maxlength="120">
              <button name="l_submit">Login</button>
            </form>
          </div>
        </div>
      </li>
      <li>Register
        <div class="glob-auth">
          <div class="glob-auth-top">
            <header>
              <h1>Register</h1>
            </header>
          </div>
          <div class="glob-auth-body">
            <form method="post">
              <input type="text" name="l_user" placeholder="Enter username" autocomplete="off" maxlength="20">
              <input type="password" name="l_pass" placeholder="Enter password" autocomplete="off" maxlength="120">
              <button name="l_submit">Login</button>
            </form>
          </div>
        </div>
      </li>
    </ul>
  </nav>
</div></code>```

答:
Insert This:

```<code>.menu nav ul li > .glob-auth {
    position: absolute;
    //Other codes...
}
</code>```

.menu{
    height: 60px;
    width: 100%;
    background-color: #fcfcfc;
    padding: 1px;
}
.menu nav ul{
    list-style: none;
    list-style-type: none;
}
.menu nav ul li{
    float: left;
}
.menu nav ul li a{
    font-size: 18px;
    color: #555;
    text-decoration: none;
    text-transform: uppercase;
    padding: 21px 20px;
}
.menu nav ul li a:hover{
    transition: all .3s ease;
    -o-transition: all .3s ease;
    -ms-transition: all .3s ease;
    -moz-transition: all .3s ease;
    -webkit-transition: all .3s ease;
    background-color: rgba(0,0,0,.3);
    color: #333;
}
.menu nav ul li > .glob-auth {
    width: 300px;
    background-color: #fcfcfc;
    display: none;
    margin-top: 28px;
    padding: 0;
    border-radius: 20px;
    -o-border-radius: 20px;
    -ms-border-radius: 20px;
    -moz-border-radius: 20px;
    -webkit-border-radius: 20px;
    z-index: 3;
    position: absolute;
}
.menu nav ul li > .glob-auth .glob-auth-top{
    padding: 1px;
    background-color: #00B16A;
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
}
.menu nav ul li > .glob-auth .glob-auth-top header h1{
    padding: 0;
    margin: 0;
    color: #fcfcfc;
    padding-left: 10px;
}
.menu nav ul li > .glob-auth .glob-auth-body{
    padding: 10px;
}
.menu nav ul li > .glob-auth .glob-auth-body input{
    padding: 10px;
    width: 260px;
    border-style: none;
    background-color: rgba(0,0,0,.1);
    font-family: 'Open Sans', sans-serif;
    font-size: 16px;
    border-radius: 3px;
    -o-border-radius: 3px;
    -ms-border-radius: 3px;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
}
.menu nav ul li > .glob-auth .glob-auth-body input:focus{
    outline: none;
}
.menu nav ul li > .glob-auth .glob-auth-body input:nth-child(2){
    margin-top: 10px;
    margin-bottom: 10px;
}
.menu nav ul li > .glob-auth .glob-auth-body button{
    padding: 10px;
    font-size: 18px;
    background-color: #009157;
    border-style: none;
    width: 100%;
    color: #fcfcfc;
    font-family: 'Open Sans', sans-serif;
    border-radius: 4px;
    -o-border-radius: 4px;
    -ms-border-radius: 4px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    border-bottom: 4px solid rgba(0,0,0,.3);
    cursor: pointer;
}
.menu nav ul li > .glob-auth .glob-auth-body button:focus{
    outline: none;
}
.menu nav ul li:hover > .glob-auth{
    display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu">
<nav>
    <ul>
        <li>Login
            <div class="glob-auth">
                <div class="glob-auth-top">
                    <header>
                        <h1>Login</h1>
                    </header>
                </div>
                <div class="glob-auth-body">
                    <form method="post">
                        <input type="text" name="l_user" placeholder="Enter username" autocomplete="off" maxlength="20">
                        <input type="password" name="l_pass" placeholder="Enter password" autocomplete="off" maxlength="120">
                        <button name="l_submit">Login</button>
                    </form>
                </div>
            </div>
        </li>
        <li>Register
            <div class="glob-auth">
                <div class="glob-auth-top">
                    <header>
                        <h1>Register</h1>
                    </header>
                </div>
                <div class="glob-auth-body">
                    <form method="post">
                        <input type="text" name="l_user" placeholder="Enter username" autocomplete="off" maxlength="20">
                        <input type="password" name="l_pass" placeholder="Enter password" autocomplete="off" maxlength="120">
                        <button name="l_submit">Login</button>
                    </form>
                </div>
            </div>
        </li>
    </ul>
</nav></code>```

Body:
I'm creating a drop down menu, and instead of another UL after a closing LI tag, I'm using a DIV tag instead, because I'm not displaying another unordered list, I'm displaying a login.

Here is a picture of the issue, the link is being pushed over when hovered over.

If anyone knows a solution, that would be greatly appreciated! Thanks in advance.

Code:s

.menu {
  height: 60px;
  width: 100%;
  background-color: #fcfcfc;
  padding: 1px;
}

.menu nav ul {
  list-style: none;
  list-style-type: none;
}

.menu nav ul li {
  float: left;
}

.menu nav ul li a {
  font-size: 18px;
  color: #555;
  text-decoration: none;
  text-transform: uppercase;
  padding: 21px 20px;
}

.menu nav ul li a:hover {
  transition: all .3s ease;
  -o-transition: all .3s ease;
  -ms-transition: all .3s ease;
  -moz-transition: all .3s ease;
  -webkit-transition: all .3s ease;
  background-color: rgba(0, 0, 0, .3);
  color: #333;
}

.menu nav ul li>.glob-auth {
  width: 300px;
  background-color: #fcfcfc;
  display: none;
  margin-top: 28px;
  padding: 0;
  border-radius: 20px;
  -o-border-radius: 20px;
  -ms-border-radius: 20px;
  -moz-border-radius: 20px;
  -webkit-border-radius: 20px;
  z-index: 3;
}

.menu nav ul li>.glob-auth .glob-auth-top {
  padding: 1px;
  background-color: #00B16A;
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
}

.menu nav ul li>.glob-auth .glob-auth-top header h1 {
  padding: 0;
  margin: 0;
  color: #fcfcfc;
  padding-left: 10px;
}

.menu nav ul li>.glob-auth .glob-auth-body {
  padding: 10px;
}

.menu nav ul li>.glob-auth .glob-auth-body input {
  padding: 10px;
  width: 260px;
  border-style: none;
  background-color: rgba(0, 0, 0, .1);
  font-family: 'Open Sans', sans-serif;
  font-size: 16px;
  border-radius: 3px;
  -o-border-radius: 3px;
  -ms-border-radius: 3px;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
}

.menu nav ul li>.glob-auth .glob-auth-body input:focus {
  outline: none;
}

.menu nav ul li>.glob-auth .glob-auth-body input:nth-child(2) {
  margin-top: 10px;
  margin-bottom: 10px;
}

.menu nav ul li>.glob-auth .glob-auth-body button {
  padding: 10px;
  font-size: 18px;
  background-color: #009157;
  border-style: none;
  width: 100%;
  color: #fcfcfc;
  font-family: 'Open Sans', sans-serif;
  border-radius: 4px;
  -o-border-radius: 4px;
  -ms-border-radius: 4px;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  border-bottom: 4px solid rgba(0, 0, 0, .3);
  cursor: pointer;
}

.menu nav ul li>.glob-auth .glob-auth-body button:focus {
  outline: none;
}

.menu nav ul li:hover>.glob-auth {
  display: block;
}

Login

Login

            <form method="post">
              <input type="text" name="l_user" placeholder="Enter username" autocomplete="off" maxlength="20">
              <input type="password" name="l_pass" placeholder="Enter password" autocomplete="off" maxlength="120">
              <button name="l_submit">Login</button>
            </form>

Register

Register

            <form method="post">
              <input type="text" name="l_user" placeholder="Enter username" autocomplete="off" maxlength="20">
              <input type="password" name="l_pass" placeholder="Enter password" autocomplete="off" maxlength="120">
              <button name="l_submit">Login</button>
            </form>

Body:
Insert This:

.menu nav ul li > .glob-auth {
    position: absolute;
    //Other codes...
}

.menu{
    height: 60px;
    width: 100%;
    background-color: #fcfcfc;
    padding: 1px;
}
.menu nav ul{
    list-style: none;
    list-style-type: none;
}
.menu nav ul li{
    float: left;
}
.menu nav ul li a{
    font-size: 18px;
    color: #555;
    text-decoration: none;
    text-transform: uppercase;
    padding: 21px 20px;
}
.menu nav ul li a:hover{
    transition: all .3s ease;
    -o-transition: all .3s ease;
    -ms-transition: all .3s ease;
    -moz-transition: all .3s ease;
    -webkit-transition: all .3s ease;
    background-color: rgba(0,0,0,.3);
    color: #333;
}
.menu nav ul li > .glob-auth {
    width: 300px;
    background-color: #fcfcfc;
    display: none;
    margin-top: 28px;
    padding: 0;
    border-radius: 20px;
    -o-border-radius: 20px;
    -ms-border-radius: 20px;
    -moz-border-radius: 20px;
    -webkit-border-radius: 20px;
    z-index: 3;
    position: absolute;
}
.menu nav ul li > .glob-auth .glob-auth-top{
    padding: 1px;
    background-color: #00B16A;
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
}
.menu nav ul li > .glob-auth .glob-auth-top header h1{
    padding: 0;
    margin: 0;
    color: #fcfcfc;
    padding-left: 10px;
}
.menu nav ul li > .glob-auth .glob-auth-body{
    padding: 10px;
}
.menu nav ul li > .glob-auth .glob-auth-body input{
    padding: 10px;
    width: 260px;
    border-style: none;
    background-color: rgba(0,0,0,.1);
    font-family: 'Open Sans', sans-serif;
    font-size: 16px;
    border-radius: 3px;
    -o-border-radius: 3px;
    -ms-border-radius: 3px;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
}
.menu nav ul li > .glob-auth .glob-auth-body input:focus{
    outline: none;
}
.menu nav ul li > .glob-auth .glob-auth-body input:nth-child(2){
    margin-top: 10px;
    margin-bottom: 10px;
}
.menu nav ul li > .glob-auth .glob-auth-body button{
    padding: 10px;
    font-size: 18px;
    background-color: #009157;
    border-style: none;
    width: 100%;
    color: #fcfcfc;
    font-family: 'Open Sans', sans-serif;
    border-radius: 4px;
    -o-border-radius: 4px;
    -ms-border-radius: 4px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    border-bottom: 4px solid rgba(0,0,0,.3);
    cursor: pointer;
}
.menu nav ul li > .glob-auth .glob-auth-body button:focus{
    outline: none;
}
.menu nav ul li:hover > .glob-auth{
    display: block;
}

<div class="menu">
<nav>
    <ul>
        <li><a href="#">Login</a>
            <div class="glob-auth">
                <div class="glob-auth-top">
                    <header>
                        <h1>Login</h1>
                    </header>
                </div>
                <div class="glob-auth-body">
                    <form method="post">
                        <input type="text" name="l_user" placeholder="Enter username" autocomplete="off" maxlength="20">
                        <input type="password" name="l_pass" placeholder="Enter password" autocomplete="off" maxlength="120">
                        <button name="l_submit">Login</button>
                    </form>
                </div>
            </div>
        </li>
        <li><a href="#">Register</a>
            <div class="glob-auth">
                <div class="glob-auth-top">
                    <header>
                        <h1>Register</h1>
                    </header>
                </div>
                <div class="glob-auth-body">
                    <form method="post">
                        <input type="text" name="l_user" placeholder="Enter username" autocomplete="off" maxlength="20">
                        <input type="password" name="l_pass" placeholder="Enter password" autocomplete="off" maxlength="120">
                        <button name="l_submit">Login</button>
                    </form>
                </div>
            </div>
        </li>
    </ul>
</nav>


问:
variable with "true" value does not meet [variable] == "true" javascript
I have a variable declared as true

```<code>var g1 = sessionStorage.getItem("g1"); //true
var g2 = sessionStorage.getItem("g2"); //false
var g3 = sessionStorage.getItem("g3"); //false
</code>```

but in my function

```<code>function checkmonitogift() {
    console.log(g1);
    if (g1 == true) {
        $("#g1").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g1").html("OK");
    }

    if (g2 == false) {
        $("#g2").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g2").html("OK");
    }

    if (g3 == false) {
        $("#g3").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g3").html("OK");
    }

}
</code>```

console return "true" but it still does not meet the condition of the if statement

答:
sessionStorage.getItem("g2") returns "true" (string) instead of true (boolean)

Make it

```<code>var g1 = sessionStorage.getItem("g1") == "true" ; //true
var g2 = sessionStorage.getItem("g2") == "true"; //false
var g3 = sessionStorage.getItem("g3") == "true"; //false
</code>```

Body:
I have a variable declared as true

var g1 = sessionStorage.getItem("g1"); //true
var g2 = sessionStorage.getItem("g2"); //false
var g3 = sessionStorage.getItem("g3"); //false

but in my function

function checkmonitogift() {
    console.log(g1);
    if (g1 == true) {
        $("#g1").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g1").html("OK");
    }

    if (g2 == false) {
        $("#g2").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g2").html("OK");
    }

    if (g3 == false) {
        $("#g3").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g3").html("OK");
    }

}

console return "true" but it still does not meet the condition of the if statement

Body:
sessionStorage.getItem("g2") returns "true" (string) instead of true (boolean)

Make it

var g1 = sessionStorage.getItem("g1") == "true" ; //true
var g2 = sessionStorage.getItem("g2") == "true"; //false
var g3 = sessionStorage.getItem("g3") == "true"; //false


问:
Is it possible to change the dimensions of my fabricjs canvas onclick?
I've got my fabricjs canvas set in JS as canvas.setHeight(616);
canvas.setWidth(446); and I was wondering if there was a way that I could enable the user to change these dimensions onclick, so that there are a few options?

答:
var canvas = new fabric.Canvas('a');
canvas.add(new fabric.Text('FabricJS is Awsome',{
 left:50,
 top:50
}));

function resizeCanvas(){
 canvas.setHeight(canvas.height+50);
 canvas.setWidth(canvas.width+50);
 canvas.renderAll();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  border: 2px solid black;
}</code>```

<button onclick='resizeCanvas()'>Resize</button>
<canvas id="a" width="200" height="200"></canvas>```

Use setHeight() / setWidth() to set height and width respectively.

Body:
var canvas = new fabric.Canvas('a');
canvas.add(new fabric.Text('FabricJS is Awsome',{
 left:50,
 top:50
}));

function resizeCanvas(){
 canvas.setHeight(canvas.height+50);
 canvas.setWidth(canvas.width+50);
 canvas.renderAll();
}

canvas {
  border: 2px solid black;
}

<script type='text/javascript' src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.19/fabric.js"></script>
<button onclick='resizeCanvas()'>Resize</button>
<canvas id="a" width="200" height="200"></canvas>

Use setHeight() / setWidth() to set height and width respectively.


问:
PHP - While writing a fixed length file, PHP is not processing `\t` as Tab after the first one. Why?
I am writing a fixed length file using PHP. Each character will have a predefined length. If characters are less than the length then it will insert that number of blank spaces. Each field is separated by TAB.

```<code>$str1 = str_pad('ten',10)."\t";
$str2 = str_pad('seven',7)."\t";
$str3 = str_pad('fifteen',15)."\t";

$str = $str1.$str2.$str3;

file_put_contents("newfile.txt",$str);
</code>```

But TAB is not working as expected.

I can see TAB only after first word (ten). After that there are no more TABs in the output file.

答:
It looks like when you are adding the padding to the string it is considering the TAB character as a space. I would suggest you change the code to the following to get the desired effect.

```<code>$str1 = str_pad('ten',10);
$str2 = str_pad('seven',7);
$str3 = str_pad('fifteen',15);

$str = $str1."\t".$str2."\t".$str3."\t";

file_put_contents("newfile.txt",$str);
</code>```

If there are a huge number of strings I would suggest putting them in an array and doing a foreach loop appending the tab character at the end.

By the way there is no tab character in your final string all you are seeing is the padding of spaces after the strings

Body:
I am writing a fixed length file using PHP. Each character will have a predefined length. If characters are less than the length then it will insert that number of blank spaces. Each field is separated by TAB.

$str1 = str_pad('ten',10)."\t";
$str2 = str_pad('seven',7)."\t";
$str3 = str_pad('fifteen',15)."\t";

$str = $str1.$str2.$str3;

file_put_contents("newfile.txt",$str);

But TAB is not working as expected.

I can see TAB only after first word (ten). After that there are no more TABs in the output file.

Body:
It looks like when you are adding the padding to the string it is considering the TAB character as a space. I would suggest you change the code to the following to get the desired effect.

$str1 = str_pad('ten',10);
$str2 = str_pad('seven',7);
$str3 = str_pad('fifteen',15);

$str = $str1."\t".$str2."\t".$str3."\t";

file_put_contents("newfile.txt",$str);

If there are a huge number of strings I would suggest putting them in an array and doing a foreach loop appending the tab character at the end.

By the way there is no tab character in your final string all you are seeing is the padding of spaces after the strings


问:
How to resume interrupted download automatically in curl?
I'm working with curl in Linux. I'm downloading a part of a file in ftp server (using the -r option), but my connection is not good, it always interrupts. I want to write a script which resume download when I'm connected again.

I've used this command, but it's not working:

```<code>until curl -r 666-9999 -C - --retry 999 -o "path/to/file" "ftp:/path/to/remote/file"; do :; done
</code>```

答:
```<code>curl -L -O your_url
</code>```

This will download the file.

Now let's say your connection is interrupted;

```<code>curl -L -O -C - your_url
</code>```

This will continue downloading from the last byte downloaded

From the manpage:

Use "-C -" to tell curl to automatically find out where/how to resume the transfer. It then uses the given output/input files to figure that out.

Body:
I'm working with curl in Linux. I'm downloading a part of a file in ftp server (using the -r option), but my connection is not good, it always interrupts. I want to write a script which resume download when I'm connected again.

I've used this command, but it's not working:

until curl -r 666-9999 -C - --retry 999 -o "path/to/file" "ftp:/path/to/remote/file"; do :; done

Body:
curl -L -O your_url

This will download the file.

Now let's say your connection is interrupted;

curl -L -O -C - your_url

This will continue downloading from the last byte downloaded

From the manpage:

Use "-C -" to tell curl to automatically find out where/how to resume the transfer. It then uses the given output/input files to figure that out.

ContentLicense: CC BY-SA 4.0


问:
jspdf first PDF page is blank
Im trying to get my jspdf to not save a blank page PDF. I been trying many examples, but nothing works :(. My table content is saved correct, with a image on the second page of the PDF, but my first page is blank.

```<code>var pdf = new jsPDF('o', 'pt', 'a6');
//pdf.autoTable(this.columns, this.data);
//var width = pdf.internal.pageSize.width;
//var height = pdf.internal.pageSize.height;
pdf.addPage('1800','900');
pdf.addImage(imgData, 'PNG', 120, 40, 120, 100);
pdf.setTextColor(0,0,0);
pdf.text(120, 20, 'BOOKINGS');
pdf.setFontSize(22);
// 'o', 'pt', 'a4'
// 'p', 'pt', 'letter'
// source can be HTML-formatted string, or a reference
// to an actual DOM element from which the text will be scraped.
source = jQuery('.dataTables_wrapper')[0];
// we support special element handlers. Register them with jQuery-style
// ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
// There is no support for any other type of selectors
// (class, of compound) at this time.
specialElementHandlers = {
    // element with id of "bypass" - jQuery style selector
    '#bypassme': function (element, renderer) {
        // true = "handled elsewhere, bypass text extraction"
        return true
    }
};
margins = {
    top: 120,
    bottom: 0,
    left: 0,
    width: 2000
};
// all coords and widths are in jsPDF instance's declared units
// 'inches' in this case
pdf.fromHTML(
source, // HTML string or DOM elem ref.
margins.left, // x coord
margins.top, { // y coord
    'width': margins.width, // max width of content on PDF
    'elementHandlers': specialElementHandlers
},

function (dispose) {
    // dispose: object with X, Y of the last line add to the PDF
    //          this allow the insertion of new lines after html
        pdf.save('bookings.pdf');
}, margins);
</code>```

}

答: The first page is blank because adding a page is the first call you make after calling the jsPDF constructor. The constructor does already create a (first) blank page. To get rid of the additional empty page at the start of the document, either delete the first page calling doc.deletePage(1), or do not add a page after the constructor is being called.

Title: jspdf first PDF page is blank

Body:
Im trying to get my jspdf to not save a blank page PDF. I been trying many examples, but nothing works :(. My table content is saved correct, with a image on the second page of the PDF, but my first page is blank.

var pdf = new jsPDF('o', 'pt', 'a6');
//pdf.autoTable(this.columns, this.data);
//var width = pdf.internal.pageSize.width;
//var height = pdf.internal.pageSize.height;
pdf.addPage('1800','900');
pdf.addImage(imgData, 'PNG', 120, 40, 120, 100);
pdf.setTextColor(0,0,0);
pdf.text(120, 20, 'BOOKINGS');
pdf.setFontSize(22);
// 'o', 'pt', 'a4'
// 'p', 'pt', 'letter'
// source can be HTML-formatted string, or a reference
// to an actual DOM element from which the text will be scraped.
source = jQuery('.dataTables_wrapper')[0];
// we support special element handlers. Register them with jQuery-style
// ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
// There is no support for any other type of selectors
// (class, of compound) at this time.
specialElementHandlers = {
    // element with id of "bypass" - jQuery style selector
    '#bypassme': function (element, renderer) {
        // true = "handled elsewhere, bypass text extraction"
        return true
    }
};
margins = {
    top: 120,
    bottom: 0,
    left: 0,
    width: 2000
};
// all coords and widths are in jsPDF instance's declared units
// 'inches' in this case
pdf.fromHTML(
source, // HTML string or DOM elem ref.
margins.left, // x coord
margins.top, { // y coord
    'width': margins.width, // max width of content on PDF
    'elementHandlers': specialElementHandlers
},

function (dispose) {
    // dispose: object with X, Y of the last line add to the PDF
    //          this allow the insertion of new lines after html
        pdf.save('bookings.pdf');
}, margins);

}


问:
Sqoop2 Hbase Import:Could not insert row with null value for row-key column
I am trying to migrate the data from oracle to Hbase with sqoop job.It looks like that it has successfully exported but it throws an error while importing the same in Hbase.

Job1:

```<code> `sqoop import --verbose --connect *** --username *** --password *** --table 'abc' --columns "MID,EID,RTIMESTAMP,VALUE,UTIMESTAMP" --split-by 'abc.ID' --hbase-table "HPVSQOOP" --column-family "cf1" --hbase-row-key MID,EID,RTIMESTAMP --num-mappers 4 --hbase-bulkload
</code>```

where ID is the primary key in Oracle but I want my HBase row-key to be as MID_EID_RTIMESTAMP

Map-Reduced failed by throwing an Error:

INFO mapreduce.Job: Task Id : attempt_1492489711789_0014_m_000003_2,
  Status : FAILED Error: java.io.IOException: Could not insert row with
  null value for row-key column: MID,EID,RTIMESTAMP at
  org.apache.sqoop.hbase.ToStringPutTransformer.getPutCommand(ToStringPutTransformer.java:146)
  at
  org.apache.sqoop.mapreduce.HBaseBulkImportMapper.map(HBaseBulkImportMapper.java:83)

Another Job with --query is not working with Hbase import.

Job2:

```<code>sqoop import --verbose --connect *** --username *** --password **' --query "select MID,EID,VALUE,RTIMESTAMP,UTIMESTAMP,ID from database.abc where \$CONDITIONS" --split-by 'abc.ID' --hbase-table "HPVSQOOP" --column-family "cf1" --hbase-row-key "MID,EID,RTIMESTAMP" --num-mappers 4 --hbase-bulkload
</code>```

ended up throwing an error:

ERROR sqoop.Sqoop: Got exception running Sqoop:
  java.lang.NullPointerException java.lang.NullPointerException

答: If the column name is lowercase in your database, you should use lowercase names in the command line like this --hbase-row-key "mid,eid..."

Body:
I am trying to migrate the data from oracle to Hbase with sqoop job.It looks like that it has successfully exported but it throws an error while importing the same in Hbase.

Job1:

 `sqoop import --verbose --connect *** --username *** --password *** --table 'abc' --columns "MID,EID,RTIMESTAMP,VALUE,UTIMESTAMP" --split-by 'abc.ID' --hbase-table "HPVSQOOP" --column-family "cf1" --hbase-row-key MID,EID,RTIMESTAMP --num-mappers 4 --hbase-bulkload

where ID is the primary key in Oracle but I want my HBase row-key to be as MID_EID_RTIMESTAMP

Map-Reduced failed by throwing an Error:

INFO mapreduce.Job: Task Id : attempt_1492489711789_0014_m_000003_2,
  Status : FAILED Error: java.io.IOException: Could not insert row with
  null value for row-key column: MID,EID,RTIMESTAMP at
  org.apache.sqoop.hbase.ToStringPutTransformer.getPutCommand(ToStringPutTransformer.java:146)
  at
  org.apache.sqoop.mapreduce.HBaseBulkImportMapper.map(HBaseBulkImportMapper.java:83)

Another Job with --query is not working with Hbase import.

Job2:

sqoop import --verbose --connect *** --username *** --password **' --query "select MID,EID,VALUE,RTIMESTAMP,UTIMESTAMP,ID from database.abc where \$CONDITIONS" --split-by 'abc.ID' --hbase-table "HPVSQOOP" --column-family "cf1" --hbase-row-key "MID,EID,RTIMESTAMP" --num-mappers 4 --hbase-bulkload

ended up throwing an error:

ERROR sqoop.Sqoop: Got exception running Sqoop:
  java.lang.NullPointerException java.lang.NullPointerException


问:
UserControl rendering: write link to current page?
I'm implementing a custom control and in this control I need to write a bunch of links to the current page, each one with a different query parameter. I need to keep existing query string intact, and add (or modify the value  of ) an extra query item (eg. "page"):

```<code>"Default.aspx?page=1"
"Default.aspx?page=2"
"Default.aspx?someother=true&page=2"
</code>```

etc.

Is there a simple helper method that I can use  in the Render method  ... uhmm ... like:

```<code>Page.ClientScript.SomeURLBuilderMethodHere(this,"page","1");
Page.ClientScript.SomeURLBuilderMethodHere(this,"page","2");
</code>```

That will take care of generating a correct URL, maintain existing query string items and not create duplicates  eg. page=1&page=2&page=3?

Rolling up my own seems like such an unappealing task.

答:
I'm afraid I don't know of any built-in method for this, we use this method that takes the querystring and sets parameters

```<code>    /// <summary>
    /// Set a parameter value in a query string. If the parameter is not found in the passed in query string,
    /// it is added to the end of the query string
    /// </summary>
    /// <param name="queryString">The query string that is to be manipulated</param>
    /// <param name="paramName">The name of the parameter</param>
    /// <param name="paramValue">The value that the parameter is to be set to</param>
    /// <returns>The query string with the parameter set to the new value.</returns>
    public static string SetParameter(string queryString, string paramName, object paramValue)
    {
        //create the regex
        //match paramname=*
        //string regex = String.Format(@"{0}=[^&]*", paramName);
        string regex = @"([&?]{0,1})" + String.Format(@"({0}=[^&]*)", paramName);

        RegexOptions options = RegexOptions.RightToLeft;
        // Querystring has parameters...
        if (Regex.IsMatch(queryString, regex, options))
        {
            queryString = Regex.Replace(queryString, regex, String.Format("$1{0}={1}", paramName, paramValue));
        }
        else
        {
            // If no querystring just return the Parameter Key/Value
            if (queryString == String.Empty)
            {
                return String.Format("{0}={1}", paramName, paramValue);
            }
            else
            {
                // Append the new parameter key/value to the end of querystring
                queryString = String.Format("{0}&{1}={2}", queryString, paramName, paramValue);
            }
        }
        return queryString;
    }
</code>```

Obviously you could use the QueryString NameValueCollection property of the URI object to make looking up the values easier, but we wanted to be able to parse any querystring.

Body:
I'm implementing a custom control and in this control I need to write a bunch of links to the current page, each one with a different query parameter. I need to keep existing query string intact, and add (or modify the value  of ) an extra query item (eg. "page"):

"Default.aspx?page=1"
"Default.aspx?page=2"
"Default.aspx?someother=true&page=2"

etc.

Is there a simple helper method that I can use  in the Render method  ... uhmm ... like:

Page.ClientScript.SomeURLBuilderMethodHere(this,"page","1");
Page.ClientScript.SomeURLBuilderMethodHere(this,"page","2");

That will take care of generating a correct URL, maintain existing query string items and not create duplicates  eg. page=1&page=2&page=3?

Rolling up my own seems like such an unappealing task.

Body:
I'm afraid I don't know of any built-in method for this, we use this method that takes the querystring and sets parameters

    /// <summary>
    /// Set a parameter value in a query string. If the parameter is not found in the passed in query string,
    /// it is added to the end of the query string
    /// </summary>
    /// <param name="queryString">The query string that is to be manipulated</param>
    /// <param name="paramName">The name of the parameter</param>
    /// <param name="paramValue">The value that the parameter is to be set to</param>
    /// <returns>The query string with the parameter set to the new value.</returns>
    public static string SetParameter(string queryString, string paramName, object paramValue)
    {
        //create the regex
        //match paramname=*
        //string regex = String.Format(@"{0}=[^&]*", paramName);
        string regex = @"([&?]{0,1})" + String.Format(@"({0}=[^&]*)", paramName);

        RegexOptions options = RegexOptions.RightToLeft;
        // Querystring has parameters...
        if (Regex.IsMatch(queryString, regex, options))
        {
            queryString = Regex.Replace(queryString, regex, String.Format("$1{0}={1}", paramName, paramValue));
        }
        else
        {
            // If no querystring just return the Parameter Key/Value
            if (queryString == String.Empty)
            {
                return String.Format("{0}={1}", paramName, paramValue);
            }
            else
            {
                // Append the new parameter key/value to the end of querystring
                queryString = String.Format("{0}&{1}={2}", queryString, paramName, paramValue);
            }
        }
        return queryString;
    }

Obviously you could use the QueryString NameValueCollection property of the URI object to make looking up the values easier, but we wanted to be able to parse any querystring.

OwnerDisplayName: Glenn Slaven


问:
Apache as intranet webserver with 'internet' content
I have a working Apache 2 set-up for intranet purposes.
The Apache server only needs to serve pages to local, intranet clients.
However, in these pages I would like to serve internet content. For example content from external RSS feeds in a feedreader like this one:

http://dev.sencha.com/deploy/dev/examples/feed-viewer/view.html

The Apache server is located on a Windows Server 2003.
Normal clients in the intranet zone connect to the internet via a proxy server.
A browser on this server also is able to connect to the internet.

My question is how to change my set-up so that Apache can get content from outside the local network without the need to serve pages outside the local intranet.

Regards,
Fabio

答: You can use Php curl to fetch external (internet) content.  http://php.net/manual/en/book.curl.php


问:
How to set list count in growing list/table title in ui5?
In sap.m.Table/List, I defined a title

```<code>            <Title
                id="lineItemsHeader"
                text="{tableView>/lineItemListTitle}"/>
</code>```

Get count logic is in updateFinished function,

```<code>        onListUpdateFinished : function (oEvent) {
            var sTitle,
                iTotalItems = oEvent.getParameter("total"),
                oViewModel = this.getModel("tableView");

            // only update the counter if the length is final
            if (this._oTable.getBinding("items").isLengthFinal()) {
                if (iTotalItems) {
                    sTitle = this.getResourceBundle().getText("DETAIL_TABLE_HEADING_COUNT", [iTotalItems]);
                } else {
                    //Display 'Line Items' instead of 'Line items (0)'
                    sTitle = this.getResourceBundle().getText("DETAIL_TABLE_HEADING");
                }
                oViewModel.setProperty("/lineItemListTitle", sTitle);
            }
        }
</code>```

But if I set growing="true", when data is more than 20 items(default growing threshold), this._oTable.getBinding("items").isLengthFinal() will return false.

So I came up an idea, use $count directly to get count data.

```<code>                this._oModel.read("/ControlSet/$count", {
                        success: this._updateListItemCount.bind(this),
                        error: this.errorCallback.bind(this)
                });
</code>```

But the question came up when I try to get count of filter result, I know the call is /ControlSet/$count?$filter=(substringof('a',name) or substringof('a',description)), and I've already maintain a filter state:

```<code>            this._oListFilterState = {
                aSearch : [new Filter...]
            };
</code>```

Did not find any clue in https://sapui5.hana.ondemand.com/#/api/sap.ui.model.Filter

Any suggestion? Try do fix this in an elegant/ui5 way, better not use        $.get

答:
On update finished event you can even use the below code also

```<code> updatingCount : function(oEvent){
            var tableCount = oEvent.getParameters().actual;
        }
</code>```

This can be used without hitting the $count service

Body:
In sap.m.Table/List, I defined a title

            <Title
                id="lineItemsHeader"
                text="{tableView>/lineItemListTitle}"/>

Get count logic is in updateFinished function,

        onListUpdateFinished : function (oEvent) {
            var sTitle,
                iTotalItems = oEvent.getParameter("total"),
                oViewModel = this.getModel("tableView");

            // only update the counter if the length is final
            if (this._oTable.getBinding("items").isLengthFinal()) {
                if (iTotalItems) {
                    sTitle = this.getResourceBundle().getText("DETAIL_TABLE_HEADING_COUNT", [iTotalItems]);
                } else {
                    //Display 'Line Items' instead of 'Line items (0)'
                    sTitle = this.getResourceBundle().getText("DETAIL_TABLE_HEADING");
                }
                oViewModel.setProperty("/lineItemListTitle", sTitle);
            }
        }

But if I set growing="true", when data is more than 20 items(default growing threshold), this._oTable.getBinding("items").isLengthFinal() will return false.

So I came up an idea, use $count directly to get count data.

                this._oModel.read("/ControlSet/$count", {
                        success: this._updateListItemCount.bind(this),
                        error: this.errorCallback.bind(this)
                });

But the question came up when I try to get count of filter result, I know the call is /ControlSet/$count?$filter=(substringof('a',name) or substringof('a',description)), and I've already maintain a filter state:

            this._oListFilterState = {
                aSearch : [new Filter...]
            };

Did not find any clue in https://sapui5.hana.ondemand.com/#/api/sap.ui.model.Filter

Any suggestion? Try do fix this in an elegant/ui5 way, better not use        $.get

Body:
On update finished event you can even use the below code also

 updatingCount : function(oEvent){
            var tableCount = oEvent.getParameters().actual;
        }

This can be used without hitting the $count service


问:
ionic 2 sounds stop background music while loading audio
I am working on a ionic 2 app and i need to add custom ringtone in my app for messages so i added Plugin: cordova-plugin-media  as well as Plugin: cordova-plugin-nativeaudio but it stop any other music player so i tried this js code

var mySound = new Audio('sounds/entering.mp3'); mySound.play();

it is working with many media players but is stop google play music and anothers music app.

also  i have tried

cordova add plugin cordova-allow-background-audio
but this is also not working for me.

Any ideas?

答:
After many try .. I fixed my problem with use code like as

```<code>var mySound = new Audio();
var mySound = new Audio('sounds/entering.mp3'); mySound.play();
</code>```

my issue was background music stop on first load.. so i am using like this load first blank.
now its work propely.

Body:
After many try .. I fixed my problem with use code like as

var mySound = new Audio();
var mySound = new Audio('sounds/entering.mp3'); mySound.play();

my issue was background music stop on first load.. so i am using like this load first blank.
now its work propely.


问:
Boolean logic for validation is failing
```<code>public static boolean isValidReferenceCode(String rc) {
    boolean validCode = true;
    if (rc.length() != 6 ) {
        validCode = false;
    } else if ( !Character.isLetter(rc.charAt(0)) ||
                !Character.isLetter(rc.charAt(1)) ||
                !Character.isDigit(rc.charAt(2)) ||
                !Character.isDigit(rc.charAt(3)) ||
                !Character.isDigit(rc.charAt(4)) ||
                !Character.isLetter(rc.charAt(5))) {
        validCode = false;
    } else if ( (!rc.substring(5).matches("B")) || (!rc.substring(5).matches("N")) ) {
        validCode = false;
    }
    return validCode;
}
</code>```

<p>This is my validation method inside a big program, I need a validation that requires the user to input at least 6 characters, first two being letters, next three being digits, and the last character either a "B" or "N" right now it's not doing that. After some trial and error, the first two IF statements seem to be correct and work when I delete the 3rd if statement about substrings, am I using the correct Syntax here? Would really appreciate help! </p>

答:
Instead of a cascade of ifs and negative logic, you can do the entire test more clearly in a single positive-logic expression:

```<code>public static boolean isValidReferenceCode(String rc) {
    return
       rc.length() == 6 &&
       Character.isLetter(rc.charAt(0)) &&
       Character.isLetter(rc.charAt(1)) &&
       Character.isDigit(rc.charAt(2)) &&
       Character.isDigit(rc.charAt(3)) &&
       Character.isDigit(rc.charAt(4)) &&
       (rc.charAt(5) == 'B' || rc.charAt(5) == 'N');
</code>```

Title: Boolean logic for validation is failing

Body:
public static boolean isValidReferenceCode(String rc) {
    boolean validCode = true;
    if (rc.length() != 6 ) {
        validCode = false;
    } else if ( !Character.isLetter(rc.charAt(0)) ||
                !Character.isLetter(rc.charAt(1)) ||
                !Character.isDigit(rc.charAt(2)) ||
                !Character.isDigit(rc.charAt(3)) ||
                !Character.isDigit(rc.charAt(4)) ||
                !Character.isLetter(rc.charAt(5))) {
        validCode = false;
    } else if ( (!rc.substring(5).matches("B")) || (!rc.substring(5).matches("N")) ) {
        validCode = false;
    }
    return validCode;
}

This is my validation method inside a big program, I need a validation that requires the user to input at least 6 characters, first two being letters, next three being digits, and the last character either a "B" or "N" right now it's not doing that. After some trial and error, the first two IF statements seem to be correct and work when I delete the 3rd if statement about substrings, am I using the correct Syntax here? Would really appreciate help!

Body:
Instead of a cascade of ifs and negative logic, you can do the entire test more clearly in a single positive-logic expression:

public static boolean isValidReferenceCode(String rc) {
    return
       rc.length() == 6 &&
       Character.isLetter(rc.charAt(0)) &&
       Character.isLetter(rc.charAt(1)) &&
       Character.isDigit(rc.charAt(2)) &&
       Character.isDigit(rc.charAt(3)) &&
       Character.isDigit(rc.charAt(4)) &&
       (rc.charAt(5) == 'B' || rc.charAt(5) == 'N');


问:
How to select a dropdown list element using webdriver selenium in python where it is of input type?
The HTML script is :

```<code>    <input id="ctl00_TableContentPlaceHolder_ddlAssignedTo_input"
    type="text" class="selectbox" autocomplete="off" readonly=""
    tabindex="0" style="width: 325px;">

    <ul id="the_list">
    <li id="ctl00_TableContentPlaceHolder_ddlAssignedTo_input_-1"
    class="">Please Select</li>
    <li id="ctl00_TableContentPlaceHolder_ddlAssignedTo_input_18">john</li>
    <li id="ctl00_TableContentPlaceHolder_ddlAssignedTo_input_20">erine</li>
    <li id="ctl00_TableContentPlaceHolder_ddlAssignedTo_input_22">devin</li>
</code>```

Here the user will give the name like john , erine or devin and i have to select that item from the list .Using selenium web driver in python 2.7 .

Here's my progress till now :

```<code>   import selenium
   from selenium.webdriver.common.action_chains import ActionChains
   from selenium.webdriver.support.select import Select
   elem = driver.find_element_by_xpath('//*
   [@id="ctl00_TableContentPlaceHolder_ddlAssignedTo_input"]')
   elem.send_keys(name)
</code>```

答:
You need to click drop-down first and then list item. </p>

```<code>import selenium
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select
driver.implicitly_wait(10)

elem = driver.find_element_by_xpath('//*[@id="the_list"]')
elem.click()

elem = driver.find_element_by_xpath('//*[text()=' + name + ']')
elem.click()
</code>```

Body:
The HTML script is :

    <input id="ctl00_TableContentPlaceHolder_ddlAssignedTo_input"
    type="text" class="selectbox" autocomplete="off" readonly=""
    tabindex="0" style="width: 325px;">

Please Select

john

erine

devin

Here the user will give the name like john , erine or devin and i have to select that item from the list .Using selenium web driver in python 2.7 .

Here's my progress till now :

   import selenium
   from selenium.webdriver.common.action_chains import ActionChains
   from selenium.webdriver.support.select import Select
   elem = driver.find_element_by_xpath('//*
   [@id="ctl00_TableContentPlaceHolder_ddlAssignedTo_input"]')
   elem.send_keys(name)

Body:
You need to click drop-down first and then list item.

import selenium
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.select import Select
driver.implicitly_wait(10)

elem = driver.find_element_by_xpath('//*[@id="the_list"]')
elem.click()

elem = driver.find_element_by_xpath('//*[text()=' + name + ']')
elem.click()


问:
Regex - grabbing all
 tags
Let's say that I have a string as so (not HTML-- from backend, I am recieving as string. I just formatted this way to be easier to read the dom tree):

```<code><ul>
    <li>
        <a href="link1">Link1</a>
        <a href="link2>Link2</a>
    </li>
    <li>
        <a href="link3">Link3</a>
        <a href="link4>Link4</a>
    </li>
</ul>
</code>```

How can I get grab inside li tags and retrieve as so :

```<code>[
    [<a href="link1">Link1</a>, <a href="link2>Link2</a>],
    [<a href="link3">Link3</a>,  <a href="link4>Link4</a>]
]
</code>```

I am assuming you need regex to achieve this (no jQuery).

答:
Wrap the string in a div and access the links using DOM methods.
It is NOT recommended to parse HTML with RegEx

var html = `

    Link1
    Link2

        Link3
        Link4

`;

var div = document.createElement('div');
div.innerHTML=html;

// version 1 - just get all links in the string/div
var linksCollection = div.querySelectorAll("a"); // will have some more stuff in it

// version 2 loop each LI and then each A
var lis = div.querySelectorAll("li"),liArr = [];
for (var i = 0; i < lis.length; i++) { // querySelectorAll is array-like
  var links = lis[i].querySelectorAll("a"), hrefArr=[];
  for (var j = 0; j < links.length; j++) {
    hrefArr.push(links[i].outerHTML);
  }
  liArr.push(hrefArr);
}
console.log(linksCollection)
console.log(liArr)```

Title: Regex - grabbing all <li> tags

Body:
Let's say that I have a string as so (not HTML-- from backend, I am recieving as string. I just formatted this way to be easier to read the dom tree):

        Link1
        Link2

        Link3
        Link4

How can I get grab inside li tags and retrieve as so :

[
    [Link1, Link2],
    [Link3,  Link4]
]

I am assuming you need regex to achieve this (no jQuery).

Body:
Wrap the string in a div and access the links using DOM methods.
It is NOT recommended to parse HTML with RegEx

var html = `<ul>
  <li>
    <a href="link1">Link1</a>
    <a href="link2">Link2</a>
    </li>
    <li>
        <a href="link3">Link3</a>
        <a href="link4">Link4</a>
  </li>
</ul>`;

var div = document.createElement('div');
div.innerHTML=html;

// version 1 - just get all links in the string/div
var linksCollection = div.querySelectorAll("a"); // will have some more stuff in it

// version 2 loop each LI and then each A
var lis = div.querySelectorAll("li"),liArr = [];
for (var i = 0; i < lis.length; i++) { // querySelectorAll is array-like
  var links = lis[i].querySelectorAll("a"), hrefArr=[];
  for (var j = 0; j < links.length; j++) {
    hrefArr.push(links[i].outerHTML);
  }
  liArr.push(hrefArr);
}
console.log(linksCollection)
console.log(liArr)


问:
NHibernate in C sharp
If possible to use NHibernate  in c#.net?How can use NHibernate  in c#?</p>

答:
NHibernate is exactly the .NET version of Hibernate for Java, designed exactly to be used with .NET.

there are many many many examples on how to set up a NHibernate project with c#, either for ASP.NET web application or for Windows Forms, google for it or search here for examples.

Title: NHibernate in C sharp


问:
Cross Domain SQL Server Logins Using Windows Authentication
I have a SQL Server 2005 named instance using Windows Authentication with domain groups serving as logins. The domain structures are as follows:

```<code>      Forest1                Forest2
      /      \                  |
Domain1       Domain2        Domain3
</code>```

Objects are organized in the following domains:

Forest1.Domain1

Users

Global Groups

Forest1.Domain2

SQL Server Instance

Domain Local Groups (serving as Logins)

Forest2.Domain3

Users

Global Groups

All my users exist in Domain1 and Domain3 but the SQL Server box exists in Domain2. As such, my logins are  domain groups in Domain2. When a user in Domain1 is added to a domain local group in Domain2 and attempts to connect using TCP/IP protocol to the SQL Server instance, he receives the following error message:

Cannot connect to <instance>. Login failed for user 'Domain1\userName'. (Microsoft SQL Server, Error: 18456)

Other things I've tried:

If I add the user as a login
explicitly, he can connect.

If I add a Domain1 global group of
which the user is a member as a login
explicitly, he can connect.

If I add a Domain1 global group of
which the user is a member as a
member of the Domain2 domain local
group used as a login, he cannot
connect.

EDIT: If I add the Domain2 domain local group to the Demote Desktop Users group on the Domain2 server hosting the SQL Server instance, the Domain1 user can successfully connect to the server - I can also connect to the instance locally as the Domain1 user (just not remotely).

EDIT: If I add the Domain2 domain local group to a local server group and create a SQL Server login for that local server group, the Domain1 user still cannot connect to the instance remotely.

EDIT: If I change the connection network protocol to "Named Pipes", the Domain1 user can successfully connect remotely.

From what I understand (referencing these TechNet articles: Group Scope and Nesting Groups), the domain group MUST be a domain local group in order to include users from both Domain1 and Domain3.

How can I use a domain group as a SQL Server login using Windows authentication such that the domain group can contain users from both Domain1 and Domain3 and users can connect remotely via TCP/IP?

MORE NOTES

The service account for the SQL Server named instance is a user account in Domain1

SPN's have been added for the service account (including server name and alias names)

UPDATE

Changing the SQL Service instance service account to be in Domain2 seems to have resolved the issue. I'll investigate further and post back my findings!

答:
Ok, I met the issue as well in 2017, hard to find any solution, finally, I figure it out only for my case.

My environment,

Forest 1 (Domain1) --- TRUST --- Forest 2(Domain2)

I have a service account in Domain2 trying to log in SQL server in Domain1 by using Windows Authentication.

And, following error message pops up.

Login failed. The login is from an untrusted domain and cannot be used with Windows authentication. (Microsoft SQL Server, Error: 18452)

The solution is simple enough, on domain1, open active directory domains and trusts tool,

Trusts -> outgoing trusts -> properties -> authentication -> change to "Forest-wide authentication"

My problem solved.

Body:
I have a SQL Server 2005 named instance using Windows Authentication with domain groups serving as logins. The domain structures are as follows:

      Forest1                Forest2
      /      \                  |
Domain1       Domain2        Domain3

Objects are organized in the following domains:

Forest1.Domain1

Users

Global Groups

Forest1.Domain2

SQL Server Instance

Domain Local Groups (serving as Logins)

Forest2.Domain3

Users

Global Groups

All my users exist in Domain1 and Domain3 but the SQL Server box exists in Domain2. As such, my logins are  domain groups in Domain2. When a user in Domain1 is added to a domain local group in Domain2 and attempts to connect using TCP/IP protocol to the SQL Server instance, he receives the following error message:

Cannot connect to <instance>. Login failed for user 'Domain1\userName'. (Microsoft SQL Server, Error: 18456)

Other things I've tried:

If I add the user as a login
explicitly, he can connect.

If I add a Domain1 global group of
which the user is a member as a login
explicitly, he can connect.

If I add a Domain1 global group of
which the user is a member as a
member of the Domain2 domain local
group used as a login, he cannot
connect.

EDIT: If I add the Domain2 domain local group to the Demote Desktop Users group on the Domain2 server hosting the SQL Server instance, the Domain1 user can successfully connect to the server - I can also connect to the instance locally as the Domain1 user (just not remotely).

EDIT: If I add the Domain2 domain local group to a local server group and create a SQL Server login for that local server group, the Domain1 user still cannot connect to the instance remotely.

EDIT: If I change the connection network protocol to "Named Pipes", the Domain1 user can successfully connect remotely.

From what I understand (referencing these TechNet articles: Group Scope and Nesting Groups), the domain group MUST be a domain local group in order to include users from both Domain1 and Domain3.

How can I use a domain group as a SQL Server login using Windows authentication such that the domain group can contain users from both Domain1 and Domain3 and users can connect remotely via TCP/IP?

MORE NOTES

The service account for the SQL Server named instance is a user account in Domain1

SPN's have been added for the service account (including server name and alias names)

UPDATE

Changing the SQL Service instance service account to be in Domain2 seems to have resolved the issue. I'll investigate further and post back my findings!


问:
jQuery - How can I allow both numpad and number key row input; as well as prevent special characters from being entered?
I want to allow both number pad numeric and oridinary number from keyboard. Currently, it only allows the number key row. I also only want numbers to be entered, but it currently allows special characters.

$(document).ready(function() {
  $('#price').keydown(function(event) {
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && event.which != 8) {
            event.preventDefault();
        }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='price'></code>```

答:
Updated your code </p>

```<code>$(document).ready(function() {
  $('#price').keydown(function(event) {
        if((event.which >= 48 && event.which <= 57) && event.shiftKey) {
            event.preventDefault();
        }
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && event.which != 8) {
            event.preventDefault();
        }
    });
});
</code>```

Body:
I want to allow both number pad numeric and oridinary number from keyboard. Currently, it only allows the number key row. I also only want numbers to be entered, but it currently allows special characters.

$(document).ready(function() {
  $('#price').keydown(function(event) {
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && event.which != 8) {
            event.preventDefault();
        }
    });
});

<input type='text' id='price'>

Body:
Updated your code

$(document).ready(function() {
  $('#price').keydown(function(event) {
        if((event.which >= 48 && event.which <= 57) && event.shiftKey) {
            event.preventDefault();
        }
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && event.which != 8) {
            event.preventDefault();
        }
    });
});


问:
Max Column for each Row
I'm an R novice, so I can't make a sample data frame for you, for which I apologize. However, I'm doing bacterial community analysis and I have a table that has species for each column and each sample for each row. Each column is an identifier for each species. Within the data frame is the species abundance for each sample. My goal is to identify the most abundant species (column) for each sample (row). I think making a data frame that has samples (rows) with the most abundant species column identifier would be the most useful!
Iterations I've tried (using phyloseq package, but can be used without this package).

```<code>beagle <- names(sort(taxa_sums(top.pdy.phyl),T, function(x) which(max==x)))
beagle2 <- names(taxa_sums(top.pdy.phyl),T, function(x) colnames(which.max(top.pdy.phyl))))
</code>```

Any help would be appreciated! Thank you!

答:
How about:

```<code>names(top.pdy.phyl)[ apply(top.pdy.phyl, 1, which.max) ]
</code>```

and

```<code>apply(top.pdy.phyl, 1 , max)
</code>```

Title: Max Column for each Row

Body:
I'm an R novice, so I can't make a sample data frame for you, for which I apologize. However, I'm doing bacterial community analysis and I have a table that has species for each column and each sample for each row. Each column is an identifier for each species. Within the data frame is the species abundance for each sample. My goal is to identify the most abundant species (column) for each sample (row). I think making a data frame that has samples (rows) with the most abundant species column identifier would be the most useful!
Iterations I've tried (using phyloseq package, but can be used without this package).

beagle <- names(sort(taxa_sums(top.pdy.phyl),T, function(x) which(max==x)))
beagle2 <- names(taxa_sums(top.pdy.phyl),T, function(x) colnames(which.max(top.pdy.phyl))))

Any help would be appreciated! Thank you!

Body:
How about:

names(top.pdy.phyl)[ apply(top.pdy.phyl, 1, which.max) ]

and

apply(top.pdy.phyl, 1 , max)


问:
Read the file and then create a dynamic array
I am trying to get the sum and the average of all numbers.
I am not getting any error or the right output.
Any help is appreciated</p>

```<code> #include <iostream>

 #include <fstream>

 #include <string>

 #include <iomanip>

 using namespace std;

 int main(){

    double temp;
    double total = 0.0;
    double avg;
    int counter = 0;

    ifstream file("dataFile.txt");
    while (file >> temp)
    {
    cout << temp << " " << endl;;
    ++counter;
    }
    cout << "Total number of elements: " << counter << endl;
    file.close();
    file.open("dataFile.txt");

    double *num = new double[counter]();

    for (int i = 0; i < counter; i++) {
    cin >> num[i];
    }
    for (int i = 0; i < counter; i++) {
    total += num[i];
    }
    avg = total / counter;

    cout << "\n\nTotal: " << total << endl;
    cout << "Average: " << avg << endl;
    delete[] num;
    num = 0;
    return 0;
}
</code>```

答: I think your issue is that you iterated through the whole file to get the size of the input, but your position in the file when you re-open it is still at the end. Check out this link to make it go back to the beginning before you re-open it.</p>

Body:
I am trying to get the sum and the average of all numbers.
I am not getting any error or the right output.
Any help is appreciated

 #include <iostream>

 #include <fstream>

 #include <string>

 #include <iomanip>

 using namespace std;

 int main(){

    double temp;
    double total = 0.0;
    double avg;
    int counter = 0;

    ifstream file("dataFile.txt");
    while (file >> temp)
    {
    cout << temp << " " << endl;;
    ++counter;
    }
    cout << "Total number of elements: " << counter << endl;
    file.close();
    file.open("dataFile.txt");

    double *num = new double[counter]();

    for (int i = 0; i < counter; i++) {
    cin >> num[i];
    }
    for (int i = 0; i < counter; i++) {
    total += num[i];
    }
    avg = total / counter;

    cout << "\n\nTotal: " << total << endl;
    cout << "Average: " << avg << endl;
    delete[] num;
    num = 0;
    return 0;
}


问:
HTMLCanvasContext.drawImage() failing when passed an image found using jQuery
The idea of my code is create a hidden div which loads the image. When it's load event is fired draw it in the canvas. When I run the code I get this error 0x80040111 (NS_ERROR_NOT_AVAILABLE), yet I am waiting for the load event. Here is my code.

HTML

```<code><div id="old-counties-image-wrapper" style="display: none;">
<img border="0" height="390" id="interreg-iiia-old-counties-map" src="/f/MISCELLANEOUS/old-map.jpg" /></div>
<p>
<canvas id="old-counties-image-canvas"></canvas></p>
</code>```

and javascript

```<code> $('#interreg-iiia-old-counties-map').load(function() {
    var canvas=document.getElementById('old-counties-image-canvas');
    if (canvas.getContext) {
         var ctx=canvas.getContext('2d');
         var img=$('#interreg-iiia-old-counties-map');
         ctx.drawImage(img, 0, 0);
    }
    //else {
    //    $('#old-counties-image-wrapper').show();
    //}
   });
</code>```

The else part is commented out for now but is there for browsers that don't support canvas.

答:
Because $('#interreg-iiia-old-counties-map') returns a jQuery object, while the drawImage method takes an Image object - the jQuery ($) function returns a jQuery object that wraps the original element to provide the usual jQuery functions you see.

You can get the underlying Image object by using the get method, but in this case it would be easier to just use this, which in the context of the callback function supplied to the load function, is the original $('#interreg-iiia-old-counties-map') DOM element. In other words,

```<code>ctx.drawImage(this, 0, 0);
</code>```

should work fine here. You also don't have to use a hidden  element - with new Image you can retrieve the image similar to what you're doing here:

```<code>var img = new Image(),
    canvas = document.getElementById('old-counties-image-canvas');
img.src = '/f/MISCELLANEOUS/old-map.jpg';

img.onload = function(){
    if (canvas.getContext) {
         var ctx = canvas.getContext('2d');
         ctx.drawImage(img, 0, 0);
    }
};
</code>```

Body:
The idea of my code is create a hidden div which loads the image. When it's load event is fired draw it in the canvas. When I run the code I get this error 0x80040111 (NS_ERROR_NOT_AVAILABLE), yet I am waiting for the load event. Here is my code.

HTML

<canvas id="old-counties-image-canvas"></canvas>

and javascript

 $('#interreg-iiia-old-counties-map').load(function() {
    var canvas=document.getElementById('old-counties-image-canvas');
    if (canvas.getContext) {
         var ctx=canvas.getContext('2d');
         var img=$('#interreg-iiia-old-counties-map');
         ctx.drawImage(img, 0, 0);
    }
    //else {
    //    $('#old-counties-image-wrapper').show();
    //}
   });

The else part is commented out for now but is there for browsers that don't support canvas.

Body:
Because $('#interreg-iiia-old-counties-map') returns a jQuery object, while the drawImage method takes an Image object - the jQuery ($) function returns a jQuery object that wraps the original element to provide the usual jQuery functions you see.

You can get the underlying Image object by using the get method, but in this case it would be easier to just use this, which in the context of the callback function supplied to the load function, is the original $('#interreg-iiia-old-counties-map') DOM element. In other words,

ctx.drawImage(this, 0, 0);

should work fine here. You also don't have to use a hidden <img> element - with new Image you can retrieve the image similar to what you're doing here:

var img = new Image(),
    canvas = document.getElementById('old-counties-image-canvas');
img.src = '/f/MISCELLANEOUS/old-map.jpg';

img.onload = function(){
    if (canvas.getContext) {
         var ctx = canvas.getContext('2d');
         ctx.drawImage(img, 0, 0);
    }
};