问:
Why I could compare Strings using view bound but not upper bound?
In the following example, I could compare two Strings using view bound but not upper bound even though on REPL, the < method works for String. Is it because String is not a subclass of Ordered[T] but there is an implicit conversion from String to Ordered[String]?

```<code>//view bound example. For String, It seems to work because I suppose there is an implicit conversion from String to Ordered[String]
scala> class Person[T <% Ordered[T]](val fn:T, val ln:T){
     | def greater = if(fn > ln) fn else ln
     | }
defined class Person

scala> val p1 = new Person("manu", "chadha")
p1: Person[String] = Person@f95d64d

scala> p1.greater
res0: String = manu

scala> val p2 = new Person("anita", "chadha")
p2: Person[String] = Person@30cafd13

scala> p2.greater
res1: String = chadha

//upper bound example. It doesn't work for String. Is it because String is not a subclass of Ordered[T] but there is an implicit converstion from String to Ordered[Strig]
scala> class Person2[T <: Ordered[T]](val fn:T, val ln:T){
     | def greater = if(fn > ln) fn else ln
     | }
defined class Person2

scala> val p3 = new Person2("manu", "chadha")
<console>:12: error: inferred type arguments [String] do not conform to class Person2's type parameter bounds [T <: Ordered[T]]
       val p3 = new Person2("manu", "chadha")
                ^
<console>:12: error: type mismatch;
 found   : String("manu")
 required: T
       val p3 = new Person2("manu", "chadha")
                            ^
<console>:12: error: type mismatch;
 found   : String("chadha")
 required: T
       val p3 = new Person2("manu", "chadha")
                                    ^
</code>```

I suppose view bounds are deprecated. So how does the following example work in REPL?

```<code>scala> "manu" > "Manu"
res2: Boolean = true
</code>```

答:
Exactly. "a" < "b" is desugared as

```<code>scala.Predef.augmentString("a") < "b"
</code>```

Where augmentString("a") is a class StringOps, which is also Ordered[String], where < comes from.

View bounds syntax is deprecated, but the implicit conversions and parameters are not. So the way your code is written in the modern Scala is just using an implicit parameter which is an implicit conversion as well:

```<code>class Person[T](val fn:T, val ln:T)(implicit view: T => Ordered[T]){
  def greater = if(fn > ln) fn else ln
}
</code>```

Although it's generally considered best practice to use typeclasses. Here, we have scala.math.Ordering in standard library:

```<code>import Ordering.Implicits._ // brings operators like "<" into the scope

class Person[T](val fn: T, val ln: T)(implicit val order: Ordering[T]) {
  def greater = if (fn > ln) fn else ln
}
</code>```

Which have the syntactic form of context bounds that is not deprecated:

```<code>import Ordering.Implicits._ // brings operators like "<" into the scope

class Person[T: Ordering](val fn: T, val ln: T) {
  def greater = if (fn > ln) fn else ln
}
</code>```

This is the equivalent of Java's Comparable vs Comparator, except you don't have to pass Comparator instances manually

```<code>assert { new Person("manu", "chadha").greater == "manu" }
</code>```

Body:
In the following example, I could compare two Strings using view bound but not upper bound even though on REPL, the < method works for String. Is it because String is not a subclass of Ordered[T] but there is an implicit conversion from String to Ordered[String]?

//view bound example. For String, It seems to work because I suppose there is an implicit conversion from String to Ordered[String]
scala> class Person[T <% Ordered[T]](val fn:T, val ln:T){
     | def greater = if(fn > ln) fn else ln
     | }
defined class Person

scala> val p1 = new Person("manu", "chadha")
p1: Person[String] = Person@f95d64d

scala> p1.greater
res0: String = manu

scala> val p2 = new Person("anita", "chadha")
p2: Person[String] = Person@30cafd13

scala> p2.greater
res1: String = chadha

//upper bound example. It doesn't work for String. Is it because String is not a subclass of Ordered[T] but there is an implicit converstion from String to Ordered[Strig]
scala> class Person2[T <: Ordered[T]](val fn:T, val ln:T){
     | def greater = if(fn > ln) fn else ln
     | }
defined class Person2

scala> val p3 = new Person2("manu", "chadha")
<console>:12: error: inferred type arguments [String] do not conform to class Person2's type parameter bounds [T <: Ordered[T]]
       val p3 = new Person2("manu", "chadha")
                ^
<console>:12: error: type mismatch;
 found   : String("manu")
 required: T
       val p3 = new Person2("manu", "chadha")
                            ^
<console>:12: error: type mismatch;
 found   : String("chadha")
 required: T
       val p3 = new Person2("manu", "chadha")
                                    ^

I suppose view bounds are deprecated. So how does the following example work in REPL?

scala> "manu" > "Manu"
res2: Boolean = true

Body:
Exactly. "a" < "b" is desugared as

scala.Predef.augmentString("a") < "b"

Where augmentString("a") is a class StringOps, which is also Ordered[String], where < comes from.

View bounds syntax is deprecated, but the implicit conversions and parameters are not. So the way your code is written in the modern Scala is just using an implicit parameter which is an implicit conversion as well:

class Person[T](val fn:T, val ln:T)(implicit view: T => Ordered[T]){
  def greater = if(fn > ln) fn else ln
}

Although it's generally considered best practice to use typeclasses. Here, we have scala.math.Ordering in standard library:

import Ordering.Implicits._ // brings operators like "<" into the scope

class Person[T](val fn: T, val ln: T)(implicit val order: Ordering[T]) {
  def greater = if (fn > ln) fn else ln
}

Which have the syntactic form of context bounds that is not deprecated:

import Ordering.Implicits._ // brings operators like "<" into the scope

class Person[T: Ordering](val fn: T, val ln: T) {
  def greater = if (fn > ln) fn else ln
}

This is the equivalent of Java's Comparable vs Comparator, except you don't have to pass Comparator instances manually

assert { new Person("manu", "chadha").greater == "manu" }


来源: stackexchange

问:
Masking number at a particular position
I have a input field with a maximum length of 15 character.
i want to do something like this

original number :784198012345671
should be:  784********5671

答:
Replace Integer to String

Iterate the string and replace the position with *:

let number = 123455666777888;
let stringedNum = number.toString();

for(i=0;i<stringedNum.length;i++) {
  if(i>5 && i<10) { // change this line as per your need
     console.log(i)
     stringedNum = stringedNum.replace(stringedNum[i],'*');
  }
}
console.log(stringedNum)```

ContentLicense: CC BY-SA 3.0

Title: Masking number at a particular position


问:
How to run embedded TomEE for integration tests with test resources
I have J2EE project based on maven. This project contains connection to database, which is set up via resources.xml and persistence.xml. Connection works fine for normal deployment.

My problem is, that i would like to run embedded TomEE server for integration tests. For these tests i need use inmemory database.

To start TomEE i use combination of maven plugins showed below.

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>2.13</version>
    <executions>
        <execution>
            <goals>
                <goal>integration-test</goal>
                <goal>verify</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>org.apache.tomee.maven</groupId>
    <artifactId>tomee-maven-plugin</artifactId>
    <version>7.0.4</version>
    <executions>
        <execution>
            <id>start</id>
            <phase>pre-integration-test</phase>
            <goals>
                <goal>start</goal>
            </goals>
            <configuration>
                <checkStarted>true</checkStarted>
            </configuration>
        </execution>
            <execution>
                <id>stop</id>
                <phase>post-integration-test</phase>
                <goals>
                     <goal>stop</goal>
                </goals>
            </execution>
     </executions>
    <configuration>
        <simpleLog>true</simpleLog>
    </configuration>
  </plugin>
</code>```

When i start maven goal mvn install, server runs as expected, but with wrong DB connection. I did not find way, how to set up, that i need use src/test/resources instead of src/main/resources.

Do you know how to set up this plugin in way? I'am open to suggestions of similar solutions, which is simple and do not contains 'lot of' frameworks.

Thank you in advance.

答:
After some investigation i found solution described below.

Three plugins were added into pom.

First plugin will start TomEE server for us.

```<code><plugin>
<groupId>org.apache.tomee.maven</groupId>
<artifactId>tomee-maven-plugin</artifactId>
<version>7.0.4</version>
<executions>
    <execution>
        <id>start</id>
        <phase>pre-integration-test</phase>
        <goals>
            <goal>start</goal>
        </goals>
        <configuration>
            <checkStarted>true</checkStarted>
        </configuration>
    </execution>
    <execution>
        <id>stop</id>
        <phase>post-integration-test</phase>
        <goals>
            <goal>stop</goal>
        </goals>
    </execution>
</executions>
<configuration>
    <simpleLog>true</simpleLog>
</configuration>
</code>```

Second one will replace proper resources and persistence files.

```<code><plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<executions>
    <execution>
        <id>copy-test-persistence</id>
        <phase>process-test-resources</phase>
        <configuration>
            <tasks>
                <!--backup the "proper" files-->
                <copy file="${project.build.outputDirectory}/META-INF/resources.xml" tofile="${project.build.outputDirectory}/META-INF/resources.xml.proper"/>
                <copy file="${project.build.outputDirectory}/META-INF/persistence.xml" tofile="${project.build.outputDirectory}/META-INF/persistence.xml.proper"/>

                <!--replace the "proper" files with the "test" version-->
                <copy file="${project.build.testOutputDirectory}/META-INF/resources.xml" tofile="${project.build.outputDirectory}/META-INF/resources.xml"/>
                <copy file="${project.build.testOutputDirectory}/META-INF/persistence.xml" tofile="${project.build.outputDirectory}/META-INF/persistence.xml"/>

            </tasks>
        </configuration>
        <goals>
            <goal>run</goal>
        </goals>
    </execution>
    <execution>
        <id>restore-persistence</id>
        <phase>prepare-package</phase>
        <configuration>
            <tasks>
                <!--restore the "proper" files -->
                <copy file="${project.build.outputDirectory}/META-INF/resources.xml.proper" tofile="${project.build.outputDirectory}/META-INF/resources.xml"/>
                <copy file="${project.build.outputDirectory}/META-INF/persistence.xml.proper" tofile="${project.build.outputDirectory}/META-INF/persistence.xml"/>
            </tasks>
        </configuration>
        <goals>
            <goal>run</goal>
        </goals>
    </execution>
</executions>
</code>```

Last plugin force 'clean' before install. Without this i had problem in case, when i forget clean project before install.

```<code><plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.4.1</version>
<executions>
    <execution>
        <id>auto-clean</id>
        <phase>initialize</phase>
        <goals>
            <goal>clean</goal>
        </goals>
    </execution>
</executions>
</code>```

Body:
I have J2EE project based on maven. This project contains connection to database, which is set up via resources.xml and persistence.xml. Connection works fine for normal deployment.

My problem is, that i would like to run embedded TomEE server for integration tests. For these tests i need use inmemory database.

To start TomEE i use combination of maven plugins showed below.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>2.13</version>
    <executions>
        <execution>
            <goals>
                <goal>integration-test</goal>
                <goal>verify</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>org.apache.tomee.maven</groupId>
    <artifactId>tomee-maven-plugin</artifactId>
    <version>7.0.4</version>
    <executions>
        <execution>
            <id>start</id>
            <phase>pre-integration-test</phase>
            <goals>
                <goal>start</goal>
            </goals>
            <configuration>
                <checkStarted>true</checkStarted>
            </configuration>
        </execution>
            <execution>
                <id>stop</id>
                <phase>post-integration-test</phase>
                <goals>
                     <goal>stop</goal>
                </goals>
            </execution>
     </executions>
    <configuration>
        <simpleLog>true</simpleLog>
    </configuration>
  </plugin>

When i start maven goal mvn install, server runs as expected, but with wrong DB connection. I did not find way, how to set up, that i need use src/test/resources instead of src/main/resources.

Do you know how to set up this plugin in way? I'am open to suggestions of similar solutions, which is simple and do not contains 'lot of' frameworks.

Thank you in advance.

Body:
After some investigation i found solution described below.

Three plugins were added into pom.

First plugin will start TomEE server for us.

<plugin>
<groupId>org.apache.tomee.maven</groupId>
<artifactId>tomee-maven-plugin</artifactId>
<version>7.0.4</version>
<executions>
    <execution>
        <id>start</id>
        <phase>pre-integration-test</phase>
        <goals>
            <goal>start</goal>
        </goals>
        <configuration>
            <checkStarted>true</checkStarted>
        </configuration>
    </execution>
    <execution>
        <id>stop</id>
        <phase>post-integration-test</phase>
        <goals>
            <goal>stop</goal>
        </goals>
    </execution>
</executions>
<configuration>
    <simpleLog>true</simpleLog>
</configuration>

Second one will replace proper resources and persistence files.

<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<executions>
    <execution>
        <id>copy-test-persistence</id>
        <phase>process-test-resources</phase>
        <configuration>
            <tasks>
                <!--backup the "proper" files-->
                <copy file="${project.build.outputDirectory}/META-INF/resources.xml" tofile="${project.build.outputDirectory}/META-INF/resources.xml.proper"/>
                <copy file="${project.build.outputDirectory}/META-INF/persistence.xml" tofile="${project.build.outputDirectory}/META-INF/persistence.xml.proper"/>

                <!--replace the "proper" files with the "test" version-->
                <copy file="${project.build.testOutputDirectory}/META-INF/resources.xml" tofile="${project.build.outputDirectory}/META-INF/resources.xml"/>
                <copy file="${project.build.testOutputDirectory}/META-INF/persistence.xml" tofile="${project.build.outputDirectory}/META-INF/persistence.xml"/>

            </tasks>
        </configuration>
        <goals>
            <goal>run</goal>
        </goals>
    </execution>
    <execution>
        <id>restore-persistence</id>
        <phase>prepare-package</phase>
        <configuration>
            <tasks>
                <!--restore the "proper" files -->
                <copy file="${project.build.outputDirectory}/META-INF/resources.xml.proper" tofile="${project.build.outputDirectory}/META-INF/resources.xml"/>
                <copy file="${project.build.outputDirectory}/META-INF/persistence.xml.proper" tofile="${project.build.outputDirectory}/META-INF/persistence.xml"/>
            </tasks>
        </configuration>
        <goals>
            <goal>run</goal>
        </goals>
    </execution>
</executions>

Last plugin force 'clean' before install. Without this i had problem in case, when i forget clean project before install.

<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.4.1</version>
<executions>
    <execution>
        <id>auto-clean</id>
        <phase>initialize</phase>
        <goals>
            <goal>clean</goal>
        </goals>
    </execution>
</executions>


问:
Xamarin forms: Load more items without button click
Dears,

I am implementing load more items to listview without a button.

My code:

```<code> public partial class DashBoardPage : ContentPage
  {
ObservableCollection<string> Items;
bool isLoading;

public DashBoardPage()
{
    InitializeComponent();

    Items = new ObservableCollection<string>();
    var listview = new ListView();

    listview.ItemsSource = Items;
    listview.ItemAppearing += (sender, e) =>
    {
        if (isLoading || Items.Count == 0)
            return;

        //hit bottom!
        if (e.Item.ToString() == Items[Items.Count - 1])
        {
            LoadItems();
        }
    };
    LoadItems();
}

public async void LoadItems()
{
    isLoading = true;
    HttpClient client = new HttpClient();
    var response = await client.GetAsync("My Url");
    string tweetJson = await response.Content.ReadAsStringAsync();

    UserTweetResponse userTweetResponse = new UserTweetResponse();
    if (tweetJson != "")
    {
        userTweetResponse = JsonConvert.DeserializeObject<UserTweetResponse>(tweetJson.ToString());
        foreach (var tweet in userTweetResponse.userTweetsList)
                    {
                        Items.Add(tweet.ToString());
                    }
    }
    ListView1.ItemsSource = userTweetResponse.userTweetsList;
    isLoading = false;
}
}
</code>```

I refer the following link and confused with the for loop inside LoadItems():
https://montemagno.com/load-more-items-at-end-of-listview-in/

```<code>for (int i = 0; i < 20; i++)
 {
  Items.Add (string.Format("Item {0}", Items.Count));
 }
</code>```

In my case I am using itemSource property to bind the response to list view.

My model class:

```<code> public class UserTweetResponse
   {
      public List<UserTweetsList> userTweetsList { get; set; }
    }
public class UserTweetsList
{
    public int tweetId { get; set; }
    public string tweetData { get; set; }
    public string createdTime { get; set; }
    public int commentCount { get; set; }
    public int likeCount { get; set; }
    public int flagCount { get; set; }
    public string mediaUrl { get; set; }
    public string tweetUser { get; set; }
    public bool userLiked { get; set; }
    public bool userFlagged { get; set; }
    public bool isMediaUrlNull { get { return string.IsNullOrEmpty(mediaUrl); } }
}
</code>```

How can I fix this?
Thanks in advance

答:
You need to add your new tweets to your Items collection

```<code>public async void LoadItems()
{
    isLoading = true;
    HttpClient client = new HttpClient();
    var response = await client.GetAsync("My Url");
    string tweetJson = await response.Content.ReadAsStringAsync();

    UserTweetResponse userTweetResponse = new UserTweetResponse();
    if (tweetJson != "")
    {
        userTweetResponse = JsonConvert.DeserializeObject<UserTweetResponse>(tweetJson.ToString());
        foreach (var tweet in userTweetResponse.userTweetsList)
        {
            Items.Add(tweet);
        }
    }
    isLoading = false;
}
</code>```

because the Observable collection is the ListView item source the new items will appear in the list.

Body:
Dears,

I am implementing load more items to listview without a button.

My code:

 public partial class DashBoardPage : ContentPage
  {
ObservableCollection<string> Items;
bool isLoading;

public DashBoardPage()
{
    InitializeComponent();

    Items = new ObservableCollection<string>();
    var listview = new ListView();

    listview.ItemsSource = Items;
    listview.ItemAppearing += (sender, e) =>
    {
        if (isLoading || Items.Count == 0)
            return;

        //hit bottom!
        if (e.Item.ToString() == Items[Items.Count - 1])
        {
            LoadItems();
        }
    };
    LoadItems();
}

public async void LoadItems()
{
    isLoading = true;
    HttpClient client = new HttpClient();
    var response = await client.GetAsync("My Url");
    string tweetJson = await response.Content.ReadAsStringAsync();

    UserTweetResponse userTweetResponse = new UserTweetResponse();
    if (tweetJson != "")
    {
        userTweetResponse = JsonConvert.DeserializeObject<UserTweetResponse>(tweetJson.ToString());
        foreach (var tweet in userTweetResponse.userTweetsList)
                    {
                        Items.Add(tweet.ToString());
                    }
    }
    ListView1.ItemsSource = userTweetResponse.userTweetsList;
    isLoading = false;
}
}

I refer the following link and confused with the for loop inside LoadItems():
https://montemagno.com/load-more-items-at-end-of-listview-in/

for (int i = 0; i < 20; i++)
 {
  Items.Add (string.Format("Item {0}", Items.Count));
 }

In my case I am using itemSource property to bind the response to list view.

My model class:

 public class UserTweetResponse
   {
      public List<UserTweetsList> userTweetsList { get; set; }
    }
public class UserTweetsList
{
    public int tweetId { get; set; }
    public string tweetData { get; set; }
    public string createdTime { get; set; }
    public int commentCount { get; set; }
    public int likeCount { get; set; }
    public int flagCount { get; set; }
    public string mediaUrl { get; set; }
    public string tweetUser { get; set; }
    public bool userLiked { get; set; }
    public bool userFlagged { get; set; }
    public bool isMediaUrlNull { get { return string.IsNullOrEmpty(mediaUrl); } }
}

How can I fix this?
Thanks in advance

Body:
You need to add your new tweets to your Items collection

public async void LoadItems()
{
    isLoading = true;
    HttpClient client = new HttpClient();
    var response = await client.GetAsync("My Url");
    string tweetJson = await response.Content.ReadAsStringAsync();

    UserTweetResponse userTweetResponse = new UserTweetResponse();
    if (tweetJson != "")
    {
        userTweetResponse = JsonConvert.DeserializeObject<UserTweetResponse>(tweetJson.ToString());
        foreach (var tweet in userTweetResponse.userTweetsList)
        {
            Items.Add(tweet);
        }
    }
    isLoading = false;
}

because the Observable collection is the ListView item source the new items will appear in the list.


答:
The process to achieving what you want varies depending on whether:

you want to mask the value after the it has been entered or

you want to mask the value during typing.

If you want to do this, after the value has been entered the following should do the trick.

Snippet:

var
  /* The original value. */
  n = "784198012345671",

  /* The masked value. */
  masked = n.slice(0, 3) + Array(8).join("*") + n.slice(-4);

/* Log the result. */
console.log(masked);```
</div>
</div>
</p>

<hr>

<p>If, instead, you want to mask the input during typing, things get more complicated.</p>

<p><strong>Snippet:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(".newsocial").on("keyup", function(e) {
  /* Turn the value into an array of characters. */
  var value = this.value.split("");

  /* Iterate over every character. */
  value.forEach(function (char, index) {
    /* Replace the character with a placeholder when appropriate. */
    if (index >= 3 && index <= 10) value[index] = "*";
  });

  /* Turn the array of chars into a string & assign it to the value of the input. */
  this.value = value.join("");
})</code>```

<input type="text" maxlength="15" id="input-card" class="newsocial">```

Title: Masking number at a particular position

Body:
I have a input field with a maximum length of 15 character.
i want to do something like this

original number :784198012345671
should be:  784********5671

Body:
The process to achieving what you want varies depending on whether:

you want to mask the value after the it has been entered or

you want to mask the value during typing.

If you want to do this, after the value has been entered the following should do the trick.

Snippet:

var
  /* The original value. */
  n = "784198012345671",

  /* The masked value. */
  masked = n.slice(0, 3) + Array(8).join("*") + n.slice(-4);

/* Log the result. */
console.log(masked);

If, instead, you want to mask the input during typing, things get more complicated.

Snippet:

$(".newsocial").on("keyup", function(e) {
  /* Turn the value into an array of characters. */
  var value = this.value.split("");

  /* Iterate over every character. */
  value.forEach(function (char, index) {
    /* Replace the character with a placeholder when appropriate. */
    if (index >= 3 && index <= 10) value[index] = "*";
  });

  /* Turn the array of chars into a string & assign it to the value of the input. */
  this.value = value.join("");
})

<!--- HTML --->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" maxlength="15" id="input-card" class="newsocial">


问:
How to get the select value into the controller
I'm trying to create a simple calculator using Angularjs,in my code I can't get the operator value.How can I fix that?

Home html contains get the two numbers and the operator.User have to select the operator..

my Code -

var name = "myApp";
requires = [];
app = angular.module(name, requires);

app.controller('calcCtrl', function($scope) {
    //$scope.cdata={};

    console.log("calcCtrl works!");
    var opp;
    ans = 0;
    opp = $scope.singleSelect;

    console.log("opp ==> "+opp);

    $scope.calculateNums = function(nu1, nu2) {
        console.log("function works!");
        console.log("nu1 ==> "+nu1);
        console.log("opp in calculateNums ==> "+opp);
        if (opp == "+") {
            ans = (parseInt(nu1) + parseInt(nu2));
            console.log("ans ==> "+ans);
        } else if (opp == "-") {
            ans = (parseInt(nu1) - parseInt(nu2));
        }
        console.log("ans ==> "+ans);
        return ans;
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<h3>Hello</h3>
<div ng-controller='calcCtrl' >
Number 1::<input Type="text" name="number1" ng-model="n1"/ required> <br/>
Number 2::<input Type="text" name="number2" ng-model="n2"/ required> <br/>
operator::<select ng-model="singleSelect">
        <option value="+">+</option>
        <option >*</option>
        <option>-</option>
        <option>/</option>
     </select></p> <br/>

<button ng-click="calculateNums(n1,n2)">Calculate Now</button>
</div>
  </body>
</html></code>```

So, The output I get is -

```<code>calcCtrl works!
opp ==> undefined
function works!
nu1 ==> 1
opp in calculateNums ==> undefined
ans ==> 0
</code>```

the operator values are undefined here..

答:
You can use scope variable directly

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $timeout) {

$scope.calculateNums=function(){
alert($scope.singleSelect)
}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl" >
<select ng-model="singleSelect" >
        <option value="+">+</option>
        <option value="*">*</option>
        <option value="-">-</option>
        <option value="/">/</option>
</select>
<button ng-click="calculateNums()">Calculate</button>
</div></code>```

Body:
I'm trying to create a simple calculator using Angularjs,in my code I can't get the operator value.How can I fix that?

Home html contains get the two numbers and the operator.User have to select the operator..

my Code -

var name = "myApp";
requires = [];
app = angular.module(name, requires);

app.controller('calcCtrl', function($scope) {
    //$scope.cdata={};

    console.log("calcCtrl works!");
    var opp;
    ans = 0;
    opp = $scope.singleSelect;

    console.log("opp ==> "+opp);

    $scope.calculateNums = function(nu1, nu2) {
        console.log("function works!");
        console.log("nu1 ==> "+nu1);
        console.log("opp in calculateNums ==> "+opp);
        if (opp == "+") {
            ans = (parseInt(nu1) + parseInt(nu2));
            console.log("ans ==> "+ans);
        } else if (opp == "-") {
            ans = (parseInt(nu1) - parseInt(nu2));
        }
        console.log("ans ==> "+ans);
        return ans;
    }
});

Hello

Number 1::<input Type="text" name="number1" ng-model="n1"/ required>

Number 2::<input Type="text" name="number2" ng-model="n2"/ required>

operator::<select ng-model="singleSelect">
        <option value="+">+</option>
        <option >*</option>
        <option>-</option>
        <option>/</option>
     </select>

<button ng-click="calculateNums(n1,n2)">Calculate Now</button>

So, The output I get is -

calcCtrl works!
opp ==> undefined
function works!
nu1 ==> 1
opp in calculateNums ==> undefined
ans ==> 0

the operator values are undefined here..

Body:
You can use scope variable directly

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $timeout) {

$scope.calculateNums=function(){
alert($scope.singleSelect)
}
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl" >
<select ng-model="singleSelect" >
        <option value="+">+</option>
        <option value="*">*</option>
        <option value="-">-</option>
        <option value="/">/</option>
</select>
<button ng-click="calculateNums()">Calculate</button>
</div>


问:
Map Recyclerview inside scrollview display black flickering background while scrolling
I have used map view inside recyclerview row.
I have attached screenshot.
While scrolling maps display black flickering background.

Adapter code:

```<code> @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TASK_VIEW) {
            return new TasksViewHolder(LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_task_row, parent, false));
        } else if (viewType == CHECKIN_VIEW) {
            return new CheckInViewHolder(LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_checkin_row, parent, false));
        } else {
            return null;
        }
    }

@Override
private void onBindCheckInViewHolder(CheckInViewHolder holder, int position) {
    final JobCheckIn singleCheckIn = (JobCheckIn) items.get(position);
    holder.location.setText(singleCheckIn.getAddress());

    holder.lastUpdated.setText(String.valueOf("Created " +
            activity.getDateTime(singleCheckIn.getCreatedDateTime())));

    holder.deleteTask.setOnClickListener(view -> jobInterface.deleteCheckIn(singleCheckIn.getId()));

    float f = 0.0f;
    if (holder.mapView != null && Float.compare(singleCheckIn.getLatitude(), f) != 0 &&
            Float.compare(singleCheckIn.getLongitude(), f) != 0) {
        holder.mapView.setVisibility(View.VISIBLE);
        holder.initializeMapView();
        if (holder.gMap != null) {
            // The map is already ready to be used
            moveMap(holder.gMap, singleCheckIn.getLatitude(), singleCheckIn.getLongitude());
        }
    }

}
   public class CheckInViewHolder extends RecyclerView.ViewHolder implements OnMapReadyCallback {

    MapView mapView;

    GoogleMap gMap;

    public CheckInViewHolder(View view) {
        super(view);
        mapView = view.findViewById(R.id.checkInMapView);

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        MapsInitializer.initialize(context);
        gMap = googleMap;
        googleMap.getUiSettings().setMapToolbarEnabled(false);
        if(items.get(getLayoutPosition())!=null )
            moveMap(gMap,((JobCheckIn) items.get(getLayoutPosition())).getLatitude(), ((JobCheckIn) items.get(getLayoutPosition())).getLongitude());
    }
    public void initializeMapView() {
        if (mapView != null) {
            // Initialise the MapView
            mapView.onCreate(null);
            // Set the map ready callback to receive the GoogleMap object
            mapView.getMapAsync(this);

        }
    }
}
 public void moveMap(GoogleMap gMap, double latitude, double longitude) {
    Log.v(TAG, "mapMoved: " + gMap);
    LatLng latlng = new LatLng(latitude, longitude);
    CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(latlng, 6);
    gMap.addMarker(new MarkerOptions().position(latlng));
    gMap.moveCamera(cu);
}
</code>```

I refer this link: Link
  but in this demo they used array adapter in my code we have used recyclerview adapter.

xml code:

```<code> <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="150dp">

            <com.google.android.gms.maps.MapView
                android:id="@+id/checkInMapView"
                android:layout_width="0dp"
                android:layout_height="150dp"
                android:layout_weight="1"
                android:enabled="true"
                android:visibility="gone"
                map:cameraZoom="15"
                map:liteMode="true"
                map:mapType="normal" />

         <!--   I have also tried adding transparent view as below but still no solution.

        <View
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/transparent"/>-->

        </LinearLayout>
</code>```

I am not performing any zoom-In, Zoom-out or drag.
  Thanks in advance.

Google Issue Track

Update

Previously i was initializing map in viewHolder instead of mentioned as above scenario.

```<code> onBindCheckInViewHolder(...){
 holder.mapView.onCreate(null);
            holder.mapView.getMapAsync(googleMap -> {
                MapsInitializer.initialize(context);
                gMap = googleMap;
                googleMap.getUiSettings().setMapToolbarEnabled(false);
                moveMap(gMap, singleCheckIn.getLatitude(), singleCheckIn.getLongitude());
            });
      }
</code>```

答:
MapView is a pretty heavy view and when you try to get a bunch of them on the screen then app will become sluggish while scrolling. you can pass data such as the latitude and longitude as a string with some static variables taken from the link mentioned below. you can get co-ordinates from the Facebook API.
This is the api link  https://developers.google.com/maps/documentation/staticmaps/.

```<code> String getMapURL = "http://maps.googleapis.com/maps/api/staticmap?zoom=
                    18&size=560x240&markers=size:mid|color:red|"
                    + JOLocation.getString("latitude") + "," + JOLocation.getString("longitude")
                    + "&sensor=false";
</code>```

The above constructed URL, when you used in a browser, returns a .PNG file.
Similar type of issue was discussed here in this link MapView in Listview check it. Hope it helps

Body:
I have used map view inside recyclerview row.
I have attached screenshot.
While scrolling maps display black flickering background.

Adapter code:

 @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TASK_VIEW) {
            return new TasksViewHolder(LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_task_row, parent, false));
        } else if (viewType == CHECKIN_VIEW) {
            return new CheckInViewHolder(LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_checkin_row, parent, false));
        } else {
            return null;
        }
    }

@Override
private void onBindCheckInViewHolder(CheckInViewHolder holder, int position) {
    final JobCheckIn singleCheckIn = (JobCheckIn) items.get(position);
    holder.location.setText(singleCheckIn.getAddress());

    holder.lastUpdated.setText(String.valueOf("Created " +
            activity.getDateTime(singleCheckIn.getCreatedDateTime())));

    holder.deleteTask.setOnClickListener(view -> jobInterface.deleteCheckIn(singleCheckIn.getId()));

    float f = 0.0f;
    if (holder.mapView != null && Float.compare(singleCheckIn.getLatitude(), f) != 0 &&
            Float.compare(singleCheckIn.getLongitude(), f) != 0) {
        holder.mapView.setVisibility(View.VISIBLE);
        holder.initializeMapView();
        if (holder.gMap != null) {
            // The map is already ready to be used
            moveMap(holder.gMap, singleCheckIn.getLatitude(), singleCheckIn.getLongitude());
        }
    }

}
   public class CheckInViewHolder extends RecyclerView.ViewHolder implements OnMapReadyCallback {

    MapView mapView;

    GoogleMap gMap;

    public CheckInViewHolder(View view) {
        super(view);
        mapView = view.findViewById(R.id.checkInMapView);

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        MapsInitializer.initialize(context);
        gMap = googleMap;
        googleMap.getUiSettings().setMapToolbarEnabled(false);
        if(items.get(getLayoutPosition())!=null )
            moveMap(gMap,((JobCheckIn) items.get(getLayoutPosition())).getLatitude(), ((JobCheckIn) items.get(getLayoutPosition())).getLongitude());
    }
    public void initializeMapView() {
        if (mapView != null) {
            // Initialise the MapView
            mapView.onCreate(null);
            // Set the map ready callback to receive the GoogleMap object
            mapView.getMapAsync(this);

        }
    }
}
 public void moveMap(GoogleMap gMap, double latitude, double longitude) {
    Log.v(TAG, "mapMoved: " + gMap);
    LatLng latlng = new LatLng(latitude, longitude);
    CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(latlng, 6);
    gMap.addMarker(new MarkerOptions().position(latlng));
    gMap.moveCamera(cu);
}

I refer this link: Link
  but in this demo they used array adapter in my code we have used recyclerview adapter.

xml code:

 <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="150dp">

            <com.google.android.gms.maps.MapView
                android:id="@+id/checkInMapView"
                android:layout_width="0dp"
                android:layout_height="150dp"
                android:layout_weight="1"
                android:enabled="true"
                android:visibility="gone"
                map:cameraZoom="15"
                map:liteMode="true"
                map:mapType="normal" />

        </LinearLayout>

I am not performing any zoom-In, Zoom-out or drag.
  Thanks in advance.

Google Issue Track

Update

Previously i was initializing map in viewHolder instead of mentioned as above scenario.

 onBindCheckInViewHolder(...){
 holder.mapView.onCreate(null);
            holder.mapView.getMapAsync(googleMap -> {
                MapsInitializer.initialize(context);
                gMap = googleMap;
                googleMap.getUiSettings().setMapToolbarEnabled(false);
                moveMap(gMap, singleCheckIn.getLatitude(), singleCheckIn.getLongitude());
            });
      }

Body:
MapView is a pretty heavy view and when you try to get a bunch of them on the screen then app will become sluggish while scrolling. you can pass data such as the latitude and longitude as a string with some static variables taken from the link mentioned below. you can get co-ordinates from the Facebook API.
This is the api link  https://developers.google.com/maps/documentation/staticmaps/.

 String getMapURL = "http://maps.googleapis.com/maps/api/staticmap?zoom=
                    18&size=560x240&markers=size:mid|color:red|"
                    + JOLocation.getString("latitude") + "," + JOLocation.getString("longitude")
                    + "&sensor=false";

The above constructed URL, when you used in a browser, returns a .PNG file.
Similar type of issue was discussed here in this link MapView in Listview check it. Hope it helps


答:
Convert your number to string and use string.prototype.substring and string.prototype.repeate to build parts:

var number = 784198012345671;
number = number.toString();
var res = number.substring(0, 3) + '*'.repeat(8) + number.substring(11, 15);
console.log(res);```

Title: Masking number at a particular position


问:
Zeppelin notebooks on Windows 7
I have failed to install Apache Zeppelin (v. 0.7.1) on my Windows 7 desktop.
I would like to proceed without having to install Docker, however.
I tried reinstalling the Java runtime etc. but Zeppelin does not start.
Any suggestions?

(I am aware of version 0.7.3 but don't feel like wasting even more time trying it on Windows 7).

答: Please share the errors your are getting. Confirm you have made all the settings (environmental or otherwise) as required. </p>

Title: Zeppelin notebooks on Windows 7


问:
jboss 7, how to set thread pool size for http connector
In jboss7, how to set the thread pool size for the http and https connectors. I am using standalone.xml for setting changes. Can anyone help me.

Thanks in Advance.

答:
You can configure it like this using maxThreads parameter:

```<code><subsystem xmlns="urn:jboss:domain:web:1.1" default-virtual-server="default-host" native="false" >

<connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http" maxThreads="300" />
</code>```

API documentation from jBoss site:

maxThread:(int) The max number of active threads in this pool, default is 200

Body:
You can configure it like this using maxThreads parameter:

<subsystem xmlns="urn:jboss:domain:web:1.1" default-virtual-server="default-host" native="false" >

<connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http" maxThreads="300" />

API documentation from jBoss site:

maxThread:(int) The max number of active threads in this pool, default is 200


问:
How to get exact latitude and longitude using GPS tracker?
I am getting lat-long using GPS tracker but I am not getting my exact current location what I am getting is location 50 meter away from my current location I am using GPS Tracker only.each and every answer will be appreciable.my location is not getting varied from device to device as per mentioned in previous question.and i did not get any helpful answer their.  </p>

答:
You can use FusedLocationProviderClient from Google location api
just apply location library in gradle(app level).

```<code>compile 'com.google.android.gms:play-services-location:11.6.0'
</code>```

and at the bottom of app level gradle add this line

```<code>apply plugin: 'com.google.gms.google-services'
</code>```

Here is my code in mainActivity

```<code>public class MainActivity extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
FusedLocationProviderClient mFusedLocationClient;

private static final String TAG="Logs Details";

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

     buildGoogleApiClient();
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    return super.onStartCommand(intent, flags, startId);

}

@Override
public void onCreate() {
    super.onCreate();

}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    Log.e(TAG,"app is connected");

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(10000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
    }

}
LocationCallback mLocationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        for (Location location : locationResult.getLocations()) {
            mLastLocation = location;

            Log.e("latitude",location.latitude);
            Log.e("longitude",location.longitude);

        }
    }

};

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
</code>```

}

Hope this helps.:)

Body:
You can use FusedLocationProviderClient from Google location api
just apply location library in gradle(app level).

compile 'com.google.android.gms:play-services-location:11.6.0'

and at the bottom of app level gradle add this line

apply plugin: 'com.google.gms.google-services'

Here is my code in mainActivity

public class MainActivity extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
FusedLocationProviderClient mFusedLocationClient;

private static final String TAG="Logs Details";

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

     buildGoogleApiClient();
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    return super.onStartCommand(intent, flags, startId);

}

@Override
public void onCreate() {
    super.onCreate();

}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    Log.e(TAG,"app is connected");

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(10000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
    }

}
LocationCallback mLocationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        for (Location location : locationResult.getLocations()) {
            mLastLocation = location;

            Log.e("latitude",location.latitude);
            Log.e("longitude",location.longitude);

        }
    }

};

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

}

Hope this helps.:)


问:
Tracking all incoming network traffic on a unbuntu server
I would like to track all incoming traffic on a ubuntu web server, first by the address they are requesting and their ip address.

Is there any way to do so?

Thanks,
Ray

答:
This is a very open ended question.

If you are interested in recorded ALL traffic to saving it for future analysis, TCPDump is the way to go. File rotation and timestamps can be taken care of for you with the proper flags. http://www.tcpdump.org/

If you are looking for Source/Dest IP and port logging, netflow is more convenient as it takes less resources and disk space to manage. This can be accomplished through nProbe http://www.ntop.org/nProbe.html or nfcapd http://manpages.ubuntu.com/manpages/intrepid/man1/nfcapd.1.html

You can always capture IP/port information from your router/firewall. This is probably the easiest.

ContentLicense: CC BY-SA 2.5


问:
How can I modify my UILabel subclass so that it can accept custom values?
This is my current class.

```<code>class PaddedUILabel: UILabel {
    var padding = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8)

    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, padding))
    }

    // Override -intrinsicContentSize: for Auto layout code
    override var intrinsicContentSize : CGSize {
        let superContentSize = super.intrinsicContentSize
        let width = superContentSize.width + padding.left + padding.right
        let heigth = superContentSize.height + padding.top + padding.bottom
        return CGSize(width: width, height: heigth)
    }

    // Override -sizeThatFits: for Springs & Struts code
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        let superSizeThatFits = super.sizeThatFits(size)
        let width = superSizeThatFits.width + padding.left + padding.right
        let heigth = superSizeThatFits.height + padding.top + padding.bottom
        return CGSize(width: width, height: heigth)
    }
}
</code>```

Right now, the paddings are hardcoded.  I'd like to be able to set custom values in StoryBoard UI (top, left, bottom, right).

What can I do to my code to modify this?

答:
```<code>import Foundation

@IBDesignable class UILabelExtendedView: UILabel {
@IBInspectable var topInset: CGFloat = 4.0
@IBInspectable var bottomInset: CGFloat = 4.0
@IBInspectable var leftInset: CGFloat = 8.0
@IBInspectable var rightInset: CGFloat = 8.0

override func drawText(in rect: CGRect) {
    let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
    super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}

override public var intrinsicContentSize: CGSize {
    var contentSize = super.intrinsicContentSize
    contentSize.height += topInset + bottomInset
    contentSize.width += leftInset + rightInset
    return contentSize
}

func setPadding(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) {
    self.topInset = top
    self.bottomInset = bottom
    self.leftInset = left
    self.rightInset = right
    let insets: UIEdgeInsets = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)
    super.drawText(in: UIEdgeInsetsInsetRect(self.frame, insets))
}}
</code>```

Pass this class name to your label in storyboard and in attribute inspector set your padding.

Body:
This is my current class.

class PaddedUILabel: UILabel {
    var padding = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8)

    override func drawText(in rect: CGRect) {
        super.drawText(in: UIEdgeInsetsInsetRect(rect, padding))
    }

    // Override -intrinsicContentSize: for Auto layout code
    override var intrinsicContentSize : CGSize {
        let superContentSize = super.intrinsicContentSize
        let width = superContentSize.width + padding.left + padding.right
        let heigth = superContentSize.height + padding.top + padding.bottom
        return CGSize(width: width, height: heigth)
    }

    // Override -sizeThatFits: for Springs & Struts code
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        let superSizeThatFits = super.sizeThatFits(size)
        let width = superSizeThatFits.width + padding.left + padding.right
        let heigth = superSizeThatFits.height + padding.top + padding.bottom
        return CGSize(width: width, height: heigth)
    }
}

Right now, the paddings are hardcoded.  I'd like to be able to set custom values in StoryBoard UI (top, left, bottom, right).

What can I do to my code to modify this?

Body:
import Foundation

@IBDesignable class UILabelExtendedView: UILabel {
@IBInspectable var topInset: CGFloat = 4.0
@IBInspectable var bottomInset: CGFloat = 4.0
@IBInspectable var leftInset: CGFloat = 8.0
@IBInspectable var rightInset: CGFloat = 8.0

override func drawText(in rect: CGRect) {
    let insets: UIEdgeInsets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
    super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}

override public var intrinsicContentSize: CGSize {
    var contentSize = super.intrinsicContentSize
    contentSize.height += topInset + bottomInset
    contentSize.width += leftInset + rightInset
    return contentSize
}

func setPadding(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) {
    self.topInset = top
    self.bottomInset = bottom
    self.leftInset = left
    self.rightInset = right
    let insets: UIEdgeInsets = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)
    super.drawText(in: UIEdgeInsetsInsetRect(self.frame, insets))
}}

Pass this class name to your label in storyboard and in attribute inspector set your padding.


问:
Binary Tree, Binary Search Tree, Binary search
I am trying to understand the Binary tree and referring to online material , and questions asked in SO.

I understood that:

Binary tree -> Tree in which each node can have at most 2 nodes.

Binary search tree -> Specialized form of Binary tree in which left node value < parent node and right node value > parent node

Do we have a thing called as Binary search ?

If Binary search tree is a data structure, why it has "search" in it? It gives a feeling as if it is an algorithm?

I am still not clear, can anyone help clear the doubts.

EDIT

This is not duplicate of the SO question appearing, it is about asking 'search' leading to misnomer.

答:
There is a searching algorithm called Binary search which performs in O(log n). The Binary search tree is a data structure that seeks to facilitate searching (Binary search) since node values are ranked in this order: left < parent < right.
However a binary search tree could be unbalanced which means that difference of height between left child and right child > 1. Enters more efficient (in terms of searching performance) binary search trees called Self-balancing binary search tree that automatically adjust its height following insertions and deletions.


问:
startActivities(android.content.Intent[]) in Activity cannot be Applied to (android.content.Intent)
I try to do one simple application, in that Intent Not working, it shows this error:

startActivities(android.content.Intent[]) in Activity cannot be Applied to (android.content.Intent)

Why?

See below my code:

```<code>public class SplashActivity extends Activity implements Animation.AnimationListener {
        ImageView imageView;
        Button button;
        Animation animationbounce;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_splash);
                imageView = (ImageView)findViewById(R.id.face);
                button = (Button)findViewById(R.id.splash);
                animationbounce = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.bounce);
                animationbounce.setAnimationListener(this);
                imageView.setVisibility(View.VISIBLE);
                imageView.startAnimation(animationbounce);
                animationbounce.setRepeatMode(Animation.REVERSE);

                button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                        imageView.setVisibility(View.VISIBLE);
                        imageView.startAnimation(animationbounce);
                }
                });

                Thread timerThread = new Thread() {

                public void run() {

                try {
                        sleep(1000);

                } catch (InterruptedException e) {
                        e.printStackTrace();
                } finally {

                    Intent intents = new Intent(SplashActivity.this, MainActivity.class);
                    SplashActivity.this.startActivities(intents);
                    // startActivities(intents);

                        }
                }
        };
        timerThread.start();
        }

@Override
public void onAnimationStart(Animation animation) {
    imageView.setVisibility(View.VISIBLE);
    imageView.startAnimation(animationbounce);
        }

@Override
public void onAnimationEnd(Animation animation) {
        if(animation==animationbounce)
        {
            imageView.setVisibility(View.VISIBLE);
            imageView.startAnimation(animationbounce);
        }

        }

@Override
public void onAnimationRepeat(Animation animation) {

    imageView.setVisibility(View.VISIBLE);
    imageView.startAnimation(animationbounce);
        }
        }
</code>```

答:
Try This it is working for me

Button = (ImageButton) findViewById(R.id.button);
 Button.setOnClickListener(new View.OnClickListener() {
 public void onClick(View view) {
                startActivities(new Intent[]{new  Intent(getApplicationContext(), NextActivity.class)});

Body:
I try to do one simple application, in that Intent Not working, it shows this error:

startActivities(android.content.Intent[]) in Activity cannot be Applied to (android.content.Intent)

Why?

See below my code:

public class SplashActivity extends Activity implements Animation.AnimationListener {
        ImageView imageView;
        Button button;
        Animation animationbounce;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_splash);
                imageView = (ImageView)findViewById(R.id.face);
                button = (Button)findViewById(R.id.splash);
                animationbounce = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.bounce);
                animationbounce.setAnimationListener(this);
                imageView.setVisibility(View.VISIBLE);
                imageView.startAnimation(animationbounce);
                animationbounce.setRepeatMode(Animation.REVERSE);

                button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                        imageView.setVisibility(View.VISIBLE);
                        imageView.startAnimation(animationbounce);
                }
                });

                Thread timerThread = new Thread() {

                public void run() {

                try {
                        sleep(1000);

                } catch (InterruptedException e) {
                        e.printStackTrace();
                } finally {

                    Intent intents = new Intent(SplashActivity.this, MainActivity.class);
                    SplashActivity.this.startActivities(intents);
                    // startActivities(intents);

                        }
                }
        };
        timerThread.start();
        }

@Override
public void onAnimationStart(Animation animation) {
    imageView.setVisibility(View.VISIBLE);
    imageView.startAnimation(animationbounce);
        }

@Override
public void onAnimationEnd(Animation animation) {
        if(animation==animationbounce)
        {
            imageView.setVisibility(View.VISIBLE);
            imageView.startAnimation(animationbounce);
        }

        }

@Override
public void onAnimationRepeat(Animation animation) {

    imageView.setVisibility(View.VISIBLE);
    imageView.startAnimation(animationbounce);
        }
        }


问:
How to create a rectangle inside each grid's column in Extjs?
I have this grid and would like to put all of the values from Box column inside a rectangle using metadata.style , tdCls or CSS. My issue is that I don't want to color the entire column (cell), I only want to color the value inside of it by wrapping it in a rectangle, and if the value of the column is empty then just show an empty rectangle.
Here's an example of what I want for each column (cell) to look like under the Box column:

Here's the working code : FIDDLE

```<code>       switch(recordStatus) {
         case 'Checked-In':
            backgroundColor = "#B4B4D6";
            metadata.style = 'background-color: ' + backgroundColor + ';';
            return val;
            break;
             ...
        }
</code>```

Thank you so much in advance!

答:
You need to return html from your renderer method and provide style as per you requirement.

In this FIDDLE, I have modified some changes in your code as per you requirement. I hope it is same as per your requirement.

JS code

```<code>var data = Ext.decode('[{"box":"","name":"Brady, Marsha","status":"Checked-In"},{"box":"MA","name":"Dwight, Schrute","status":"With MA"},{"box":"MA","name":"Jim, Halpert","status":"With MA"},{"box":"MA","name":"Mike, Brown","status":"With MA"},{"box":"MA","name":"Steve, Smith","status":"With MA"},{"box":"MA","name":"Lori, Morrison","status":"With MA"},{"box":"MA","name":"Mary, Loson","status":"With MA"},{"box":"MA","name":"Junior, Meloni","status":"With MA"},{"box":"MA","name":"Jim, Halpert","status":"With MA"},{"box":"","name":"Kevin, Malone","status":"Checked-In"},{"box":"","name":"Angela, Martin","status":"Checked-In"},{"box":"2","name":"Jim, Halpert","status":"Ready for MA"},{"box":"2","name":"Kevin, Malone","status":"Ready for MA"},{"box":"2","name":"Angela, Martin","status":"Ready for MA"}]'),//Store Data
    //Create store
    store = Ext.create('Ext.data.Store', {
        fields: ['name', 'box', 'status'],
        data: data,
        groupField: 'status'
    }),
    //create grid
    grid = Ext.create('Ext.grid.Panel', {
        height: 450,
        frame: true,
        title: 'Sponsored Projects',
        iconCls: 'icon-grid',
        renderTo: document.body,
        store: store,
        features: [{
            ftype: 'grouping',
        }],
        columns: [{
            text: 'Box',
            renderer: function (val, metadata, record) {
                var recordStatus = record.get('status'),
                    style = 'border:1px solid #cccccc';
                if (val) {
                    switch (recordStatus) {
                    case 'Checked-In':
                        style = "background-color:#B4B4D6";
                        break;
                    case 'With MA':
                        style = "background-color:#CBC5EB";
                        break;
                    case 'Ready for MA':
                        style = "background-color:#E3E1ED";
                        break;
                    default:
                        style = '';
                    }
                }
                metadata.style = "text-align: center;";
                return `<div class="x-box-div" style="${style}">${val}</div>`
            },
            dataIndex: 'box',
            flex: 0.5
        }, {
            text: 'Name',
            renderer: function (value, metaData) {
                return value.replace(value, '<u><b>' + value.toUpperCase() + '</b></u>');
            },
            dataIndex: 'name',
            flex: 2
        }, {
            text: 'Status',
            dataIndex: 'status',
            flex: 1
        }]
    });
</code>```

CSS code

```<code><style>
    .x-box-div {
        min-width: 30px;
        min-height: 30px;
        text-align: center;
        display: inline-block;
        vertical-align: middle;
        padding: 10px 0;
        max-height: 30px;
    }

</style>
</code>```

Body:
I have this grid and would like to put all of the values from Box column inside a rectangle using metadata.style , tdCls or CSS. My issue is that I don't want to color the entire column (cell), I only want to color the value inside of it by wrapping it in a rectangle, and if the value of the column is empty then just show an empty rectangle.
Here's an example of what I want for each column (cell) to look like under the Box column:

Here's the working code : FIDDLE

       switch(recordStatus) {
         case 'Checked-In':
            backgroundColor = "#B4B4D6";
            metadata.style = 'background-color: ' + backgroundColor + ';';
            return val;
            break;
             ...
        }

Thank you so much in advance!

Body:
You need to return html from your renderer method and provide style as per you requirement.

In this FIDDLE, I have modified some changes in your code as per you requirement. I hope it is same as per your requirement.

JS code

var data = Ext.decode('[{"box":"","name":"Brady, Marsha","status":"Checked-In"},{"box":"MA","name":"Dwight, Schrute","status":"With MA"},{"box":"MA","name":"Jim, Halpert","status":"With MA"},{"box":"MA","name":"Mike, Brown","status":"With MA"},{"box":"MA","name":"Steve, Smith","status":"With MA"},{"box":"MA","name":"Lori, Morrison","status":"With MA"},{"box":"MA","name":"Mary, Loson","status":"With MA"},{"box":"MA","name":"Junior, Meloni","status":"With MA"},{"box":"MA","name":"Jim, Halpert","status":"With MA"},{"box":"","name":"Kevin, Malone","status":"Checked-In"},{"box":"","name":"Angela, Martin","status":"Checked-In"},{"box":"2","name":"Jim, Halpert","status":"Ready for MA"},{"box":"2","name":"Kevin, Malone","status":"Ready for MA"},{"box":"2","name":"Angela, Martin","status":"Ready for MA"}]'),//Store Data
    //Create store
    store = Ext.create('Ext.data.Store', {
        fields: ['name', 'box', 'status'],
        data: data,
        groupField: 'status'
    }),
    //create grid
    grid = Ext.create('Ext.grid.Panel', {
        height: 450,
        frame: true,
        title: 'Sponsored Projects',
        iconCls: 'icon-grid',
        renderTo: document.body,
        store: store,
        features: [{
            ftype: 'grouping',
        }],
        columns: [{
            text: 'Box',
            renderer: function (val, metadata, record) {
                var recordStatus = record.get('status'),
                    style = 'border:1px solid #cccccc';
                if (val) {
                    switch (recordStatus) {
                    case 'Checked-In':
                        style = "background-color:#B4B4D6";
                        break;
                    case 'With MA':
                        style = "background-color:#CBC5EB";
                        break;
                    case 'Ready for MA':
                        style = "background-color:#E3E1ED";
                        break;
                    default:
                        style = '';
                    }
                }
                metadata.style = "text-align: center;";
                return `<div class="x-box-div" style="${style}">${val}</div>`
            },
            dataIndex: 'box',
            flex: 0.5
        }, {
            text: 'Name',
            renderer: function (value, metaData) {
                return value.replace(value, '<u><b>' + value.toUpperCase() + '</b></u>');
            },
            dataIndex: 'name',
            flex: 2
        }, {
            text: 'Status',
            dataIndex: 'status',
            flex: 1
        }]
    });

CSS code

<style>
    .x-box-div {
        min-width: 30px;
        min-height: 30px;
        text-align: center;
        display: inline-block;
        vertical-align: middle;
        padding: 10px 0;
        max-height: 30px;
    }

</style>


问:
Angular2 router (@angular/router), how to set default route?
How can I set a default route in my @Routes route metadata collection?  If you use the angular2 router from @angular/router-deprecated you define the routes in @routeConfig object, which is a collection of route objects, but these route objects have more attributes on them.  For instance they have 'name' and 'useAsDefualt' attributes whereas the routes defined out of @angular/router do not.  I would like to write my new app using the new router, but how do i use the new router and set a default route?

This is my main app component which defines my routes:

```<code>import { Component } from '@angular/core';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ConfigManagerComponent } from './configManager/configManager.component';
import { ApplicationMgmtComponent } from './applicationMgmt/applicationMgmt.component';
import { MergeComponent } from './merge/merge.component';

import { ROUTER_DIRECTIVES, Routes } from '@angular/router';

@Component({
    selector: 'app-container',
    templateUrl: 'app/app.component.html',
    directives: [ROUTER_DIRECTIVES]
})

@Routes([

        { path: '/Dashboard', component: DashboardComponent },
        { path: '/ConfigManager', component: ConfigManagerComponent },
        { path: '/Merge', component: MergeComponent },
        { path: '/ApplicationManagement', component: ApplicationMgmtComponent }
])

export class AppComponent { }
</code>```

The route definitions seem to be working fine, when I click on anchor tags like this one:

```<code><li class="nav hidden-xs"><a [routerLink]="['./Dashboard']">Dashboard</a>/li>
</code>```

It transitions to the associated route.  My only issue is that when my app loads it doesn't have a route active.  How do i define a default route that is active when my app bootstraps?

Thanks!

答:
I faced same issue apply all possible solution but finally this solve my problem

```<code>export class AppRoutingModule {
constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        this.router.navigate(['404']); // or redirect to default route
    }
  }
}
</code>```

Hope this will help you.

Body:
How can I set a default route in my @Routes route metadata collection?  If you use the angular2 router from @angular/router-deprecated you define the routes in @routeConfig object, which is a collection of route objects, but these route objects have more attributes on them.  For instance they have 'name' and 'useAsDefualt' attributes whereas the routes defined out of @angular/router do not.  I would like to write my new app using the new router, but how do i use the new router and set a default route?

This is my main app component which defines my routes:

import { Component } from '@angular/core';
import { DashboardComponent } from './dashboard/dashboard.component';
import { ConfigManagerComponent } from './configManager/configManager.component';
import { ApplicationMgmtComponent } from './applicationMgmt/applicationMgmt.component';
import { MergeComponent } from './merge/merge.component';

import { ROUTER_DIRECTIVES, Routes } from '@angular/router';

@Component({
    selector: 'app-container',
    templateUrl: 'app/app.component.html',
    directives: [ROUTER_DIRECTIVES]
})

@Routes([

        { path: '/Dashboard', component: DashboardComponent },
        { path: '/ConfigManager', component: ConfigManagerComponent },
        { path: '/Merge', component: MergeComponent },
        { path: '/ApplicationManagement', component: ApplicationMgmtComponent }
])

export class AppComponent { }

The route definitions seem to be working fine, when I click on anchor tags like this one:

Dashboard/li>

It transitions to the associated route.  My only issue is that when my app loads it doesn't have a route active.  How do i define a default route that is active when my app bootstraps?

Thanks!

Body:
I faced same issue apply all possible solution but finally this solve my problem

export class AppRoutingModule {
constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        this.router.navigate(['404']); // or redirect to default route
    }
  }
}

Hope this will help you.


问:
Refresh NetSuite portlet on save/submit
I have created a PortLet to create task in NetSuite. And new task getting create when an user press Submit button, but  portlet not geting refresh automatially. Every time user need to refreash portlet manully. Is there any way to refresh portlet on submit?</p>

```<code>function formCreateTaskPL(portlet, column) {
var user = 257;
var entityid = 1985;
var trandate = nlapiDateToString(new Date());
var contact = 201;

portlet.setTitle('Quick Add Task');

var fld = portlet.addField('custpage_cust', 'text', 'Customet');
fld.setDefaultValue(entityid);

var fld = portlet.addField('custpage_user', 'text', 'User');
fld.setDefaultValue(user);

var fld = portlet.addField('custpage_date', 'date', 'Date');
fld.setDefaultValue(trandate);

var fld = portlet.addField('custpage_contact','text','Contact');
fld.setDefaultValue(contact);

var fld = portlet.addField('custpage_title', 'text', 'Title');
var fld = portlet.addField('custpage_text', 'longtext', 'Detail');

var url = nlapiResolveURL('SUITELET', 'customscript_create_task','customdeploy_create_task');

portlet.setSubmitButton(url, 'Submit');

}
</code>```

答:
try this
https://chrome.google.com/webstore/detail/netsuite-portlet-refreshe/odpaehonnmgmjkneccjjhgaoannpnghg

If you install this plugin ,Refreshes the portlets in your Netsuite Dashboard Automatically every time you login or access your netsuite Home Page.

ContentLicense: CC BY-SA 4.0

Title: Refresh NetSuite portlet on save/submit

Body:
I have created a PortLet to create task in NetSuite. And new task getting create when an user press Submit button, but  portlet not geting refresh automatially. Every time user need to refreash portlet manully. Is there any way to refresh portlet on submit?

function formCreateTaskPL(portlet, column) {
var user = 257;
var entityid = 1985;
var trandate = nlapiDateToString(new Date());
var contact = 201;

portlet.setTitle('Quick Add Task');

var fld = portlet.addField('custpage_cust', 'text', 'Customet');
fld.setDefaultValue(entityid);

var fld = portlet.addField('custpage_user', 'text', 'User');
fld.setDefaultValue(user);

var fld = portlet.addField('custpage_date', 'date', 'Date');
fld.setDefaultValue(trandate);

var fld = portlet.addField('custpage_contact','text','Contact');
fld.setDefaultValue(contact);

var fld = portlet.addField('custpage_title', 'text', 'Title');
var fld = portlet.addField('custpage_text', 'longtext', 'Detail');

var url = nlapiResolveURL('SUITELET', 'customscript_create_task','customdeploy_create_task');

portlet.setSubmitButton(url, 'Submit');

}


问:
How to use multiple aggregate function with group by
I have three tables in advertiser,advertiser_clicks and advertiser_cost in which i have used join with multiple aggregate function.But i was unable to get the actual record from the tables.Please find below my table structure.

Table1:advertiser

```<code>................
id      name
................
1     Your Survey
2     Vindale
</code>```

Table2:advertiser_clicks
In this table adv_id is foreign key of advertiser table id

```<code>.............................................................
id    adv_id    survey_id   survey_name  clicks  dt_datetime
.............................................................
1       1        101        survey1       1       2017-11-30
2       2        102        survey2       1       2017-11-29
3       1        103        survey3       1       2017-11-28
</code>```

Table3:advertiser_cost
In this table a_click_id is the foreign key of advertiser_clicks table adv_id

```<code>.......................................................
ac_id   a_click_id   cpi    conversion  cost   profit
......................................................
  1       1          10       1           8      2
  2       2          10       1           5      5
  3       3          5        1           5      5
</code>```

I want below output:-when i select start date:2017-11-29 and enddate :2017-11-30 in where condition then i want below output.Here total click,cpi,cost & profit is the sum of all the data which comes in between that daterange.

```<code>.............................................................
adv_id    advertiser     totalclick    cpi    cost   profit
.............................................................
   1       Your survey       2          20     13     8
   2        vindale          0           0     0      0
</code>```

I have write the below query which returns the exact data which comes
in between that date range but i it will not return the record of vindale
advertiser as a zero value.Please find my below query.

```<code>SELECT sum(advertiser_clicks.`clicks`) as totalclick,sum(advertiser_cost.cpi) as revenue,sum(advertiser_cost.`conversion`) as conversion,sum(advertiser_cost.`cost`) as cost,SUM(advertiser_cost.profit) as profit,advertiser.name as advertiser,advertiser.id as adv_id FROM `advertiser_clicks` LEFT JOIN advertiser_cost on advertiser_cost.a_click_id=advertiser_clicks.`id` inner join advertiser on advertiser.id=advertiser_clicks.`adv_id` where advertiser_clicks.`dt_datetime`>='2017-11-29' and advertiser_clicks.`dt_datetime`<='2017-11-30' group by advertiser.name,advertiser.id
</code>```

My query return this output:-

```<code>.............................................................
adv_id    advertiser     totalclick    cpi    cost   profit
.............................................................
   1       Your survey       2          20     13     8
</code>```

答:
Hi i have resolved my issue:-</p>

```<code>SELECT sum(advertiser_clicks.`clicks`) as totalclick,sum(advertiser_cost.cpi) as revenue,sum(advertiser_cost.`conversion`) as conversion,sum(advertiser_cost.`cost`) as cost,SUM(advertiser_cost.profit) as profit,advertiser.name as advertiser,advertiser.id as adv_id FROM `advertiser` left join advertiser_clicks on advertiser.id=advertiser_clicks.`adv_id` and (advertiser_clicks.`dt_datetime` between '$startdate' and '$enddate' ) LEFT JOIN advertiser_cost on advertiser_cost.a_click_id=advertiser_clicks.`id` group by advertiser.name,advertiser.id
</code>```

Body:
I have three tables in advertiser,advertiser_clicks and advertiser_cost in which i have used join with multiple aggregate function.But i was unable to get the actual record from the tables.Please find below my table structure.

Table1:advertiser

................
id      name
................
1     Your Survey
2     Vindale

Table2:advertiser_clicks
In this table adv_id is foreign key of advertiser table id

.............................................................
id    adv_id    survey_id   survey_name  clicks  dt_datetime
.............................................................
1       1        101        survey1       1       2017-11-30
2       2        102        survey2       1       2017-11-29
3       1        103        survey3       1       2017-11-28

Table3:advertiser_cost
In this table a_click_id is the foreign key of advertiser_clicks table adv_id

.......................................................
ac_id   a_click_id   cpi    conversion  cost   profit
......................................................
  1       1          10       1           8      2
  2       2          10       1           5      5
  3       3          5        1           5      5

I want below output:-when i select start date:2017-11-29 and enddate :2017-11-30 in where condition then i want below output.Here total click,cpi,cost & profit is the sum of all the data which comes in between that daterange.

.............................................................
adv_id    advertiser     totalclick    cpi    cost   profit
.............................................................
   1       Your survey       2          20     13     8
   2        vindale          0           0     0      0

I have write the below query which returns the exact data which comes
in between that date range but i it will not return the record of vindale
advertiser as a zero value.Please find my below query.

SELECT sum(advertiser_clicks.`clicks`) as totalclick,sum(advertiser_cost.cpi) as revenue,sum(advertiser_cost.`conversion`) as conversion,sum(advertiser_cost.`cost`) as cost,SUM(advertiser_cost.profit) as profit,advertiser.name as advertiser,advertiser.id as adv_id FROM `advertiser_clicks` LEFT JOIN advertiser_cost on advertiser_cost.a_click_id=advertiser_clicks.`id` inner join advertiser on advertiser.id=advertiser_clicks.`adv_id` where advertiser_clicks.`dt_datetime`>='2017-11-29' and advertiser_clicks.`dt_datetime`<='2017-11-30' group by advertiser.name,advertiser.id

My query return this output:-

.............................................................
adv_id    advertiser     totalclick    cpi    cost   profit
.............................................................
   1       Your survey       2          20     13     8

Body:
Hi i have resolved my issue:-

SELECT sum(advertiser_clicks.`clicks`) as totalclick,sum(advertiser_cost.cpi) as revenue,sum(advertiser_cost.`conversion`) as conversion,sum(advertiser_cost.`cost`) as cost,SUM(advertiser_cost.profit) as profit,advertiser.name as advertiser,advertiser.id as adv_id FROM `advertiser` left join advertiser_clicks on advertiser.id=advertiser_clicks.`adv_id` and (advertiser_clicks.`dt_datetime` between '$startdate' and '$enddate' ) LEFT JOIN advertiser_cost on advertiser_cost.a_click_id=advertiser_clicks.`id` group by advertiser.name,advertiser.id


问:
Python: start new process that executes another object's method
I want to start a new process that will create some other object and then calls that objects loops_forever method.

I tried using Python's multiprocessing module as described in my previous SO question here: Python Multiprocessing calling object method

Here is what I tried:

```<code>import OtherService
from multiprocessing import Process
my_other_service = OtherService(address=ADDRESS)
my_other_process = Process(target=my_other_service.loops_forever)
my_other_process.start()
</code>```

The problem with this solution is that the created object (OtherService) is not serializable and I get a "can't pickle _thread.lock object" error in the last line above.

How can I start a new process from my main class, and tell that process to create a new OtherService object (handing that process only the address parameter) and then tell that other process to call loops_forever?

Note that the solution doesnt have to use pythons multiprocessing, I will use whichever package makes most sense.

答:
You've got the answer in your question, in English. You just have to translate it into code.

tell that process to create a new OtherService object (handing that process only the address parameter) and then tell that other process to call loops_forever?

Create a simple new function, which will take an address, create an OtherService object, and call its loops_forever() method. This function is what's passed as the target of the new process you create.

Like so:

```<code>def create_service_and_loop(address):
    service = OtherService(address)
    service.loops_forever()

proc = multiprocessing.Process(target=create_service_and_loop, args=(ADDRESS,))
proc.start()
</code>```

Body:
I want to start a new process that will create some other object and then calls that objects loops_forever method.

I tried using Python's multiprocessing module as described in my previous SO question here: Python Multiprocessing calling object method

Here is what I tried:

import OtherService
from multiprocessing import Process
my_other_service = OtherService(address=ADDRESS)
my_other_process = Process(target=my_other_service.loops_forever)
my_other_process.start()

The problem with this solution is that the created object (OtherService) is not serializable and I get a "can't pickle _thread.lock object" error in the last line above.

How can I start a new process from my main class, and tell that process to create a new OtherService object (handing that process only the address parameter) and then tell that other process to call loops_forever?

Note that the solution doesnt have to use pythons multiprocessing, I will use whichever package makes most sense.

Body:
You've got the answer in your question, in English. You just have to translate it into code.

tell that process to create a new OtherService object (handing that process only the address parameter) and then tell that other process to call loops_forever?

Create a simple new function, which will take an address, create an OtherService object, and call its loops_forever() method. This function is what's passed as the target of the new process you create.

Like so:

def create_service_and_loop(address):
    service = OtherService(address)
    service.loops_forever()

proc = multiprocessing.Process(target=create_service_and_loop, args=(ADDRESS,))
proc.start()


问:
Generate a single use token in PHP: random_bytes or openssl_random_pseudo_bytes?
I need to generate a single-use token in PHP. There are two functions available that I can use for this that seem to do the same thing: random_bytes and openssl_random_pseudo_bytes. For example, using random_bytes:

```<code>var_dump(bin2hex(random_bytes(12)));

--> string(24) "338f489ec37a2c2b4943905d"
</code>```

and using openssl_random_pseudo_bytes:

```<code>var_dump(bin2hex(openssl_random_pseudo_bytes(12)));

--> string(24) "1c7febea20029bd524fba8e7"
</code>```

openssl_random_pseudo_bytes is PHP 5.3 and up (so I assume it's been around longer), and random_bytes is PHP 7. I'm using PHP 7 so I can use either.

So is there any major (or minor for that matter) difference between the two? If not, I'm tempted to go with random_bytes simply because it has an easier name ( = code that's easier to read).

答:
Just to update, the cryptographic insecurity in openssl_random_pseudo_bytes was fixed in 2016. More details here:

http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-8867

It usese RAND_bytes now, which OpenSSL recommends in its wiki:

https://wiki.openssl.org/index.php/Random_Numbers#FIPS_Mode

Body:
I need to generate a single-use token in PHP. There are two functions available that I can use for this that seem to do the same thing: random_bytes and openssl_random_pseudo_bytes. For example, using random_bytes:

var_dump(bin2hex(random_bytes(12)));

--> string(24) "338f489ec37a2c2b4943905d"

and using openssl_random_pseudo_bytes:

var_dump(bin2hex(openssl_random_pseudo_bytes(12)));

--> string(24) "1c7febea20029bd524fba8e7"

openssl_random_pseudo_bytes is PHP 5.3 and up (so I assume it's been around longer), and random_bytes is PHP 7. I'm using PHP 7 so I can use either.

So is there any major (or minor for that matter) difference between the two? If not, I'm tempted to go with random_bytes simply because it has an easier name ( = code that's easier to read).


问:
Some times getting error while writing in to a text file
i am writing a string value to a text file continuously

```<code>std::string line =('8101001033900039','00','22','','','','','3','','0'),
</code>```

this string we are writing to a text file like below

```<code>outfile.open((char*)fileName.c_str(), ios::app);

if(outfile.is_open())
    {
        // write inputted data into the file.
        DBGF_TRACE("3.write line : %s", line);
        outfile<< line << std::endl;
        DBGF_TRACE("write line : %s", line);
    }
</code>```

Now the error i am getting is , sometimes its getting failed to write . Can someone help

Body:
i am writing a string value to a text file continuously

std::string line =('8101001033900039','00','22','','','','','3','','0'),

this string we are writing to a text file like below

outfile.open((char*)fileName.c_str(), ios::app);

if(outfile.is_open())
    {
        // write inputted data into the file.
        DBGF_TRACE("3.write line : %s", line);
        outfile<< line << std::endl;
        DBGF_TRACE("write line : %s", line);
    }

Now the error i am getting is , sometimes its getting failed to write . Can someone help

Body:
What is that to begin with:

std::string line =('8101001033900039','00','22','','','','','3','','0');

The compiler should give you something like that:

prog.cc:8:24: warning: character constant too long for its type
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                        ^~~~~~~~~~~~~~~~~~
prog.cc:8:43: warning: multi-character character constant [-Wmultichar]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                           ^~~~
prog.cc:8:48: warning: multi-character character constant [-Wmultichar]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                ^~~~
prog.cc:8:53: error: empty character constant
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                     ^~
prog.cc:8:56: error: empty character constant
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                        ^~
prog.cc:8:59: error: empty character constant
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                           ^~
prog.cc:8:62: error: empty character constant
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                              ^~
prog.cc:8:69: error: empty character constant
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                                     ^~
prog.cc: In function 'int main()':
prog.cc:8:43: warning: left operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                           ^~~~
prog.cc:8:48: warning: right operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                ^~~~
prog.cc:8:53: warning: right operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                     ^~
prog.cc:8:56: warning: right operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                        ^~
prog.cc:8:59: warning: right operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                           ^~
prog.cc:8:62: warning: right operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                              ^~
prog.cc:8:65: warning: right operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                                 ^~~
prog.cc:8:69: warning: right operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                                     ^~
prog.cc:8:72: warning: right operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                                        ^~~
prog.cc:8:71: error: conversion from 'char' to non-scalar type 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} requested
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~

so the data themselves are not OK.

So now, let's replace single quotes with double quotes, since you probably want strings, like this:

std::string line =("8101001033900039","00","22","","","","","3","","0");

then only the right most operand will be assigned to line, meaning that line is now equal to "0". Read more about it in What does i = (i, ++i, 1) + 1; do?

EDIT:

You need this:

#include <fstream>
#include <string>
#include <iostream>

int main(void) {
    std::string fileName = "output.txt";
    std::string line ="('8101001033900039','00','22','','','','','3','','0'),";
    std::ofstream out(fileName.c_str());
    out << line << std::endl;
    out.close();
    return 0;
}


问:
Select the number of days a record is present within a certain year/month
In sql server I have a table with start and end dates for job postings. Given a month and a year by the user I need to find the amount of days between the start and end date that fall in the given year/month for that posting.

So if the posting Start Date is 2010/11/15 and End Date is 2010/12/05
Then output should be:

```<code>November  16 days
December  5 days
Total     21 days
</code>```

I've been beating my head against the wall with this one and am fresh out of ideas.

答:
```<code>DECLARE
   @StartDate datetime,
   @EndDate datetime;
SET @StartDate = '20101115';
SET @EndDate = '20101205';

WITH Mos AS (
   SELECT
      Number,
      DateAdd(Month, Number, @StartDate - Day(@StartDate) + 1) MoDate
   FROM master.dbo.spt_values
   WHERE
      Type = 'P'
      AND Number <= DateDiff(Month, @StartDate, @EndDate)
), Dys AS (
   SELECT
      MoDate,
      DateDiff(
         Day,
         CASE WHEN Number = 0 THEN @StartDate ELSE MoDate END,
         CASE WHEN Number = DateDiff(Month, @StartDate, @EndDate) THEN @EndDate ELSE DateAdd(Month, 1, MoDate) - 1 END
      ) + 1 Cnt
   FROM Mos
)
SELECT
   Year(MoDate) Yr,
   Coalesce(DateName(Month, MoDate), 'Total') Mo,
   Convert(varchar(11), Sum(Cnt)) + ' day' + CASE WHEN Sum(Cnt) = 1 THEN '' ELSE 's' END Descr
FROM Dys
GROUP BY MoDate
WITH ROLLUP
ORDER BY Grouping(MoDate), MoDate;
</code>```

And here's a table version in case you wanted to do it with many at once:

```<code>CREATE TABLE AccountDates (
   AccountCode varchar(10) NOT NULL CONSTRAINT PK_AccountDates PRIMARY KEY CLUSTERED,
   StartDate datetime,
   EndDate datetime
);

INSERT AccountDates VALUES ('BLINKEN', '20101115', '20101205');
INSERT AccountDates VALUES ('KRAM', '20101027', '20110118');
INSERT AccountDates VALUES ('NUVU', '20101207', '20101207');

WITH Mos AS (
   SELECT
      AccountCode,
      D.StartDate,
      D.EndDate,
      Number,
      DateAdd(Month, Number, D.StartDate - Day(D.StartDate) + 1) MoDate
   FROM
      AccountDates D
      INNER JOIN master.dbo.spt_values V ON V.Number <= DateDiff(Month, D.StartDate, D.EndDate)
   WHERE
      V.Type = 'P'
), Dys AS (
   SELECT
      AccountCode,
      MoDate,
      DateDiff(
         Day,
         CASE WHEN Number = 0 THEN StartDate ELSE MoDate END,
         CASE WHEN Number = DateDiff(Month, StartDate, EndDate) THEN EndDate ELSE DateAdd(Month, 1, MoDate) - 1 END
      ) + 1 Cnt
   FROM Mos
)
SELECT
   AccountCode,
   Year(MoDate) Yr,
   Coalesce(DateName(Month, MoDate), 'Total') Mo,
   Convert(varchar(11), Sum(Cnt)) + ' day' + CASE WHEN Sum(Cnt) = 1 THEN '' ELSE 's' END Descr
FROM Dys
GROUP BY AccountCode, MoDate
WITH ROLLUP
HAVING Grouping(AccountCode) = 0
ORDER BY
   AccountCode,
   Grouping(MoDate),
   MoDate;
</code>```

I simplified things a little from my original query.

Body:
In sql server I have a table with start and end dates for job postings. Given a month and a year by the user I need to find the amount of days between the start and end date that fall in the given year/month for that posting.

So if the posting Start Date is 2010/11/15 and End Date is 2010/12/05
Then output should be:

November  16 days
December  5 days
Total     21 days

I've been beating my head against the wall with this one and am fresh out of ideas.

Body:
DECLARE
   @StartDate datetime,
   @EndDate datetime;
SET @StartDate = '20101115';
SET @EndDate = '20101205';

WITH Mos AS (
   SELECT
      Number,
      DateAdd(Month, Number, @StartDate - Day(@StartDate) + 1) MoDate
   FROM master.dbo.spt_values
   WHERE
      Type = 'P'
      AND Number <= DateDiff(Month, @StartDate, @EndDate)
), Dys AS (
   SELECT
      MoDate,
      DateDiff(
         Day,
         CASE WHEN Number = 0 THEN @StartDate ELSE MoDate END,
         CASE WHEN Number = DateDiff(Month, @StartDate, @EndDate) THEN @EndDate ELSE DateAdd(Month, 1, MoDate) - 1 END
      ) + 1 Cnt
   FROM Mos
)
SELECT
   Year(MoDate) Yr,
   Coalesce(DateName(Month, MoDate), 'Total') Mo,
   Convert(varchar(11), Sum(Cnt)) + ' day' + CASE WHEN Sum(Cnt) = 1 THEN '' ELSE 's' END Descr
FROM Dys
GROUP BY MoDate
WITH ROLLUP
ORDER BY Grouping(MoDate), MoDate;

And here's a table version in case you wanted to do it with many at once:

CREATE TABLE AccountDates (
   AccountCode varchar(10) NOT NULL CONSTRAINT PK_AccountDates PRIMARY KEY CLUSTERED,
   StartDate datetime,
   EndDate datetime
);

INSERT AccountDates VALUES ('BLINKEN', '20101115', '20101205');
INSERT AccountDates VALUES ('KRAM', '20101027', '20110118');
INSERT AccountDates VALUES ('NUVU', '20101207', '20101207');

WITH Mos AS (
   SELECT
      AccountCode,
      D.StartDate,
      D.EndDate,
      Number,
      DateAdd(Month, Number, D.StartDate - Day(D.StartDate) + 1) MoDate
   FROM
      AccountDates D
      INNER JOIN master.dbo.spt_values V ON V.Number <= DateDiff(Month, D.StartDate, D.EndDate)
   WHERE
      V.Type = 'P'
), Dys AS (
   SELECT
      AccountCode,
      MoDate,
      DateDiff(
         Day,
         CASE WHEN Number = 0 THEN StartDate ELSE MoDate END,
         CASE WHEN Number = DateDiff(Month, StartDate, EndDate) THEN EndDate ELSE DateAdd(Month, 1, MoDate) - 1 END
      ) + 1 Cnt
   FROM Mos
)
SELECT
   AccountCode,
   Year(MoDate) Yr,
   Coalesce(DateName(Month, MoDate), 'Total') Mo,
   Convert(varchar(11), Sum(Cnt)) + ' day' + CASE WHEN Sum(Cnt) = 1 THEN '' ELSE 's' END Descr
FROM Dys
GROUP BY AccountCode, MoDate
WITH ROLLUP
HAVING Grouping(AccountCode) = 0
ORDER BY
   AccountCode,
   Grouping(MoDate),
   MoDate;

I simplified things a little from my original query.


问:
Flashlight/ torch when streaming video
I want to switch on torch on Android devices when tokbox is streaming video, using it as a lantern.

Swith on and off the torch is pretty easy, but if you try when camera is already working it launch a error.

Torch for camera "0" is not available due to an existing camera user

I guess this is expected result, but I've seen some apps using the torch while streaming video.

Any clues?
Thanks

答: I solved it using the camera object inside the custom video capturer, from opentok Android examples.</p>

Title: Flashlight/ torch when streaming video