问:
The system cannot execute the specified program
I have Developed one console application for generating report in excel file format, in my machine it is working fine but when i am deploying it on server its showing

The system cannot execute the specified program

Please give me the solution.

答: Some tag was missing in the App.Config file, Placing proper tag works fine.</p>


来源: stackexchange

问:
iterm vs. zsh features
I'm confused on why I would need both iterm and zsh because from my understanding both just gives you coloring themes and shortcuts like gco instead of git checkout or is iterm more known for the former and zsh for the latter?

答:
You are comparing apples to oranges.

iTerm is an application that shows a terminal window. Inside that window a shell will be run. There are many different shells. One of those shells is zsh

When it comes to coloring, iTerm allows coloring in the shell. The shell itself must also allow coloring, most do by default these days. The shell could be configured to do coloring e.g. when running built in commands like ls (configured by the CLICOLOR and LSCOLORS variable).

By "shortcuts" I think you mean "aliases". Shells allow aliases to be set up. None are normally set up by default, but if you use some standard library for zsh like oh-my-zsh you will get many defaults.

ContentLicense: CC BY-SA 3.0

Title: iterm vs. zsh features

ContentLicense: CC BY-SA 4.0


问:
Show element if user starts typing
I am trying to show an element when the following criteria has been met:
1. The input is in focus
2. The input has 1 or more characters.

My jquery code so far (which doesn't work) is this...

$('input').click(function() {
  if (($(this).is(':focus')) && ($(this).val().length > 1)) {
    $(this).siblings('.show').fadeIn();
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: sans-serif;
  font-size: 16px;
  color: #5c5c5c;
  line-height: 22px;
}

main {
  max-width: 600px;
  margin: 20px auto;
  padding: 16px;
}

.group {
  margin-bottom: 16px;
  position: relative;
}

label {
  color: #393939;
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
}

input,
textarea {
  font-family: sans-serif;
  font-size: 16px;
  color: #5c5c5c;
  border-radius: 2px;
  border: 1px solid #ccc;
  width: 100%;
  padding: 12px;
  margin-bottom: 4px;
  -webkit-appearance: none;
  outline: none;
  transition: all 0.4s ease;
}

input:not(textarea) {
  height: 48px;
}

input:focus,
textarea:focus {
  box-shadow: inset 0 0 0 2px rgba(74, 168, 81, 1);
}

::placeholder {
  font-family: sans-serif;
  color: #bbb;
}

.hint {
  font-size: 14px;
  line-height: 20px;
  color: #727272;
  position: relative;
  top: -5px;
  opacity: 0;
  z-index: -1;
  transition: all 0.2s ease;
}

input:focus+.hint {
  opacity: 1;
  top: 0;
}

.show {
  font-size: 14px;
  line-height: 20px;
  display: none;
  position: absolute;
  top: 44px;
  right: 14px;
}</code>```

    Email
    <input type="text" id="email" placeholder="e.g. jamesgreen@gmail.com">

    Password
    <input type="password" id="password">

Password must have at least 8 characters, a lower case letter, an uppercase letter and a number

    SHOW

```

Not sure where I am going wrong, here is a link to the codepen

答:
You can use input event instead of click event and focus selector:

$('input').on('input', function(){
    if ($(this).val().length > 1) {
  $(this).siblings('.show').fadeIn();
 } else {
          $(this).siblings('.show').fadeOut();
    }
});
   ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}

body {
 font-family: sans-serif;
 font-size: 16px;
 color: #5c5c5c;
 line-height: 22px;
}

main {
 max-width: 600px;
 margin: 20px auto;
 padding: 16px;
}

.group {
 margin-bottom: 16px;
 position: relative;
}

label {
 color: #393939;
 display: block;
 margin-bottom: 8px;
 font-weight: bold;
}

input,
textarea {
 font-family: sans-serif;
 font-size: 16px;
 color: #5c5c5c;
 border-radius: 2px;
 border: 1px solid #ccc;
 width: 100%;
 padding: 12px;
 margin-bottom: 4px;
 -webkit-appearance: none;
 outline: none;
 transition: all 0.4s ease;
}

input:not(textarea){
 height: 48px;
}

input:focus,
textarea:focus {
 box-shadow: inset 0 0 0 2px rgba(74, 168, 81, 1);
}

::placeholder {
 font-family: sans-serif;
 color: #bbb;
}

.hint {
 font-size: 14px;
 line-height: 20px;
 color: #727272;
 position: relative;
 top: -5px;
 opacity: 0;
 z-index: -1;
 transition: all 0.2s ease;
}

input:focus + .hint {
 opacity: 1;
 top: 0;
}

.show {
 font-size: 14px;
 line-height: 20px;
 display: none;
 position: absolute;
    top: 44px;
    right: 14px;
}</code>```

  Email
     <input type="text" id="email" placeholder="e.g. jamesgreen@gmail.com">

  Password
     <input type="password" id="password">

Password must have at least 8 characters, a lower case letter, an uppercase letter and a number

     SHOW

```

Title: Show element if user starts typing

Body:
I am trying to show an element when the following criteria has been met:
1. The input is in focus
2. The input has 1 or more characters.

My jquery code so far (which doesn't work) is this...

$('input').click(function() {
  if (($(this).is(':focus')) && ($(this).val().length > 1)) {
    $(this).siblings('.show').fadeIn();
  }
});

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: sans-serif;
  font-size: 16px;
  color: #5c5c5c;
  line-height: 22px;
}

main {
  max-width: 600px;
  margin: 20px auto;
  padding: 16px;
}

.group {
  margin-bottom: 16px;
  position: relative;
}

label {
  color: #393939;
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
}

input,
textarea {
  font-family: sans-serif;
  font-size: 16px;
  color: #5c5c5c;
  border-radius: 2px;
  border: 1px solid #ccc;
  width: 100%;
  padding: 12px;
  margin-bottom: 4px;
  -webkit-appearance: none;
  outline: none;
  transition: all 0.4s ease;
}

input:not(textarea) {
  height: 48px;
}

input:focus,
textarea:focus {
  box-shadow: inset 0 0 0 2px rgba(74, 168, 81, 1);
}

::placeholder {
  font-family: sans-serif;
  color: #bbb;
}

.hint {
  font-size: 14px;
  line-height: 20px;
  color: #727272;
  position: relative;
  top: -5px;
  opacity: 0;
  z-index: -1;
  transition: all 0.2s ease;
}

input:focus+.hint {
  opacity: 1;
  top: 0;
}

.show {
  font-size: 14px;
  line-height: 20px;
  display: none;
  position: absolute;
  top: 44px;
  right: 14px;
}

    Email
    <input type="text" id="email" placeholder="e.g. jamesgreen@gmail.com">

    Password
    <input type="password" id="password">

Password must have at least 8 characters, a lower case letter, an uppercase letter and a number

    SHOW

Not sure where I am going wrong, here is a link to the codepen

Body:
You can use input event instead of click event and focus selector:

$('input').on('input', function(){
    if ($(this).val().length > 1) {
  $(this).siblings('.show').fadeIn();
 } else {
          $(this).siblings('.show').fadeOut();
    }
});

* {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}

body {
 font-family: sans-serif;
 font-size: 16px;
 color: #5c5c5c;
 line-height: 22px;
}

main {
 max-width: 600px;
 margin: 20px auto;
 padding: 16px;
}

.group {
 margin-bottom: 16px;
 position: relative;
}

label {
 color: #393939;
 display: block;
 margin-bottom: 8px;
 font-weight: bold;
}

input,
textarea {
 font-family: sans-serif;
 font-size: 16px;
 color: #5c5c5c;
 border-radius: 2px;
 border: 1px solid #ccc;
 width: 100%;
 padding: 12px;
 margin-bottom: 4px;
 -webkit-appearance: none;
 outline: none;
 transition: all 0.4s ease;
}

input:not(textarea){
 height: 48px;
}

input:focus,
textarea:focus {
 box-shadow: inset 0 0 0 2px rgba(74, 168, 81, 1);
}

::placeholder {
 font-family: sans-serif;
 color: #bbb;
}

.hint {
 font-size: 14px;
 line-height: 20px;
 color: #727272;
 position: relative;
 top: -5px;
 opacity: 0;
 z-index: -1;
 transition: all 0.2s ease;
}

input:focus + .hint {
 opacity: 1;
 top: 0;
}

.show {
 font-size: 14px;
 line-height: 20px;
 display: none;
 position: absolute;
    top: 44px;
    right: 14px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
  <div class="group">
  <label for="email">Email</label>
     <input type="text" id="email" placeholder="e.g. jamesgreen@gmail.com">
 </div>

 <div class="group">
  <label for="password">Password</label>
     <input type="password" id="password">
     <p class="hint">Password must have at least 8 characters, a lower case letter, an uppercase letter and a number</p>
     <span class="show">SHOW</span>
 </div>
</main>


问:
Excel: Count how many text values in a column of data are Alpha only, Alphanumeric and All Types
Say I have a column with 10,000 entries. I want to count how many of these entries  contain letters only, numbers and letters, and finally everything else. Note that all data is stored as text, not as numbers. </p>

答:
I tested the following and it seemed to work.

Note to get this to work you need to add a reference to Microsoft VBScript Regular Expressions 5.5 from within the VB editor:

Tools > References > Microsoft VBScript Regular Expressions 5.5

```<code>Sub CountTextPatterns()
Dim rngToCheck As Range
Dim cl As Range

Set rngToCheck = Range("A1:A10000") //Set up the range that contains the text data

Dim numbersLetters As VBScript_RegExp_55.RegExp
Set numbersLetters = New RegExp
numbersLetters.Pattern = "^\d*[a-zA-Z][a-zA-Z0-9]*$" //Regex pattern to match alphanumeric with at least one letter

Dim lettersOnly As VBScript_RegExp_55.RegExp
Set lettersOnly = New RegExp
lettersOnly.Pattern = "^[a-zA-Z]+$" //Regex pattern for letters only

Dim cntNumbersLetters As Long, cntLetters As Long, cntRemainder As Long
cntNumbersLetters = cntLetters = cntRemainder = 0

//Loop through range, match cell contents to pattern, and increment count accordingly
For Each cl In rngToCheck
    If lettersOnly.Test(cl) Then
        cntLetters = cntLetters + 1
    ElseIf numbersLetters.Test(cl) Then
        cntNumbersLetters = cntNumbersLetters + 1
    End If
Next

//For anything that isn't letters only or numbers and letters, simply subtract from counts and total row count
cntRemainder = rngToCheck.Rows.Count - cntNumbersLetters - cntLetters

Debug.Print "Numbers and Letters = " & cntNumbersLetters & vbTab & "Letters = " & cntLetters & vbTab & "Remainder = " & cntRemainder

End Sub
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I tested the following and it seemed to work.

Note to get this to work you need to add a reference to Microsoft VBScript Regular Expressions 5.5 from within the VB editor:

Tools > References > Microsoft VBScript Regular Expressions 5.5

Sub CountTextPatterns()
Dim rngToCheck As Range
Dim cl As Range

Set rngToCheck = Range("A1:A10000") //Set up the range that contains the text data

Dim numbersLetters As VBScript_RegExp_55.RegExp
Set numbersLetters = New RegExp
numbersLetters.Pattern = "^\d*[a-zA-Z][a-zA-Z0-9]*$" //Regex pattern to match alphanumeric with at least one letter

Dim lettersOnly As VBScript_RegExp_55.RegExp
Set lettersOnly = New RegExp
lettersOnly.Pattern = "^[a-zA-Z]+$" //Regex pattern for letters only

Dim cntNumbersLetters As Long, cntLetters As Long, cntRemainder As Long
cntNumbersLetters = cntLetters = cntRemainder = 0

//Loop through range, match cell contents to pattern, and increment count accordingly
For Each cl In rngToCheck
    If lettersOnly.Test(cl) Then
        cntLetters = cntLetters + 1
    ElseIf numbersLetters.Test(cl) Then
        cntNumbersLetters = cntNumbersLetters + 1
    End If
Next

//For anything that isn't letters only or numbers and letters, simply subtract from counts and total row count
cntRemainder = rngToCheck.Rows.Count - cntNumbersLetters - cntLetters

Debug.Print "Numbers and Letters = " & cntNumbersLetters & vbTab & "Letters = " & cntLetters & vbTab & "Remainder = " & cntRemainder

End Sub


问:
Where to find bootstrap classes' css definitons?
What I want is, for example, to change the css background color of navigations bar of .navbar-default, which can be done by .navbar-default{background-color:#000;}

But I want is, to see the full css style definitions of .navbar-default class, so I can look and change every element(text-color, hovering colors and every other thing) as I like. Rather than inspecting webpage elements for css codes from browsers, I want to look in a place where the definitions contain.

答: You can find all in readable format here</p>


问:
Create Matrix with gaussian-distributed ellipsis in python
I have a 100x100 Matrix with Zeros. I want to add a 10x20 ellipsis around a specific point in the Matrix - lets say at position 40,60. The Ellipsis should be filled with values from 0 to 1. (1 in the center - 0 at the edge) - The numbers should be gaussian-distributed.
Maybe someone can give me a clue, how to start with this problem..</p>

答:
You need to draw samples from a multi-variate gaussian distribution. The function you can use is numpy.random.multivariate_normal

You mean value matrix should be [40, 60]. The covariance C matrix should be 2X2. Regarding its values:

C[1, 1], C[2, 2]: decides the width of the ellipse along each axis. Choose it so that 3*C[i,i] is almost equal to the width of the ellipse along this axis.

The diagonal values are zero if you want the ellipse to be along the axes, otherwise put larger values (keep in mind that C[2, 1]==C[1, 2]

However, keep in mind that, since it is a Gaussian distribution, the output values will be close to 0 at distance 3*C[i,i] from the center, but they will never be truly zero.


问:
C# How can I prevent in this code that this error message occurs: Sequence contains no elements?
I have two Dictionaries. One with a list of columns from an Excel sheet and a list of defined columns. I wanna know if the defined columns exists in the sheet. If they exists then they will selected in a chosen dropdownlist.

In the row dropdownList.SelectedValue = selectedItem.First().Key; I get sometimes an errormessage Sequence contains no elements. I thought that I had coded safety. What do I forget?

... the command ...

```<code>SetDataSource(import.ColumnList, import.DefColumnList, ddlSomeColumn, SomeEnum.Zipcode);
</code>```

... and then the calling method ...

```<code>    private void SetDataSource(Dictionary<int, string> columnList, Dictionary<int, string> defColumnList, DropDownList dropdownList, SomeEnum item)
    {
        int index = (int)item;
        dropdownList.BeginUpdate();
        dropdownList.ValueMember = "Key";
        dropdownList.DisplayMember = "Value";
        dropdownList.DataSource = columnList;
        if (defColumnList.ContainsKey(index) && defColumnList[index].Length > 0)
        {
            var selectedItem = columnList.Where(cl => cl.Value == defColumnList[index]);
            if (selectedItem != null)
                dropdownList.SelectedValue = selectedItem.First().Key;
        }
        dropdownList.EndUpdate();
    }
</code>```

答:
.Where() operator returns an enumeration, and not a single element. So, your selectedeItem!=null condition always returns true. Change your code to this:</p>

```<code>private void SetDataSource(Dictionary<int, string> columnList, Dictionary<int, string> defColumnList, DropDownList dropdownList, SomeEnum item)
    {
        int index = (int)item;
        dropdownList.BeginUpdate();
        dropdownList.ValueMember = "Key";
        dropdownList.DisplayMember = "Value";
        dropdownList.DataSource = columnList;
        if (defColumnList.ContainsKey(index) && defColumnList[index].Length > 0)
        {
            var selectedItem = columnList.FirstOrDefault(cl => cl.Value == defColumnList[index]);
            if (selectedItem != null)
                dropdownList.SelectedValue = selectedItem.Key;
        }
        dropdownList.EndUpdate();
    }
</code>```

Body:
I have two Dictionaries. One with a list of columns from an Excel sheet and a list of defined columns. I wanna know if the defined columns exists in the sheet. If they exists then they will selected in a chosen dropdownlist.

In the row dropdownList.SelectedValue = selectedItem.First().Key; I get sometimes an errormessage Sequence contains no elements. I thought that I had coded safety. What do I forget?

... the command ...

SetDataSource(import.ColumnList, import.DefColumnList, ddlSomeColumn, SomeEnum.Zipcode);

... and then the calling method ...

    private void SetDataSource(Dictionary<int, string> columnList, Dictionary<int, string> defColumnList, DropDownList dropdownList, SomeEnum item)
    {
        int index = (int)item;
        dropdownList.BeginUpdate();
        dropdownList.ValueMember = "Key";
        dropdownList.DisplayMember = "Value";
        dropdownList.DataSource = columnList;
        if (defColumnList.ContainsKey(index) && defColumnList[index].Length > 0)
        {
            var selectedItem = columnList.Where(cl => cl.Value == defColumnList[index]);
            if (selectedItem != null)
                dropdownList.SelectedValue = selectedItem.First().Key;
        }
        dropdownList.EndUpdate();
    }

Body:
.Where() operator returns an enumeration, and not a single element. So, your selectedeItem!=null condition always returns true. Change your code to this:

private void SetDataSource(Dictionary<int, string> columnList, Dictionary<int, string> defColumnList, DropDownList dropdownList, SomeEnum item)
    {
        int index = (int)item;
        dropdownList.BeginUpdate();
        dropdownList.ValueMember = "Key";
        dropdownList.DisplayMember = "Value";
        dropdownList.DataSource = columnList;
        if (defColumnList.ContainsKey(index) && defColumnList[index].Length > 0)
        {
            var selectedItem = columnList.FirstOrDefault(cl => cl.Value == defColumnList[index]);
            if (selectedItem != null)
                dropdownList.SelectedValue = selectedItem.Key;
        }
        dropdownList.EndUpdate();
    }


问:
KnockoutJS calling observable properties
In KnockoutJS, why we need to call the observable member of a view model as a function, for instance in the below snippet while retrieving the values of currentProfit is called as currentProfit().  Any pointers will be helpful.

Thanks

```<code>var viewModel = {
        currentProfit: ko.observable(150000)
    };

 viewModel.profitStatus = ko.pureComputed(function() {
        return this.currentProfit() < 0 ? "profitWarning" : "profitPositive";
    }, viewModel);
</code>```

答:
I see you've already found out why knockout uses the pattern it does, but it might be fun to explore if it can be changed. Especially since the main reason was to support older browsers.

Here's a quick exploration of how you could use your observable's default methods inside a get and set. If you'd want to, I'm sure you'll be able to extend this to also use ko.computeds (typeof model[prop] === "function") and ko.observableArrays (Array.isArray(model[prop])).

If anybody has some more knowledge on Object.defineProperty and how to make subscribe and other methods accessible, please feel free to add to this answer/comment. Personally, I'd be very interested in a new version of knockout supporting this syntax :)

const viewModel = {
  currentProfit: 1500
};

const makeObsGetSet = (model, prop) => {
  const innerObs = ko.observable(model[prop]);

  Object.defineProperty(model, prop, {
    get: innerObs,
    set: innerObs
  });

  return model;
};

// Mutate the vm to have obs. property
makeObsGetSet(viewModel, "currentProfit");

console.log("get without ():", viewModel.currentProfit);

// Subscribe to show it worked:
// (if anybody knows of an easier way to make subscribe
// accessible from the outside, let me know!)
Object.getOwnPropertyDescriptor(viewModel, "currentProfit").get.subscribe(
    v => console.log("New currentProfit value:", v)
);

// Write using `= 2000` instead of `(2000)`
viewModel.currentProfit = 2000;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script></code>```

Body:
In KnockoutJS, why we need to call the observable member of a view model as a function, for instance in the below snippet while retrieving the values of currentProfit is called as currentProfit().  Any pointers will be helpful.

Thanks

var viewModel = {
        currentProfit: ko.observable(150000)
    };

 viewModel.profitStatus = ko.pureComputed(function() {
        return this.currentProfit() < 0 ? "profitWarning" : "profitPositive";
    }, viewModel);

Body:
I see you've already found out why knockout uses the pattern it does, but it might be fun to explore if it can be changed. Especially since the main reason was to support older browsers.

Here's a quick exploration of how you could use your observable's default methods inside a get and set. If you'd want to, I'm sure you'll be able to extend this to also use ko.computeds (typeof model[prop] === "function") and ko.observableArrays (Array.isArray(model[prop])).

If anybody has some more knowledge on Object.defineProperty and how to make subscribe and other methods accessible, please feel free to add to this answer/comment. Personally, I'd be very interested in a new version of knockout supporting this syntax :)

const viewModel = {
  currentProfit: 1500
};

const makeObsGetSet = (model, prop) => {
  const innerObs = ko.observable(model[prop]);

  Object.defineProperty(model, prop, {
    get: innerObs,
    set: innerObs
  });

  return model;
};

// Mutate the vm to have obs. property
makeObsGetSet(viewModel, "currentProfit");

console.log("get without ():", viewModel.currentProfit);

// Subscribe to show it worked:
// (if anybody knows of an easier way to make subscribe
// accessible from the outside, let me know!)
Object.getOwnPropertyDescriptor(viewModel, "currentProfit").get.subscribe(
    v => console.log("New currentProfit value:", v)
);

// Write using `= 2000` instead of `(2000)`
viewModel.currentProfit = 2000;

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>


问:
CDI: Two producers
I have to producers:

```<code>@Produces
public IPaymentGateway getStripePaymentGateway(@StripeApiKey final String apiKey) {
   return new StripeFluentAPI(apiKey);
}

@Produces
public IPaymentGateway getStripePaymentGatewayProxy() {
    IPaymentGateway gateway = mock(IPaymentGateway.class);
    ICustomer customer = mock(ICustomer.class);

    when(gateway.customer()).thenReturn(customer);

    return gateway;
}
</code>```

The first one returns a real implementation of my IPaymentGateway. By other side, the second one returns a proxied object.

I'm using an @ApplicationScoped object in order to know if the gateway has to be enabled or disabled:

```<code>@ApplicationScoped
public class ConfigurationResources {
    public boolean isPaymentGatewayEnabled() {
        return paymentGatewayEnabled;
    }
}
</code>```

So, I'd like to know how to select on or other producers according isPaymentGatewayEnabled value.

答:
Since your ConfigurationResources is a CDI bean (@ApplicationScoped) it is also injectable. You can make use of that and go for producer injection in approximately this way:

```<code>@Produces
public IPaymentGateway getStripePaymentGateway(@StripeApiKey final String apiKey, ConfigurationResources configResource) {
   if (configResource.isEnabled()) {
     return new StripeFluentAPI(apiKey);
   } else {
     IPaymentGateway gateway = mock(IPaymentGateway.class);
     ICustomer customer = mock(ICustomer.class);
     when(gateway.customer()).thenReturn(customer);
     return gateway;
   }
}
</code>```

Therefore, this will create a result based on configResource.isEnabled().

Title: CDI: Two producers

Body:
I have to producers:

@Produces
public IPaymentGateway getStripePaymentGateway(@StripeApiKey final String apiKey) {
   return new StripeFluentAPI(apiKey);
}

@Produces
public IPaymentGateway getStripePaymentGatewayProxy() {
    IPaymentGateway gateway = mock(IPaymentGateway.class);
    ICustomer customer = mock(ICustomer.class);

    when(gateway.customer()).thenReturn(customer);

    return gateway;
}

The first one returns a real implementation of my IPaymentGateway. By other side, the second one returns a proxied object.

I'm using an @ApplicationScoped object in order to know if the gateway has to be enabled or disabled:

@ApplicationScoped
public class ConfigurationResources {
    public boolean isPaymentGatewayEnabled() {
        return paymentGatewayEnabled;
    }
}

So, I'd like to know how to select on or other producers according isPaymentGatewayEnabled value.

Body:
Since your ConfigurationResources is a CDI bean (@ApplicationScoped) it is also injectable. You can make use of that and go for producer injection in approximately this way:

@Produces
public IPaymentGateway getStripePaymentGateway(@StripeApiKey final String apiKey, ConfigurationResources configResource) {
   if (configResource.isEnabled()) {
     return new StripeFluentAPI(apiKey);
   } else {
     IPaymentGateway gateway = mock(IPaymentGateway.class);
     ICustomer customer = mock(ICustomer.class);
     when(gateway.customer()).thenReturn(customer);
     return gateway;
   }
}

Therefore, this will create a result based on configResource.isEnabled().


问:
Android in service how to know when screen is locked?
I want to handle an Androids application work in the background. I've read that I have to use services for this.
In this application, I need to know when the screen gets locked and when it gets unlocked again. Every time this happens, I have to do some actions.

For activities, I've seen we have onPause and onRestart for this, but I need to know when the screen is turned off and when it is turned on in a service. How can this information be retrieved from inside a service.

答:
You can use this

```<code>KeyguardManager keyguardManager = (KeyguardManager)
context.getSystemService(Context.KEYGUARD_SERVICE);
if( keyguardManager.inKeyguardRestrictedInputMode()) {
  //it is locked
  } else {
  //it is not locked
}
</code>```

Hope this helps.

Body:
You can use this

KeyguardManager keyguardManager = (KeyguardManager)
context.getSystemService(Context.KEYGUARD_SERVICE);
if( keyguardManager.inKeyguardRestrictedInputMode()) {
  //it is locked
  } else {
  //it is not locked
}

Hope this helps.


问:
How to draw polylines from Google Directions Api
I'm trying to draw a polyline from what the Google Directions Api returns, the api has this field, overview_polyline, I'm assuming that this field contains the entire polyline so I was thinking why not draw the polyline from there, this is what I have in my JSON, from Google:

```<code>{
     geocoded_waypoints: [
        {},
        {}
     ],
     routes: [
        {
           bounds: {},
           copyrights: "Dados do mapa ©2017 Google, Inst. Geogr. Nacional",
           legs: [],
           overview_polyline: {
               points: "cxwnFtdct@dAQlAf@fAf@|Aq@l@]pCcFhCjA|LfJlAT~@IpDi@jAb@f@HXi@t@kBhBeBx@Qz@z@dClHzFpW`H|RvTpj@`AxAdBdAnAXhB?fBk@rAcAnG_HhCgAjAKrATbA`Al@lBHnAc@rFgBhIkCxMBfIlBvHnBtCnB|AnEdCrJxFj@fB@h@OhAgCtHGfCl@jAlA\jE]tDBzBb@tLxFtK~E`d@hShIzEtDhDxDrEfDpFlFjNvDtRdDjThF`TzH`QhEhG|EvFhL`JpJtE|LpEdOpFjOzGlPfJlHzE~NjLfQvPfP|RtHrKxDjGfI|NdHbOvGjPfCbHpCtIvJh_@vG|[|CtNvFvSvE~MfI|QzLbTfNxQbKlKrRzP|NnNvNlQjIzMnLfV`T|h@nDbHhIdMxFjH~JrMnEfHzIrQfHvOtEjI|MnQfNzP`FzI~EnLrKp[nDlHvErHzL~MbRbM`EjCjFxEtRnX|D~EjIhI~WrRxGlGdFnG`JjNxHzKfTxVfKfRfMbRlErHtBlFxIjYvHnPpBtFxF~WpCjHjGhJfDzClF~CnDlArDl@pC\vHXvX[lOaB|GcBdFqBxQwJbDmAxE_ApJ_@jEXtItBrQ~EbQbDlUfBpMfA|IxCbF`DhGlGnJjKtJrF`SpFbRnDdUxAbGrAlEjBnFpDtNnMfGlE~[lTbRdQjTpUxH`GjHfEnGlC`O|DrUxEnEzAfFrBnSpIjPnDxSlAf\lAl~@hDzRrAjOpBvKrBrQtEv^pM``@rPrR|JxSdMlGnGfGtH~HxFdFlBtGfApGp@bG|AnHxD|FzFrH`L~FvH|HrFrFtBtFjA~Mt@pHR|FhA`IfDpEbDzFxGrHrKhEtErF`EnS`MzMvItSdUfF~DtE~B|SrInEnBzDtCxN`QpQfVtQ~Yjn@~fAnK`RvLlRzEjF|GlFrc@vUfRjKfIvGxDhEjIxKdN~T`L~MrFvE~LhIlp@fb@xCtBzFtFbEzFbDrGhH`TfF|JnGfHzEdD|UdIpTdHtKtFj]nUrEzC~[pTfLfG|EbB~KfCnTvDpmAxSzs@~LhOfDzOdFfOxGdY`O`k@zYnVzMlK|HrFjFbXj[rCbCvDfB|FfBbD^xRBlb@nBrIdArJvDfD|B|FzFvFzHnCbIDrCk@dA_A_@q@mHz@sAvAJ^f@r@n@x@UR_@fBGjET`S~@ro@pCpXpAfFp@dEhCnGtE@HXl@n@H^W|ASpShAbZxAtPp@~SjAzGZKdDStBd@x@dC@nEVz@HtAp@b@\OZ|AbBxDnFJf@"
           },
           summary: "A1",
           warnings: [ ],
           waypoint_order: [ ]
        }
     ],
     status: "OK"
 }
</code>```

How do I draw with that value?

答:
This help me,you can use it..
Firstly create a google server key from google developer account

```<code>GoogleDirection.withServerKey(getResources().getString(R.string.SERVER_KEY))
                        .from(SourceLatlng)
                        .to(DestinationLatlng)
                        .execute(new DirectionCallback() {
                            @Override
                            public void onDirectionSuccess(Direction direction, String message) {
                                if (direction.isOK()) {
                                    routeSucess2(direction, message,SourceLatlng,DestinationLatlng);
                                } else {
                                    //selectedRawLine = ERROR;
                                }

                            }

                            @Override
                            public void onDirectionFailure(Throwable t) {
                                t.printStackTrace();
                            }
                        });
</code>```

then draw a route using google direction

```<code> private void routeSucess2(Direction direction, String message,LatLng sourceLatlng,LatLng DestinationLng) {

        for (Route route : direction.getRouteList()) {
            PolylineOptions polyoptions = new PolylineOptions();
            polyoptions.color(getResources().getColor(R.color.primary__dark));
            polyoptions.width(5);
            polyoptions.addAll(route.getOverviewPolyline().getPointList());
            poly = googleMap.addPolyline(polyoptions);
            poly.setClickable(true);

        }
        LatLngBounds.Builder latLngBuilder = new LatLngBounds.Builder();
        if(sourceLatlng!=null)
        latLngBuilder.include(sourceLatlng);
        if(DestinationLng!=null)
        latLngBuilder.include(DestinationLng);

        try {
            LatLngBounds bounds = latLngBuilder.build();
            CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds,
                    UiHelper.dpToPixel(getActivity(), 135));
            googleMap.animateCamera(cu);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
</code>```

This would help you.

Body:
I'm trying to draw a polyline from what the Google Directions Api returns, the api has this field, overview_polyline, I'm assuming that this field contains the entire polyline so I was thinking why not draw the polyline from there, this is what I have in my JSON, from Google:

{
     geocoded_waypoints: [
        {},
        {}
     ],
     routes: [
        {
           bounds: {},
           copyrights: "Dados do mapa ©2017 Google, Inst. Geogr. Nacional",
           legs: [],
           overview_polyline: {
               points: "cxwnFtdct@dAQlAf@fAf@|Aq@l@]pCcFhCjA|LfJlAT~@IpDi@jAb@f@HXi@t@kBhBeBx@Qz@z@dClHzFpW`H|RvTpj@`AxAdBdAnAXhB?fBk@rAcAnG_HhCgAjAKrATbA`Al@lBHnAc@rFgBhIkCxMBfIlBvHnBtCnB|AnEdCrJxFj@fB@h@OhAgCtHGfCl@jAlA\jE]tDBzBb@tLxFtK~E`d@hShIzEtDhDxDrEfDpFlFjNvDtRdDjThF`TzH`QhEhG|EvFhL`JpJtE|LpEdOpFjOzGlPfJlHzE~NjLfQvPfP|RtHrKxDjGfI|NdHbOvGjPfCbHpCtIvJh_@vG|[|CtNvFvSvE~MfI|QzLbTfNxQbKlKrRzP|NnNvNlQjIzMnLfV`T|h@nDbHhIdMxFjH~JrMnEfHzIrQfHvOtEjI|MnQfNzP`FzI~EnLrKp[nDlHvErHzL~MbRbM`EjCjFxEtRnX|D~EjIhI~WrRxGlGdFnG`JjNxHzKfTxVfKfRfMbRlErHtBlFxIjYvHnPpBtFxF~WpCjHjGhJfDzClF~CnDlArDl@pC\vHXvX[lOaB|GcBdFqBxQwJbDmAxE_ApJ_@jEXtItBrQ~EbQbDlUfBpMfA|IxCbF`DhGlGnJjKtJrF`SpFbRnDdUxAbGrAlEjBnFpDtNnMfGlE~[lTbRdQjTpUxH`GjHfEnGlC`O|DrUxEnEzAfFrBnSpIjPnDxSlAf\lAl~@hDzRrAjOpBvKrBrQtEv^pM``@rPrR|JxSdMlGnGfGtH~HxFdFlBtGfApGp@bG|AnHxD|FzFrH`L~FvH|HrFrFtBtFjA~Mt@pHR|FhA`IfDpEbDzFxGrHrKhEtErF`EnS`MzMvItSdUfF~DtE~B|SrInEnBzDtCxN`QpQfVtQ~Yjn@~fAnK`RvLlRzEjF|GlFrc@vUfRjKfIvGxDhEjIxKdN~T`L~MrFvE~LhIlp@fb@xCtBzFtFbEzFbDrGhH`TfF|JnGfHzEdD|UdIpTdHtKtFj]nUrEzC~[pTfLfG|EbB~KfCnTvDpmAxSzs@~LhOfDzOdFfOxGdY`O`k@zYnVzMlK|HrFjFbXj[rCbCvDfB|FfBbD^xRBlb@nBrIdArJvDfD|B|FzFvFzHnCbIDrCk@dA_A_@q@mHz@sAvAJ^f@r@n@x@UR_@fBGjET`S~@ro@pCpXpAfFp@dEhCnGtE@HXl@n@H^W|ASpShAbZxAtPp@~SjAzGZKdDStBd@x@dC@nEVz@HtAp@b@\OZ|AbBxDnFJf@"
           },
           summary: "A1",
           warnings: [ ],
           waypoint_order: [ ]
        }
     ],
     status: "OK"
 }

How do I draw with that value?

Body:
This help me,you can use it..
Firstly create a google server key from google developer account

GoogleDirection.withServerKey(getResources().getString(R.string.SERVER_KEY))
                        .from(SourceLatlng)
                        .to(DestinationLatlng)
                        .execute(new DirectionCallback() {
                            @Override
                            public void onDirectionSuccess(Direction direction, String message) {
                                if (direction.isOK()) {
                                    routeSucess2(direction, message,SourceLatlng,DestinationLatlng);
                                } else {
                                    //selectedRawLine = ERROR;
                                }

                            }

                            @Override
                            public void onDirectionFailure(Throwable t) {
                                t.printStackTrace();
                            }
                        });

then draw a route using google direction

 private void routeSucess2(Direction direction, String message,LatLng sourceLatlng,LatLng DestinationLng) {

        for (Route route : direction.getRouteList()) {
            PolylineOptions polyoptions = new PolylineOptions();
            polyoptions.color(getResources().getColor(R.color.primary__dark));
            polyoptions.width(5);
            polyoptions.addAll(route.getOverviewPolyline().getPointList());
            poly = googleMap.addPolyline(polyoptions);
            poly.setClickable(true);

        }
        LatLngBounds.Builder latLngBuilder = new LatLngBounds.Builder();
        if(sourceLatlng!=null)
        latLngBuilder.include(sourceLatlng);
        if(DestinationLng!=null)
        latLngBuilder.include(DestinationLng);

        try {
            LatLngBounds bounds = latLngBuilder.build();
            CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds,
                    UiHelper.dpToPixel(getActivity(), 135));
            googleMap.animateCamera(cu);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

This would help you.


问:
Sliding window on list of lists in Python
I'm trying to use numpy/pandas to constuct a sliding window style comparator. I've got list of lists each of which is a different length. I want to compare each list to to another list as depicted below:

```<code>lists = [[10,15,5],[5,10],[5]]

window_diff(l[1],l[0]) = 25
</code>```

The window diff for lists[0] and lists[1] would give 25 using the following window sliding technique shown in the image below. Because lists[1] is the shorter path we shift it once to the right, resulting in 2 windows of comparison. If you sum the last row in the image below we get the total difference between the two lists using the two windows of comparison; in this case a total of 25. To note we are taking the absolute difference.

The function should aggregate the total window_diff between each list and the other lists, so in this case

```<code>tot = total_diffs(lists)
tot>>[40, 30, 20]

# where tot[0] represents the sum of lists[0] window_diff with all other lists.
</code>```

I wanted to know if there was a quick route to doing this in pandas or numpy. Currently I am using a very long winded process of for looping through each of the lists and then comparing bitwise by shifting the shorter list in accordance to the longer list.

My approach works fine for short lists, but my dataset is 10,000 lists long and some of these lists contain 60 or so datapoints, so speed is a criteria here. I was wondering if numpy, pandas had some advice on this? Thanks

Sample problem data

```<code>from random import randint
lists = [[random.randint(0,1000) for r in range(random.randint(0,60))] for x in range(100000)]
</code>```

答:
Just for completeness of @Divakar's great answer and for its application to very large datasets:

```<code>import itertools

N = len(lists)
out = np.zeros(N, dtype=type(lists[0][0]))

for i, j in itertools.combinations(range(N), 2):
    A, B = lists[i], lists[j]

    if len(A)>len(B):
        diff = np.abs(strided_app(A,L=len(B)) - B).sum()
    else:
        diff = np.abs(strided_app(B,L=len(A)) - A).sum()

    out[i] += diff
    out[j] += diff
</code>```

It does not create unnecessary large datasets and updates a single vector while iterating only over the upper triangular array.

It will still take a while to compute, as there is a tradeoff between computational complexity and larger-than-ram datasets. Solutions for larger than ram datasets often rely on iterations, and python is not great at it. Iterating in python over a large dataset is slow, very slow.

Translating the code above to cython could speedup things a bit.

Body:
I'm trying to use numpy/pandas to constuct a sliding window style comparator. I've got list of lists each of which is a different length. I want to compare each list to to another list as depicted below:

lists = [[10,15,5],[5,10],[5]]

window_diff(l[1],l[0]) = 25

The window diff for lists[0] and lists[1] would give 25 using the following window sliding technique shown in the image below. Because lists[1] is the shorter path we shift it once to the right, resulting in 2 windows of comparison. If you sum the last row in the image below we get the total difference between the two lists using the two windows of comparison; in this case a total of 25. To note we are taking the absolute difference.

The function should aggregate the total window_diff between each list and the other lists, so in this case

tot = total_diffs(lists)
tot>>[40, 30, 20]

# where tot[0] represents the sum of lists[0] window_diff with all other lists.

I wanted to know if there was a quick route to doing this in pandas or numpy. Currently I am using a very long winded process of for looping through each of the lists and then comparing bitwise by shifting the shorter list in accordance to the longer list.

My approach works fine for short lists, but my dataset is 10,000 lists long and some of these lists contain 60 or so datapoints, so speed is a criteria here. I was wondering if numpy, pandas had some advice on this? Thanks

Sample problem data

from random import randint
lists = [[random.randint(0,1000) for r in range(random.randint(0,60))] for x in range(100000)]

Body:
Just for completeness of @Divakar's great answer and for its application to very large datasets:

import itertools

N = len(lists)
out = np.zeros(N, dtype=type(lists[0][0]))

for i, j in itertools.combinations(range(N), 2):
    A, B = lists[i], lists[j]

    if len(A)>len(B):
        diff = np.abs(strided_app(A,L=len(B)) - B).sum()
    else:
        diff = np.abs(strided_app(B,L=len(A)) - A).sum()

    out[i] += diff
    out[j] += diff

It does not create unnecessary large datasets and updates a single vector while iterating only over the upper triangular array.

It will still take a while to compute, as there is a tradeoff between computational complexity and larger-than-ram datasets. Solutions for larger than ram datasets often rely on iterations, and python is not great at it. Iterating in python over a large dataset is slow, very slow.

Translating the code above to cython could speedup things a bit.


问:
Optimal way of creating and handling multiple observables for multiple network calls using RxJava
I need to iterate through a list of data, get all their Ids, trigger network calls using those Ids, and then do something once I get the list of results (The server could take list of Ids and return a list of result but it doesn't work that way as of now).

Currently I got it working like this:

```<code>for (Data data: dataList) {
    String id = data.getId();
    idObservables.add(dataService.getResultFromNetwork(id));
}

Observable.zip(idObservables, new FuncN<List<Result>>() {
    @Override
    public List<Result> call(Object... args) {
        List<Result> resultList = new ArrayList<>();
        for (Object arg : args) {
            resultList.add((Result) arg));
        }
        return resultList;
    }
}).subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(new Action1<List<Result>>() {
        @Override
        public void call(List<Result> resultList) {
           // Do something with the list of Result
        }
    }, new Action1<Throwable>() {
        @Override
        public void call(Throwable throwable) {
            Log.e("", "error", throwable);
        }
    });
</code>```

But obviously I'm not happy with the way it's done. It will be great to know better ways to handle a case like this using RxJava in Android.

Cheers!!

答:
Apologies for the lambda-isms, but it really makes the logic easier to read:

```<code>Observable
.fromIterable(dataList)
.flatMap(data ->
     dataService
     .getResultFromNetwork(data.getId())
     .subscribeOn(Schedulers.io())
)
.toList()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(list -> {
    // do something
});
</code>```

The idea is to keep as much as the pipeline in Rx-land; it's worth it to have simple methods taking normal parameters and return observables, and complex methods take observables and return observables.

Note: the above will not retain ordering; if you need an ordered list, use concatMap with prefetch.

Body:
I need to iterate through a list of data, get all their Ids, trigger network calls using those Ids, and then do something once I get the list of results (The server could take list of Ids and return a list of result but it doesn't work that way as of now).

Currently I got it working like this:

for (Data data: dataList) {
    String id = data.getId();
    idObservables.add(dataService.getResultFromNetwork(id));
}

Observable.zip(idObservables, new FuncN<List<Result>>() {
    @Override
    public List<Result> call(Object... args) {
        List<Result> resultList = new ArrayList<>();
        for (Object arg : args) {
            resultList.add((Result) arg));
        }
        return resultList;
    }
}).subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(new Action1<List<Result>>() {
        @Override
        public void call(List<Result> resultList) {
           // Do something with the list of Result
        }
    }, new Action1<Throwable>() {
        @Override
        public void call(Throwable throwable) {
            Log.e("", "error", throwable);
        }
    });

But obviously I'm not happy with the way it's done. It will be great to know better ways to handle a case like this using RxJava in Android.

Cheers!!

Body:
Apologies for the lambda-isms, but it really makes the logic easier to read:

Observable
.fromIterable(dataList)
.flatMap(data ->
     dataService
     .getResultFromNetwork(data.getId())
     .subscribeOn(Schedulers.io())
)
.toList()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(list -> {
    // do something
});

The idea is to keep as much as the pipeline in Rx-land; it's worth it to have simple methods taking normal parameters and return observables, and complex methods take observables and return observables.

Note: the above will not retain ordering; if you need an ordered list, use concatMap with prefetch.


答:
Use this actions in receiver tag in manifest</p>

```<code> <action android:name="android.intent.action.SCREEN_ON" />
 <action android:name="android.intent.action.SCREEN_OFF" />
</code>```

Title: Android in service how to know when screen is locked?

Body:
I want to handle an Androids application work in the background. I've read that I have to use services for this.
In this application, I need to know when the screen gets locked and when it gets unlocked again. Every time this happens, I have to do some actions.

For activities, I've seen we have onPause and onRestart for this, but I need to know when the screen is turned off and when it is turned on in a service. How can this information be retrieved from inside a service.

Body:
Use this actions in receiver tag in manifest

 <action android:name="android.intent.action.SCREEN_ON" />
 <action android:name="android.intent.action.SCREEN_OFF" />


问:
Test ionic 2 app without android studio
Due to certain reasons I can't download android studio. And I recently incorporated sqlite DB in my app. As far as i know, ionic serve cannot run a sqlite DB. I wanted to know if it's possible to test my ionic 3.x app on an android device without having android studio.

答:
You don't need Android studio at all to work on Ionic development. Any editor + a terminal will do.

Having said that it is strongly recommended to work with the free Visual Studio Code editor, as it's built by Microsoft, the same team that built Typescript which makes coding there a great experience.

I also suggest this set of plugins to get you started.

Unfortunately you cannot work on SQLite in the browser but I strongly recommend you use ionic-storage anyway, which provides a single API and will use automatically whatever best storage method is available in the current platform, with no additional effort from you.

Ionic Storage is a package created and maintained by the ionic team to abstract development from the specifics of each browser or platform and automatically use the best storage solution available.

1. Installing Dependencies

In your case for SQLite you need to first install the dependencies for both Angular and Cordova:

npm install @ionic/storage --save

and

cordova plugin add cordova-sqlite-storage --save

Then edit your NgModule declaration in src/app/app.module.ts to add IonicStorageModule as an import:

import { IonicStorageModule } from '@ionic/storage';

@NgModule({
  declarations: [...],
  imports: [
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot({
      name: '__mydb',
      driverOrder: ['indexeddb', 'sqlite', 'websql'],
    })
  ],
  bootstrap: [...],
  entryComponents: [...],
  providers: [...],
})
export class AppModule { }
```
<br>
<h1>2. Inject Storage module into your component </h1>
```import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(public storage: Storage) {}
}
```
<br>
<h1>3. Using Ionic Storage</h1>
<p>Whenever you access storage, make sure to always wrap your code in the following:</p>
```storage.ready().then(() => { /* code here safely */});
```
<h3>3.1 Saving a key-value pair</h3>
```storage.ready().then(() => {
    storage.set('some key', 'some value');
});
```
<h3>3.2 Retrieving a value</h3>
```storage.ready().then(() => {
  storage.get('age').then((val: string) => {
      console.log('Your age is', val);
  });
});
```
<h3>3.3 Deleting a key-value pair</h3>
```storage.ready().then(() => {
    storage.remove('key').then((key: string) => { /* do something after deletion */})
});
```

Title: Test ionic 2 app without android studio

Body:
You don't need Android studio at all to work on Ionic development. Any editor + a terminal will do.

Having said that it is strongly recommended to work with the free Visual Studio Code editor, as it's built by Microsoft, the same team that built Typescript which makes coding there a great experience.

I also suggest this set of plugins to get you started.

Unfortunately you cannot work on SQLite in the browser but I strongly recommend you use ionic-storage anyway, which provides a single API and will use automatically whatever best storage method is available in the current platform, with no additional effort from you.

Ionic Storage is a package created and maintained by the ionic team to abstract development from the specifics of each browser or platform and automatically use the best storage solution available.

1. Installing Dependencies

In your case for SQLite you need to first install the dependencies for both Angular and Cordova:

npm install @ionic/storage --save

and

cordova plugin add cordova-sqlite-storage --save

Then edit your NgModule declaration in src/app/app.module.ts to add IonicStorageModule as an import:

import { IonicStorageModule } from '@ionic/storage';

@NgModule({
  declarations: [...],
  imports: [
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot({
      name: '__mydb',
      driverOrder: ['indexeddb', 'sqlite', 'websql'],
    })
  ],
  bootstrap: [...],
  entryComponents: [...],
  providers: [...],
})
export class AppModule { }

2. Inject Storage module into your component

import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(public storage: Storage) {}
}

3. Using Ionic Storage

Whenever you access storage, make sure to always wrap your code in the following:

storage.ready().then(() => { /* code here safely */});

3.1 Saving a key-value pair

storage.ready().then(() => {
    storage.set('some key', 'some value');
});

3.2 Retrieving a value

storage.ready().then(() => {
  storage.get('age').then((val: string) => {
      console.log('Your age is', val);
  });
});

3.3 Deleting a key-value pair

storage.ready().then(() => {
    storage.remove('key').then((key: string) => { /* do something after deletion */})
});


问:
How to execute success method in Firebase?
I'm developing an Android+Firebase app but since I'm new to both techlogies I'm having a problem regarding async calls and I haven't found the solution yet so hope you can help me.

I have the following snippet in my Activity's onCreate method:

```<code>final ArrayList<AssetLocation> assetsLocations = new ArrayList<>();
        DatabaseReference assetsLocationReference = database.getReference(FirebaseReferences.ASSETSLOCATION_REFERENCE);
        assetsLocationReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                ArrayList<String> assetsLocationSpinner = new ArrayList<String>();
                // Create an ArrayAdapter using the string array and a default spinner layout
                for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                    //Getting the data from snapshot
                    AssetLocation assetsLocation = postSnapshot.getValue(AssetLocation.class);
                    assetsLocations.add(AssetLocation);
                }
            }

            @Override
            public void onCancelled(DatabaseError firebaseError) {
                System.out.println("The read failed: " + firebaseError.getMessage());
            }
        });
</code>```

I also have a pretty similar call but instead of getting Locations, I'm getting Types.

After this code (inside the onCreate method as well), I'm calling setScreenInfo which is a function to fill both spinners (and do more stuff) with said data but since it is an async call, the spinners are blank when I execute it.

How can I execute setScreenInfo once the calls are made? I tried with .once()/.on() but it's not being recognised by Android Studio as a function.

Thanks for your help!

答:
You can use thread:

```<code>thread = new Thread() {

    @Override
    public void run() {

        try {
            //background tasks

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //UI tasks
                }
            });
        }
        catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
};
    thread.start();`
</code>```

Or you can use Firebase Multi Query method.
link:  Only load layout when firebase calls are complete

Body:
I'm developing an Android+Firebase app but since I'm new to both techlogies I'm having a problem regarding async calls and I haven't found the solution yet so hope you can help me.

I have the following snippet in my Activity's onCreate method:

final ArrayList<AssetLocation> assetsLocations = new ArrayList<>();
        DatabaseReference assetsLocationReference = database.getReference(FirebaseReferences.ASSETSLOCATION_REFERENCE);
        assetsLocationReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                ArrayList<String> assetsLocationSpinner = new ArrayList<String>();
                // Create an ArrayAdapter using the string array and a default spinner layout
                for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                    //Getting the data from snapshot
                    AssetLocation assetsLocation = postSnapshot.getValue(AssetLocation.class);
                    assetsLocations.add(AssetLocation);
                }
            }

            @Override
            public void onCancelled(DatabaseError firebaseError) {
                System.out.println("The read failed: " + firebaseError.getMessage());
            }
        });

I also have a pretty similar call but instead of getting Locations, I'm getting Types.

After this code (inside the onCreate method as well), I'm calling setScreenInfo which is a function to fill both spinners (and do more stuff) with said data but since it is an async call, the spinners are blank when I execute it.

How can I execute setScreenInfo once the calls are made? I tried with .once()/.on() but it's not being recognised by Android Studio as a function.

Thanks for your help!

Body:
You can use thread:

thread = new Thread() {

    @Override
    public void run() {

        try {
            //background tasks

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //UI tasks
                }
            });
        }
        catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
};
    thread.start();`

Or you can use Firebase Multi Query method.
link:  Only load layout when firebase calls are complete


问:
Setting Image Close to TextView - Xamarin Android
I am sure this is very basic but i don't get why my image(icon) wouldn't show up on the left of my text. I want to have something like this
(icon) Text. This is what i have tried using left drawables but it won't work for me.

listItem.axml

```<code><LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="63"
                android:orientation="vertical"
                android:paddingRight="10dp"
                android:paddingLeft="10dp"
                android:paddingTop="7dp"
                android:paddingBottom="7dp">
                <TextView
                    android:text="Event Name"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/textView1"
                    android:textStyle="bold"
                    android:textColor="#000"
                    android:gravity="center_vertical"
                    android:padding="2dp"
                    android:textSize="18sp"/>
</code>```

Activity

```<code>     textIcon = FindViewById<TextView>(Resource.Id.textView1);
                textIcon.SetCompoundDrawablesWithIntrinsicBounds(Resource.Drawable.Icon, 0, 0, 0);
</code>```

Adapter and Holder

```<code>  public class Fragment : SupportFragment

        {
            public override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);
                // Create your fragment here
            }

            public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
            {
                RecyclerView recyclerView = inflater.Inflate(Resource.Layout.Fragment, container, false) as RecyclerView;

                SetUpRecyclerView(recyclerView);

                return recyclerView;
            }

            private void SetUpRecyclerView(RecyclerView recyclerView)
            {
                recyclerView.SetLayoutManager(new LinearLayoutManager(recyclerView.Context));

                var Adapter = new EventAdapter(Collection.GetData());

                recyclerView.SetAdapter(Adapter);

            }

            public class Adapter : RecyclerView.Adapter
            {

                private JavaList<MyData> AllData;

                public EventAdapter(JavaList<MyData> AllData)
                {
                    this.AllData = AllData;

                }

                public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
                {
                    MyHolder hold = holder as MyHolder;
                    hold.Name.Text = AllData[position].Name;

   }

                public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
                {
                    View v = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.ListItem, parent, false);
                    MyHolder holder = new MyHolder(v);

                    return holder;
                }

                public override int ItemCount
                {

                    get { return AllData.Size(); }

                }

            }
        }

    public class MyHolder : RecyclerView.ViewHolder
    {

        public TextView Name;

        public EventHolder(View itemView) : base(itemView)
        {
            Name = itemView.FindViewById<TextView>(Resource.Id.textView1);

        }

    }
</code>```

答:
just put notifydatasetchnaged after view update inside fragment.

```<code>  textIcon = FindViewById<TextView>(Resource.Id.textView1);
                textIcon.SetCompoundDrawablesWithIntrinsicBounds(Resource.Drawable.Icon, 0, 0, 0);
</code>```

and then notify to adapter

```<code>Adapter.notifyDataSetChanged()
</code>```

Body:
I am sure this is very basic but i don't get why my image(icon) wouldn't show up on the left of my text. I want to have something like this
(icon) Text. This is what i have tried using left drawables but it won't work for me.

listItem.axml

<LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="63"
                android:orientation="vertical"
                android:paddingRight="10dp"
                android:paddingLeft="10dp"
                android:paddingTop="7dp"
                android:paddingBottom="7dp">
                <TextView
                    android:text="Event Name"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/textView1"
                    android:textStyle="bold"
                    android:textColor="#000"
                    android:gravity="center_vertical"
                    android:padding="2dp"
                    android:textSize="18sp"/>

Activity

     textIcon = FindViewById<TextView>(Resource.Id.textView1);
                textIcon.SetCompoundDrawablesWithIntrinsicBounds(Resource.Drawable.Icon, 0, 0, 0);

Adapter and Holder

  public class Fragment : SupportFragment

        {
            public override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);
                // Create your fragment here
            }

            public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
            {
                RecyclerView recyclerView = inflater.Inflate(Resource.Layout.Fragment, container, false) as RecyclerView;

                SetUpRecyclerView(recyclerView);

                return recyclerView;
            }

            private void SetUpRecyclerView(RecyclerView recyclerView)
            {
                recyclerView.SetLayoutManager(new LinearLayoutManager(recyclerView.Context));

                var Adapter = new EventAdapter(Collection.GetData());

                recyclerView.SetAdapter(Adapter);

            }

            public class Adapter : RecyclerView.Adapter
            {

                private JavaList<MyData> AllData;

                public EventAdapter(JavaList<MyData> AllData)
                {
                    this.AllData = AllData;

                }

                public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
                {
                    MyHolder hold = holder as MyHolder;
                    hold.Name.Text = AllData[position].Name;

   }

                public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
                {
                    View v = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.ListItem, parent, false);
                    MyHolder holder = new MyHolder(v);

                    return holder;
                }

                public override int ItemCount
                {

                    get { return AllData.Size(); }

                }

            }
        }

    public class MyHolder : RecyclerView.ViewHolder
    {

        public TextView Name;

        public EventHolder(View itemView) : base(itemView)
        {
            Name = itemView.FindViewById<TextView>(Resource.Id.textView1);

        }

    }

Body:
just put notifydatasetchnaged after view update inside fragment.

  textIcon = FindViewById<TextView>(Resource.Id.textView1);
                textIcon.SetCompoundDrawablesWithIntrinsicBounds(Resource.Drawable.Icon, 0, 0, 0);

and then notify to adapter

Adapter.notifyDataSetChanged()


问:
Gitlab-CI PHP executable returning error code 255
I recently set up GitLab-CI in my self-hosted GitLab CE instance. I created one runner for a specific project and one shared runner.

My /etc/gitlab-runner/config.toml is following:

```<code>concurrent = 1
check_interval = 0

[[runners]]
  name = "project runner"
  url = "https://gitlab.domain.com/ci"
  token = "SECRET"
  executor = "docker"
  [runners.docker]
    tls_verify = false
    image = "geertw/docker-php-ci:7.0-no-xdebug"
    privileged = false
    disable_cache = false
    volumes = ["/cache"]
    shm_size = 0
  [runners.cache]

[[runners]]
  name = "shared runner"
  url = "https://gitlab.domain.com"
  token = "SECRET"
  executor = "docker"
  [runners.docker]
    tls_verify = false
    image = "geertw/docker-php-ci:7.0-no-xdebug"
    privileged = false
    disable_cache = false
    volumes = ["/cache"]
    shm_size = 0
  [runners.cache]
</code>```

Then I added custom scripts to my composer.json file:

```<code>...

"scripts": {
    "build": [
        "@composer install --no-progress --no-interaction --no-suggest",
        "@lint"
    ],
    "lint": "php -d display_errors -d display_startup_errors ./vendor/bin/parallel-lint --exclude vendor ."
}
</code>```

And the script is part of my .gitlab-ci.yml file:

```<code>before_script:
  - php -v

services:
  - mysql:latest

variables:
  MYSQL_DATABASE: "database"
  MYSQL_ROOT_PASSWORD: "password"

build:7.0:
  image: geertw/docker-php-ci:7.0
  script:
    - composer build
    - php vendor/bin/phpunit --coverage-text --colors=never

build:7.1:
  image: geertw/docker-php-ci:7.1-no-xdebug
  script:
    - composer build

cache:
  paths:
    - vendor/
</code>```

When I execute the pipeline in GitLab, I receive an error:

```<code>> php -d display_errors -d display_startup_errors ./vendor/bin/parallel-lint --exclude vendor .
Script php -d display_errors -d display_startup_errors ./vendor/bin/parallel-lint --exclude vendor . handling the lint event returned with error code 255
ERROR: Job failed: exit code 1
</code>```

Now when I run composer lint locally, it works as expected. I also tried to comment it out and I receive the same error with PHPUnit (build:7.0 in .gitlab-ci.yml). For debugging reasons I added php -d to display errors, yet nothing is shown.

The other (private) pipeline works as expected for a smaller project that has exactly the same .gitlab-ci.yml file. I also tried switching from one runner to another but it doesn't work on either.

Since I am new to docker and CI in general, I have little knowledge on how to debug this situation properly, perhaps increase php memory_limit
in some way or output errors to stderr.

Any ideas?

答: Turns out there was an autoloader executing ext-mysqli functions with @call. The app is a mess.</p>

Body:
I recently set up GitLab-CI in my self-hosted GitLab CE instance. I created one runner for a specific project and one shared runner.

My /etc/gitlab-runner/config.toml is following:

concurrent = 1
check_interval = 0

[[runners]]
  name = "project runner"
  url = "https://gitlab.domain.com/ci"
  token = "SECRET"
  executor = "docker"
  [runners.docker]
    tls_verify = false
    image = "geertw/docker-php-ci:7.0-no-xdebug"
    privileged = false
    disable_cache = false
    volumes = ["/cache"]
    shm_size = 0
  [runners.cache]

[[runners]]
  name = "shared runner"
  url = "https://gitlab.domain.com"
  token = "SECRET"
  executor = "docker"
  [runners.docker]
    tls_verify = false
    image = "geertw/docker-php-ci:7.0-no-xdebug"
    privileged = false
    disable_cache = false
    volumes = ["/cache"]
    shm_size = 0
  [runners.cache]

Then I added custom scripts to my composer.json file:

...

"scripts": {
    "build": [
        "@composer install --no-progress --no-interaction --no-suggest",
        "@lint"
    ],
    "lint": "php -d display_errors -d display_startup_errors ./vendor/bin/parallel-lint --exclude vendor ."
}

And the script is part of my .gitlab-ci.yml file:

before_script:
  - php -v

services:
  - mysql:latest

variables:
  MYSQL_DATABASE: "database"
  MYSQL_ROOT_PASSWORD: "password"

build:7.0:
  image: geertw/docker-php-ci:7.0
  script:
    - composer build
    - php vendor/bin/phpunit --coverage-text --colors=never

build:7.1:
  image: geertw/docker-php-ci:7.1-no-xdebug
  script:
    - composer build

cache:
  paths:
    - vendor/

When I execute the pipeline in GitLab, I receive an error:

> php -d display_errors -d display_startup_errors ./vendor/bin/parallel-lint --exclude vendor .
Script php -d display_errors -d display_startup_errors ./vendor/bin/parallel-lint --exclude vendor . handling the lint event returned with error code 255
ERROR: Job failed: exit code 1

Now when I run composer lint locally, it works as expected. I also tried to comment it out and I receive the same error with PHPUnit (build:7.0 in .gitlab-ci.yml). For debugging reasons I added php -d to display errors, yet nothing is shown.

The other (private) pipeline works as expected for a smaller project that has exactly the same .gitlab-ci.yml file. I also tried switching from one runner to another but it doesn't work on either.

Since I am new to docker and CI in general, I have little knowledge on how to debug this situation properly, perhaps increase php memory_limit
in some way or output errors to stderr.

Any ideas?


问:
Add FocusListener to a 2D JTextField array
So I want to setText a string called value when I click on one of the JTextfield. I read about adding FocusListener to a JTextField but couldn't find anything about adding it to a 2D JTextField array. I'm having trouble making it work.

```<code>private int totalX = 20;
private int totalY = 20;

private JTextField[][] fields;
fields = new JTextField[totalX][totalY];
</code>```

答:
You have to add the listener on each JTextField object if you want each field may react to the click.

```<code>private JTextField[][] fields = new JTextField[totalX][totalY];
... // create JTextField objects of the array

// then iterate on the array to add the Listener
for (JTextField field : fields){
    field.addFocusListener(new MyFocusListener());
}
</code>```

You should use one FocusListener instance by JTextField object if the FocusListener implementation is stateful.

Otherwise you could reuse the same FocusListener instance for all JTextField objects.

Body:
So I want to setText a string called value when I click on one of the JTextfield. I read about adding FocusListener to a JTextField but couldn't find anything about adding it to a 2D JTextField array. I'm having trouble making it work.

private int totalX = 20;
private int totalY = 20;

private JTextField[][] fields;
fields = new JTextField[totalX][totalY];

Body:
You have to add the listener on each JTextField object if you want each field may react to the click.

private JTextField[][] fields = new JTextField[totalX][totalY];
... // create JTextField objects of the array

// then iterate on the array to add the Listener
for (JTextField field : fields){
    field.addFocusListener(new MyFocusListener());
}

You should use one FocusListener instance by JTextField object if the FocusListener implementation is stateful.

Otherwise you could reuse the same FocusListener instance for all JTextField objects.


问:
Alternative for multiple pthreads joining one pthread?
I read in man pthread_join that multiple pthreads cannot join a pthread that has already been joined. Is there another way to achieve the same result? Multiple pthreads suspend themselves until some specific pthread tells them "you may continue"? And how would that work? (in C language)

答:
The concept of pthread_join is different from what you have asked "Multiple pthreads suspend themselves until some specific pthread tells them "you may continue"?"

Incase of pthread_join, a thread waits for other threads to complete before proceeding further.

If you want multiple threads to wait for a signal from other thread (or threads), you can try exploring pthread_cond_wait and pthread_cond_signal API(s)


问:
How do I create a link to pre-select a form option
I have the following code on another webpage on my site with a form (say on page index.html): JSFiddle

```<code><select class="select form-control" id="dropdown" name="dropdown" onchange="showForm()">
</code>```

i.e a dropdown form.

I want to have a link on another webpage that will go to this page, and have the "Sales" option already selected.

```<code><option value="1">
    Sales
</option>
</code>```

from the drop down menu (instead of the current default option), how do I create this?

答:
Query parameters can be used to achieve the result you want, but you will need to parse the query parameter manually on your current page, since there is no standard JavaScript method for doing it.

You can write the following code on your page to automatically select the option:

```<code>$(document).ready(function() {
  // Parse your query parameters here, and assign them to a variable named `queryParams`
  var option = queryParams.type;
  $("#dropdown").val(option);
});
</code>```

Now you can create an anchor with the URL of this page, e.g. http://yourpage.url?type=1, which will redirect to this page, and will automatically change the value of your dropdown accordingly.

Body:
I have the following code on another webpage on my site with a form (say on page index.html): JSFiddle

<select class="select form-control" id="dropdown" name="dropdown" onchange="showForm()">

i.e a dropdown form.

I want to have a link on another webpage that will go to this page, and have the "Sales" option already selected.

<option value="1">
    Sales
</option>

from the drop down menu (instead of the current default option), how do I create this?

Body:
Query parameters can be used to achieve the result you want, but you will need to parse the query parameter manually on your current page, since there is no standard JavaScript method for doing it.

You can write the following code on your page to automatically select the option:

$(document).ready(function() {
  // Parse your query parameters here, and assign them to a variable named `queryParams`
  var option = queryParams.type;
  $("#dropdown").val(option);
});

Now you can create an anchor with the URL of this page, e.g. http://yourpage.url?type=1, which will redirect to this page, and will automatically change the value of your dropdown accordingly.


问:
Display attributed text in textview in swift 3?
I want to display text in Italic ,bold which is received from server .

   hello   world
 so,

```<code>responseObj!["text"] = "<p><b><i>hello</i></b><i>world</></p>"
     if let postText:String = responseObj!["text"] as? String{
          let str = try NSAttributedString(data: postText.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
      self.textView.attributedText = str
    }
</code>```

when i am adding like this means my text displays normal without applying bold & italic . I want text to be displayed in bold ,italic .

答:
Assign Attributed text to UITextView from below function,</p>

```<code>//HTML to Attributed text
func stringFromHtml(string: String) -> NSAttributedString? {
do {
    let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
    if let d = data {
        let str = try NSAttributedString(data: d,
                                         options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                                         documentAttributes: nil)
        return str
    }
} catch {
}
return nil
}

//This will give you attributed text which you have to assign to your UITextView. and whatever string having html tag that you have to pass inside this function.

//Below code will conver attributed text to HTML Text
//Attributed to HTML text

    let attrStr = self.txtView.attributedText
    let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
    do {
        let htmlData = try attrStr?.data(from: NSMakeRange(0, (attrStr?.length)!), documentAttributes:documentAttributes)
        if let htmlString = String(data:htmlData!, encoding:String.Encoding.utf8) {
            print(htmlString)
        }
    }
    catch {
        print("error creating HTML from Attributed String")
    }
</code>```

Body:
I want to display text in Italic ,bold which is received from server .

   hello   world
 so,

responseObj!["text"] = "
helloworld</>
"
     if let postText:String = responseObj!["text"] as? String{
          let str = try NSAttributedString(data: postText.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
      self.textView.attributedText = str
    }

when i am adding like this means my text displays normal without applying bold & italic . I want text to be displayed in bold ,italic .

Body:
Assign Attributed text to UITextView from below function,

//HTML to Attributed text
func stringFromHtml(string: String) -> NSAttributedString? {
do {
    let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
    if let d = data {
        let str = try NSAttributedString(data: d,
                                         options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
                                         documentAttributes: nil)
        return str
    }
} catch {
}
return nil
}

//This will give you attributed text which you have to assign to your UITextView. and whatever string having html tag that you have to pass inside this function.

//Below code will conver attributed text to HTML Text
//Attributed to HTML text

    let attrStr = self.txtView.attributedText
    let documentAttributes = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
    do {
        let htmlData = try attrStr?.data(from: NSMakeRange(0, (attrStr?.length)!), documentAttributes:documentAttributes)
        if let htmlString = String(data:htmlData!, encoding:String.Encoding.utf8) {
            print(htmlString)
        }
    }
    catch {
        print("error creating HTML from Attributed String")
    }


问:
I have a selection box with 5 option values. I want to repeat a table row based on the value I select from it
This is my select box code:

```<code><select class="form-control">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>
</code>```

This is the table row I want to repeat:

```<code><tr>
    <td><input type="text" class="form-control" name="" placeholder="Name"></td>
    <td><input type="text" class="form-control" name="" placeholder="Email"></td>
    <td><input type="text" class="form-control" name="" placeholder="Mobile No."></td>
</tr>
</code>```

答:
$('.form-control').change(function() {
  $('#table').find('tr:not(:nth-child(1))').remove()
  var value = $("option:selected", this).val();

  for (var i = 0; i < value; i++) {
    $('#table').append($('#table').find('tr:nth-child(1)').clone())
  }

})```
<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>
<select class="form-control">
<option></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>

<table id="table">
  <tr>
    <td><input type="text" class="form-control" name="" placeholder="Name"></td>
    <td><input type="text" class="form-control" name="" placeholder="Email"></td>
    <td><input type="text" class="form-control" name="" placeholder="Mobile No."></td>
  </tr>
</table></code>```

Use change event of the select to clone the first TR

Depending on the value of option selected use it as number of iteration to append the tr

Body:
This is my select box code:

<select class="form-control">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>

This is the table row I want to repeat:

    <input type="text" class="form-control" name="" placeholder="Name">
    <input type="text" class="form-control" name="" placeholder="Email">
    <input type="text" class="form-control" name="" placeholder="Mobile No.">

Body:
$('.form-control').change(function() {
  $('#table').find('tr:not(:nth-child(1))').remove()
  var value = $("option:selected", this).val();

  for (var i = 0; i < value; i++) {
    $('#table').append($('#table').find('tr:nth-child(1)').clone())
  }

})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control">
<option></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>

<table id="table">
  <tr>
    <td><input type="text" class="form-control" name="" placeholder="Name"></td>
    <td><input type="text" class="form-control" name="" placeholder="Email"></td>
    <td><input type="text" class="form-control" name="" placeholder="Mobile No."></td>
  </tr>
</table>

Use change event of the select to clone the first TR

Depending on the value of option selected use it as number of iteration to append the tr


问:
Method is not returning CSV file - Java
I am trying to read a  HashMap and write to a CSV file. I am using CSVPrinter, but my method is not returning a CSV file.

This is the code I use:
Edited Code

```<code>   import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVPrinter;

public class SJV{
    public File writeCSV(Map featureSet) throws IOException{

        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
        Map<String, Integer> map = featureSet;
        File temp = File.createTempFile("tempfile", ".tmp");
        FileWriter fs = new FileWriter(temp);

        CSVPrinter csvFilePrinter = new CSVPrinter(fs, csvFileFormat);
        //csvFilePrinter.printRecord(FILE_HEADER);

        csvFilePrinter.printRecord(map.keySet().toArray());
        csvFilePrinter.printRecord(map.values().toArray());

csvFilePrinter.close();
fs.close();

        return  temp;
    }
}
</code>```

This is the test I have:

```<code>public void testWriteCSV() throws IOException {
    SJV sj = new  SJV();

    HashMap<String, Integer> hmap = new HashMap<String, Integer>();
    hmap.put("Feature1", 1);
    hmap.put("Feature2", 2);
    File fs = sj.writeCSV(hmap);

    if (fs.exists()){
        Scanner input = new Scanner(fs );

        while (input.hasNextLine())
        {
           System.out.println(input.nextLine());
        }
        input.close();
    }
</code>```

I really don't understand why the method is not returning a CSV file.

答:
Try:</p>

```<code>fs.flush();
fs.close();
csvFilePrinter.close();
</code>```

Title: Method is not returning CSV file - Java

Body:
I am trying to read a  HashMap and write to a CSV file. I am using CSVPrinter, but my method is not returning a CSV file.

This is the code I use:
Edited Code

   import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVPrinter;

public class SJV{
    public File writeCSV(Map featureSet) throws IOException{

        CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
        Map<String, Integer> map = featureSet;
        File temp = File.createTempFile("tempfile", ".tmp");
        FileWriter fs = new FileWriter(temp);

        CSVPrinter csvFilePrinter = new CSVPrinter(fs, csvFileFormat);
        //csvFilePrinter.printRecord(FILE_HEADER);

        csvFilePrinter.printRecord(map.keySet().toArray());
        csvFilePrinter.printRecord(map.values().toArray());

csvFilePrinter.close();
fs.close();

        return  temp;
    }
}

This is the test I have:

public void testWriteCSV() throws IOException {
    SJV sj = new  SJV();

    HashMap<String, Integer> hmap = new HashMap<String, Integer>();
    hmap.put("Feature1", 1);
    hmap.put("Feature2", 2);
    File fs = sj.writeCSV(hmap);

    if (fs.exists()){
        Scanner input = new Scanner(fs );

        while (input.hasNextLine())
        {
           System.out.println(input.nextLine());
        }
        input.close();
    }

I really don't understand why the method is not returning a CSV file.

Body:
Try:

fs.flush();
fs.close();
csvFilePrinter.close();


问:
How can i display stack C
How could I display stack when I insert x in to programs.

```<code>#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int Data;
    struct Node* next;
} * top;

void popStack()
{
    struct Node *temp, *var = top;
    if (var == top)
    {
        top = top->next;
        free(var);
    }
    else
        printf("\nStack Empty");
}

void push(int value)
{
    struct Node* temp;
    temp = (struct Node*)malloc(sizeof(struct Node));
    temp->Data = value;
    if (top == NULL)
    {
        top = temp;
        top->next = NULL;
    }
    else
    {
        temp->next = top;
        top = temp;
    }
}

void display()
{
    struct Node* var = top;
    if (var != NULL)
    {
        printf("\nElements are as:\n");
        while (var != NULL)
        {
            printf("\t%d\n", var->Data);
            var = var->next;
        }
        printf("\n");
    }
    else
        printf("\nStack is Empty");
}

int main(int argc, char* argv[])
{
    printf(" Wellcome to Basic Stacking. \n");
    top = NULL;
    while (1)

    {
</code>```

when i insert "x" I want program to display stack and exit but it does not work after I insert x in this programs it will be infinite loop and don't display the stack and don't exit what should i do????.

```<code>        char x ;

        int value;
        if (value != x)
        {

            printf("please enter Your Name:");
            scanf("%d", &value);
            push(value);
            fflush(stdin);
            display();
        }
        else
        {
            // popStack();
            display();
            break;
        }
    }
    getch();
}
</code>```

答:
I found out your problem! This was kinda of an headache since the program was always going for an infinite loop!
But the problem is you are reading characters with scanf("%d",&value). This scanf doesn't remove the input from the buffer, so every other scanf you do after will have the same input ('x'), which your scanf can't read.

To fix this change these lines:

printf("please enter Your Name:");
 scanf("%d", &value);

to

printf("please enter Your Name:");
   if(scanf("%d", &value)==0)value=x;

So if scanf isn't successful then you assume the user wants to exit.

This is also a duplicate question, lease refer to this question, for more details.

Title: How can i display stack C

Body:
How could I display stack when I insert x in to programs.

#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int Data;
    struct Node* next;
} * top;

void popStack()
{
    struct Node *temp, *var = top;
    if (var == top)
    {
        top = top->next;
        free(var);
    }
    else
        printf("\nStack Empty");
}

void push(int value)
{
    struct Node* temp;
    temp = (struct Node*)malloc(sizeof(struct Node));
    temp->Data = value;
    if (top == NULL)
    {
        top = temp;
        top->next = NULL;
    }
    else
    {
        temp->next = top;
        top = temp;
    }
}

void display()
{
    struct Node* var = top;
    if (var != NULL)
    {
        printf("\nElements are as:\n");
        while (var != NULL)
        {
            printf("\t%d\n", var->Data);
            var = var->next;
        }
        printf("\n");
    }
    else
        printf("\nStack is Empty");
}

int main(int argc, char* argv[])
{
    printf(" Wellcome to Basic Stacking. \n");
    top = NULL;
    while (1)

    {

when i insert "x" I want program to display stack and exit but it does not work after I insert x in this programs it will be infinite loop and don't display the stack and don't exit what should i do????.

        char x ;

        int value;
        if (value != x)
        {

            printf("please enter Your Name:");
            scanf("%d", &value);
            push(value);
            fflush(stdin);
            display();
        }
        else
        {
            // popStack();
            display();
            break;
        }
    }
    getch();
}


问:
Keep User logged in on android webview (wordpress site)
i have developed a wordpress website and I used webview for the android app.
now my concern is that whenever a user log in to the app and opens the app after closing the app.I want to keep them logged in ! </p>

答: two ways either save your user login username and  password to sharedprefrence and check it everytime or save your user login username and password to sqlite and check if cursor count is 1 then redirect to webview else type username and password.</p>


问:
File output manipulation - ideally in one line
Apologies in advance this is my first post, hope you can understand it etc.

Original File

```<code>cat trail
PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                          Global
    forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                         Global
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown

vi and :set list

PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                          Global                    $
    forked child process 31522922$
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                         Global                    $
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown $

cat trail | oc -d
0226220                        G   l   o   b   a   l
0226240                                                               \n
0226260                                    f   o   r   k   e   d       c
0226300    h   i   l   d       p   r   o   c   e   s   s       3   1   5
0226320    2   2   9   2   2  \n   P   R   O   C   _   E   x   e   c   u
0226340    t   e                   r   o   o   t                       O
0226360    K                                           M   o   n       J
0226400    u   n       0   5       1   6   :   0   5   :   4   5       2
0226420    0   1   7       a   u   d   i   t
0226440
0226460                    G   l   o   b   a   l
0226500                                                           \n
0226520                                e   u   i   d   :       0       e
0226540    g   i   d   :       0       e   p   r   i   v   :       f   f
0226560    f   f   f   f   f   f   :   f   f   f   f   f   f   f   f
0226600    n   a   m   e       a   u   d   i   t       s   h   u   t   d
0226620    o   w   n      \n
0226625
</code>```

Desired Output

Ideally using some tools that I can pipe the trail file through such as sed/tr/awk etc.

```<code>PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                            Global        forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                           Global        euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown
</code>```

or

```<code>PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash        forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit       euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown
</code>```

I have manged to just remove the carriage returns and the word Global, but am struggling to just remove the carriage return and /or Global on the lines with Global in.  Thanks in advance.

I have used the following:

```<code>sed 's/Global//g'
tr -d '\n'
</code>```

but was hoping to do it all with sed but couldn't get it to work when trying to remove the carriage returns.

Larger sample of file

```<code>S_PASSWD_READ   root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    audit object read event detected /etc/security/passwd
S_PASSWD_READ   root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    audit object read event detected /etc/security/passwd
FILE_Write      root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    file descriptor = 5 filename =
FILE_Write      root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    file descriptor = 3 filename =
PROC_Execute    root     OK          Mon Jun 05 16:05:37 2017 ksh                             Global
   euid: 0 egid: 0 epriv: ffffffff:ffffffff name -ksh
PROC_Create     root     OK          Mon Jun 05 16:05:37 2017 ksh                             Global
    forked child process 40763616
PROC_Execute    root     OK          Mon Jun 05 16:05:37 2017 termdef                         Global
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name termdef
</code>```

答:
use sed with :label and N may can help, like:

cat trail | sed ':label;N;s/Global[ \n]*//;N;b label'

Edit1:

```<code>cat trail | sed '
:label;
N;
s/Global[ \n]*//;
N;
b label'
</code>```

Body:
Apologies in advance this is my first post, hope you can understand it etc.

Original File

cat trail
PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                          Global
    forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                         Global
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown

vi and :set list

PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                          Global                    $
    forked child process 31522922$
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                         Global                    $
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown $

cat trail | oc -d
0226220                        G   l   o   b   a   l
0226240                                                               \n
0226260                                    f   o   r   k   e   d       c
0226300    h   i   l   d       p   r   o   c   e   s   s       3   1   5
0226320    2   2   9   2   2  \n   P   R   O   C   _   E   x   e   c   u
0226340    t   e                   r   o   o   t                       O
0226360    K                                           M   o   n       J
0226400    u   n       0   5       1   6   :   0   5   :   4   5       2
0226420    0   1   7       a   u   d   i   t
0226440
0226460                    G   l   o   b   a   l
0226500                                                           \n
0226520                                e   u   i   d   :       0       e
0226540    g   i   d   :       0       e   p   r   i   v   :       f   f
0226560    f   f   f   f   f   f   :   f   f   f   f   f   f   f   f
0226600    n   a   m   e       a   u   d   i   t       s   h   u   t   d
0226620    o   w   n      \n
0226625

Desired Output

Ideally using some tools that I can pipe the trail file through such as sed/tr/awk etc.

PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash                            Global        forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit                           Global        euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown

or

PROC_Create     root     OK          Mon Jun 05 16:05:45 2017 bash        forked child process 31522922
PROC_Execute    root     OK          Mon Jun 05 16:05:45 2017 audit       euid: 0 egid: 0 epriv: ffffffff:ffffffff name audit shutdown

I have manged to just remove the carriage returns and the word Global, but am struggling to just remove the carriage return and /or Global on the lines with Global in.  Thanks in advance.

I have used the following:

sed 's/Global//g'
tr -d '\n'

but was hoping to do it all with sed but couldn't get it to work when trying to remove the carriage returns.

Larger sample of file

S_PASSWD_READ   root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    audit object read event detected /etc/security/passwd
S_PASSWD_READ   root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    audit object read event detected /etc/security/passwd
FILE_Write      root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    file descriptor = 5 filename =
FILE_Write      root     OK          Mon Jun 05 16:05:37 2017 su                              Global
    file descriptor = 3 filename =
PROC_Execute    root     OK          Mon Jun 05 16:05:37 2017 ksh                             Global
   euid: 0 egid: 0 epriv: ffffffff:ffffffff name -ksh
PROC_Create     root     OK          Mon Jun 05 16:05:37 2017 ksh                             Global
    forked child process 40763616
PROC_Execute    root     OK          Mon Jun 05 16:05:37 2017 termdef                         Global
    euid: 0 egid: 0 epriv: ffffffff:ffffffff name termdef

Body:
use sed with :label and N may can help, like:

cat trail | sed ':label;N;s/Global[ \n]*//;N;b label'

Edit1:

cat trail | sed '
:label;
N;
s/Global[ \n]*//;
N;
b label'


问:
URL Change in Codeigniter framework
I have a URL

```<code>http://localhost/himalaya/webmanager/recentUpdate/index/edit-recent-update-1
</code>```

but I want it to make the URL like this:

```<code>http://localhost/himalaya/webmanager/recentUpdate/edit-recent-update-1.
</code>```

The controller name is recentUpdate and method name is index. My question is how can I remove index method name from URL in codeigniter framework?

答:
add .htaccess file in your project.

Add code in it.

```<code>RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</code>```

Title: URL Change in Codeigniter framework

Body:
I have a URL

http://localhost/himalaya/webmanager/recentUpdate/index/edit-recent-update-1

but I want it to make the URL like this:

http://localhost/himalaya/webmanager/recentUpdate/edit-recent-update-1.

The controller name is recentUpdate and method name is index. My question is how can I remove index method name from URL in codeigniter framework?

Body:
add .htaccess file in your project.

Add code in it.

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]