问:
How to calculate probability in a normal distribution given mean & standard deviation?
How to calculate probability in normal distribution given mean, std in Python? I can always explicitly code my own function according to the definition like the OP in this question did: Calculating Probability of a Random Variable in a Distribution in Python

Just wondering if there is a library function call will allow you to do this. In my imagine it would like this:

```<code>nd = NormalDistribution(mu=100, std=12)
p = nd.prob(98)
</code>```

There is a similar question in Perl: How can I compute the probability at a point given a normal distribution in Perl?. But I didn't see one in Python.

Numpy has a random.normal function, but it's like sampling, not exactly what I want.

答:
Here is more info.
First you are dealing with a frozen distribution (frozen in this case means its parameters are set to specific values). To create a frozen distribution:</p>

```<code>import scipy.stats
scipy.stats.norm(loc=100, scale=12)
#where loc is the mean and scale is the std dev
#if you wish to pull out a random number from your distribution
scipy.stats.norm.rvs(loc=100, scale=12)

#To find the probability that the variable has a value LESS than or equal
#let's say 113, you'd use CDF cumulative Density Function
scipy.stats.norm.cdf(113,100,12)
Output: 0.86066975255037792
#or 86.07% probability

#To find the probability that the variable has a value GREATER than or
#equal to let's say 125, you'd use SF Survival Function
scipy.stats.norm.sf(125,100,12)
Output: 0.018610425189886332
#or 1.86%

#To find the variate for which the probability is given, let's say the
#value which needed to provide a 98% probability, you'd use the
#PPF Percent Point Function
scipy.stats.norm.ppf(.98,100,12)
Output: 124.64498692758187
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to calculate probability in normal distribution given mean, std in Python? I can always explicitly code my own function according to the definition like the OP in this question did: Calculating Probability of a Random Variable in a Distribution in Python

Just wondering if there is a library function call will allow you to do this. In my imagine it would like this:

nd = NormalDistribution(mu=100, std=12)
p = nd.prob(98)

There is a similar question in Perl: How can I compute the probability at a point given a normal distribution in Perl?. But I didn't see one in Python.

Numpy has a random.normal function, but it's like sampling, not exactly what I want.

Body:
Here is more info.
First you are dealing with a frozen distribution (frozen in this case means its parameters are set to specific values). To create a frozen distribution:

import scipy.stats
scipy.stats.norm(loc=100, scale=12)
#where loc is the mean and scale is the std dev
#if you wish to pull out a random number from your distribution
scipy.stats.norm.rvs(loc=100, scale=12)

#To find the probability that the variable has a value LESS than or equal
#let's say 113, you'd use CDF cumulative Density Function
scipy.stats.norm.cdf(113,100,12)
Output: 0.86066975255037792
#or 86.07% probability

#To find the probability that the variable has a value GREATER than or
#equal to let's say 125, you'd use SF Survival Function
scipy.stats.norm.sf(125,100,12)
Output: 0.018610425189886332
#or 1.86%

#To find the variate for which the probability is given, let's say the
#value which needed to provide a 98% probability, you'd use the
#PPF Percent Point Function
scipy.stats.norm.ppf(.98,100,12)
Output: 124.64498692758187


来源: stackexchange

问:
An image place horizontally next to a list
Can somebody tell me what I'm doing wrong?

```<code><div class="row">
      <ul class='list-group .col-md-6'> <li>1</li><li>1</li><li>1</li>  </ul>
      <div>
        <img class=".col-md-6" src="https://farm8.staticflickr.com/7613/16147502573_613d5f6b23.jpg" />
      </div>
</div>
</code>```

Pretend the list elements are placeholders.
What I want to do is have a list on the left half of the window, and an image on the right half of the window (preferably centered vertically with the list, if any of you guys know how to do that as well)
I thought using bootstrap grid system would work but I'm a newbie at bootstrap and it is not resulting in a side by side depiction, but the image appears under the list. And yes, I already have bootstrap imported and fetched. And no, removing the div around the image didnt make a difference.

Also if bootstrap isn't the best way to do this, I'm okay with accepting plain CSS answers.

答: apply float:left to ul and float:right to the img.

ContentLicense: CC BY-SA 3.0

Body:
Can somebody tell me what I'm doing wrong?

1

1

1

Pretend the list elements are placeholders.
What I want to do is have a list on the left half of the window, and an image on the right half of the window (preferably centered vertically with the list, if any of you guys know how to do that as well)
I thought using bootstrap grid system would work but I'm a newbie at bootstrap and it is not resulting in a side by side depiction, but the image appears under the list. And yes, I already have bootstrap imported and fetched. And no, removing the div around the image didnt make a difference.

Also if bootstrap isn't the best way to do this, I'm okay with accepting plain CSS answers.


问:
Kotlin - Android can we implement OnClickListener on Class?
I'm starting out with Kotlin and seems that onClick does not trigger if I implement it on an Activity Class

```<code>class MainActivity : AppCompatActivity(), View.OnClickListener{

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        tvTitle.text = "Hi There"

//        tvTitle.setOnClickListener { this } // NOT WORKING??
        tvTitle.setOnClickListener { doSomething() }
    }

    override fun onClick(v: View) {
        Log.d("click", "Hello")
    }

    fun doSomething(){
        Log.d("do", "Something")
    }
}
</code>```

I'm using Android Studio 3.0 with kotlin_version of 1.1.51, thank you in advance

答:
Try this</p>

```<code>class MainActivity : AppCompatActivity(), View.OnClickListener{

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    tvTitle.text = "Hi There"

    tvTitle.setOnClickListener(this)
   //   tvTitle.setOnClickListener { doSomething() }
}

override fun onClick(v: View) {
    Log.d("click", "Hello")
}

fun doSomething(){
    Log.d("do", "Something")
}
}
</code>```

Body:
I'm starting out with Kotlin and seems that onClick does not trigger if I implement it on an Activity Class

class MainActivity : AppCompatActivity(), View.OnClickListener{

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        tvTitle.text = "Hi There"

//        tvTitle.setOnClickListener { this } // NOT WORKING??
        tvTitle.setOnClickListener { doSomething() }
    }

    override fun onClick(v: View) {
        Log.d("click", "Hello")
    }

    fun doSomething(){
        Log.d("do", "Something")
    }
}

I'm using Android Studio 3.0 with kotlin_version of 1.1.51, thank you in advance

Body:
Try this

class MainActivity : AppCompatActivity(), View.OnClickListener{

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    tvTitle.text = "Hi There"

    tvTitle.setOnClickListener(this)
   //   tvTitle.setOnClickListener { doSomething() }
}

override fun onClick(v: View) {
    Log.d("click", "Hello")
}

fun doSomething(){
    Log.d("do", "Something")
}
}


问:
Usage of SUMIF in Excel
I have list of customers and their corresponding revenues in 3 services. These list of customer belongs to various regions- North, East, South, West.

In above excel, I wish to find sum total region wise. Kindly help to use SUMIF or any other useful function.

答:
This array formula seems to work in C13.

```<code>=SUM(SUMIFS(C$3:C$11, $B$3:$B$11, IF($H$3:$H$11=$B13, $G$3:$G$11)))
</code>```

Fill right and down.

Title: Usage of SUMIF in Excel

Body:
This array formula seems to work in C13.

=SUM(SUMIFS(C$3:C$11, $B$3:$B$11, IF($H$3:$H$11=$B13, $G$3:$G$11)))

Fill right and down.


问:
java split keep the separator as independent array element
I want to split the string

```<code>Actual #keys: {}, Estimated #keys:{}, Err%: {}"
</code>```

to

```<code>[{}, Actual #keys: , {}, Estimated #keys:, {}, Err%: , {}]
</code>```

I try use

```<code>str.split("(?=\\b\\{\\})")
</code>```

but its result is

```<code>[{}Actual #keys: {}, Estimated #keys:{}, Err%: {}]
</code>```

答: Use java.util.StringTokenizer, which has an option to return the delimiters.

Body:
I want to split the string

Actual #keys: {}, Estimated #keys:{}, Err%: {}"

to

[{}, Actual #keys: , {}, Estimated #keys:, {}, Err%: , {}]

I try use

str.split("(?=\\b\\{\\})")

but its result is

[{}Actual #keys: {}, Estimated #keys:{}, Err%: {}]


问:
compare two string in java result in percentage
I have to compare two strings which 4000-5000 characters.

I need result in percentage(i.e. 70% - 80% matched), in java.

Kindly suggest me any solution for it.

Regards

答:
You can use Apache Commons Lang 3.

Maven dependency:

```<code><dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>${commons.lang.version}</version>
</dependency>

@Test
public void test_stringDistance() throws Exception {
    String teamName = "Partizn Belgrade";
    String propositionName = "Partizan Belgrade";

    // This one seems better
    double distance = StringUtils.getJaroWinklerDistance(teamName, propositionName);
    System.out.println(distance);
}
</code>```

This is print out percentage, the larger the better (100% is exact )

Body:
You can use Apache Commons Lang 3.

Maven dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>${commons.lang.version}</version>
</dependency>

@Test
public void test_stringDistance() throws Exception {
    String teamName = "Partizn Belgrade";
    String propositionName = "Partizan Belgrade";

    // This one seems better
    double distance = StringUtils.getJaroWinklerDistance(teamName, propositionName);
    System.out.println(distance);
}

This is print out percentage, the larger the better (100% is exact )


Title: Reshape from values to colname

Body:
I'm looking to reshape my dataframe as follow from :

     Ech   pos    sm    nb
   <int> <chr> <dbl> <dbl>
 1     4    BD    10    80
 2     4    BG     5    80
 3     4    HD     1    80
 4     4    HG     2    80

to

     Ech    BD   BG   HD   HG  nb
 1     4    10    5    1   2   80

my data :

DF=structure(list(Ech = c(4L, 4L, 4L, 4L, 13L, 13L, 13L, 13L, 28L,
28L, 28L, 28L, 37L, 37L, 37L, 37L, 40L, 40L, 40L, 40L), pos = c("BD",
"BG", "HD", "HG", "BD", "BG", "HD", "HG", "BD", "BG", "HD", "HG",
"BD", "BG", "HD", "HG", "BD", "BG", "HD", "HG"), sm = c(10, 5,
1, 2, 2, 4, 2, 1, 3, 7, 1, 2, 6, 4, 2, 4, 11, 8, 1, 4), nb = c(80,
80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80,
80, 80, 80)), .Names = c("Ech", "pos", "sm", "nb"), row.names = c(NA,
-20L), vars = "Ech", drop = TRUE, class = c("grouped_df", "tbl_df",
"tbl", "data.frame"))

What is the fastest way to do this ? thanks

Body:
tidyr::spread does this:

spread(DF, pos, sm)

Output:

    Ech    nb    BD    BG    HD    HG
* <int> <dbl> <dbl> <dbl> <dbl> <dbl>
1     4    80    10     5     1     2
2    13    80     2     4     2     1
3    28    80     3     7     1     2
4    37    80     6     4     2     4
5    40    80    11     8     1     4


问:
How do I make the remote call actually remote?
How do I make an actual remote call?

I've followed the guide: https://codelabs.developers.google.com/codelabs/webrtc-web/#4

And gotten their example fully integrated in my application (Angular, TypeScript, multi webcam &etc).

How do I make the remote call actually remote? - I get the idea of a signalling server, but maybe someone can show with basic strings?

I found this, but it's not been updated in a while so I'm not sure what's still valid:

答:
Found some nice sequence diagrams https://webrtc.org/native-code/native-apis/

Setup call

(source: webrtc.org)

Receive a Call

(source: webrtc.org)

Close Down a Call

(source: webrtc.org)


问:
Please show me what's going wrong with this delete row function for SQL in C#
I am trying to learn the basics of making databases in Visual C#, and I am building a basic application.  In the application there is a delete button that will delete the record that is currently shown in the textboxes.  The code I have at the moment is this:

```<code>private void btnDelete_Click(object sender, EventArgs e)
{
    currentRow.Delete();
    dAdapter.Update(dataset, "Contacts");
    clearTextBoxes();
}
</code>```

currentRow is the DataRow I want to delete and that which is shown in the textboxes.  dataset is the Dataset.  dAdapter is the DataAdapter, and "Contacts" is the table name or w/e.  However this is generating an error sometimes.  What's wrong here?  Thanks!

答:
You need to outline a delete command, something like this:</p>

```<code><asp:SqlDataSource ID="dAdapter" DeleteCommand="DELETE FROM [Sheep] WHERE Id = @Id">
    <DeleteParameters>
        <asp:Parameter Name="@Id" />
    </DeleteParameters>
</asp:SqlDataSource>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to learn the basics of making databases in Visual C#, and I am building a basic application.  In the application there is a delete button that will delete the record that is currently shown in the textboxes.  The code I have at the moment is this:

private void btnDelete_Click(object sender, EventArgs e)
{
    currentRow.Delete();
    dAdapter.Update(dataset, "Contacts");
    clearTextBoxes();
}

currentRow is the DataRow I want to delete and that which is shown in the textboxes.  dataset is the Dataset.  dAdapter is the DataAdapter, and "Contacts" is the table name or w/e.  However this is generating an error sometimes.  What's wrong here?  Thanks!

Body:
You need to outline a delete command, something like this:

<asp:SqlDataSource ID="dAdapter" DeleteCommand="DELETE FROM [Sheep] WHERE Id = @Id">
    <DeleteParameters>
        <asp:Parameter Name="@Id" />
    </DeleteParameters>
</asp:SqlDataSource>


问:
Boot from docker volume
I'm trying to build Linux From Scratch in docker. It expects a mounted volume on which it'll build a system you can boot from, so my plan was to attach a docker volume to a normal docker ubuntu container to build the LFS system and stuff it into the volume, then boot another docker container from said volume.

It says no to the latter:

```<code>docker: Error response from daemon: invalid mount config for type "volume": invalid specification: destination can't be '/'.
</code>```

That makes sense considering I was trying to boot a ubuntu docker image, but how am I to achieve this?

Perhaps I should be content with a docker image that has a tiny boot partition of its own which then mounts the LFS system volume to find all the /usr stuff. I guess LFS will make that easy, but I'm not sure how to make that docker image. How does one start a docker image from nothing and put grub, vmlinuz, etc into it?

答: To answer your question let me first start with booting host OS process - it starts with; BIOS - grub - vmlinuz - os - filesystem - system services - user services; Now coming to docker  - It is sandbox and make use of the existing running kernel thus the booting of docker process is; mount filesystem - system services - user services; The volumes are mounted with the base filesystem like ext2, ext3, etc., Since docker is sandbox we can bring more than 1000 dockers in seconds</p>

Title: Boot from docker volume

Body:
I'm trying to build Linux From Scratch in docker. It expects a mounted volume on which it'll build a system you can boot from, so my plan was to attach a docker volume to a normal docker ubuntu container to build the LFS system and stuff it into the volume, then boot another docker container from said volume.

It says no to the latter:

docker: Error response from daemon: invalid mount config for type "volume": invalid specification: destination can't be '/'.

That makes sense considering I was trying to boot a ubuntu docker image, but how am I to achieve this?

Perhaps I should be content with a docker image that has a tiny boot partition of its own which then mounts the LFS system volume to find all the /usr stuff. I guess LFS will make that easy, but I'm not sure how to make that docker image. How does one start a docker image from nothing and put grub, vmlinuz, etc into it?


问:
Possible to hook an event for ReadProcessMemory()?
Is it possible to hook calls to ReadProcessMemory() in the win32 API?  I would like to do it in C or C++.

What I mean is, anytime another process uses that function, it detours to my callback at some point with all the info.

答:
You can inject your code into every running process and hook ReadProcessMemory in the calling process, just like you would any other function but there is no way for you to hook it from the target process.

Alternatively you can use obRegisterCallbacks() from the kernel to detect OpenProcess() by filtering by PsProcessType object type and OB_OPERATION_HANDLE_CREATE operation.  This will show you any processes that need handles to call ReadProcessMemory(). You would then have the ability to execute your own code when these events are triggered from the kernel.  You could also speak to a usermode process from your obRegisterCallbacks routine.


问:
Jenkins groovy regex match string : Error: java.io.NotSerializableException: java.util.regex.Matcher
I'm trying to get the matched string from a regex in groovy. The matched string prints to the console  without problems, but when I try use the matched string in a git command I get the following error:

```<code>Err: Incremental Build failed with Error: java.io.NotSerializableException: java.util.regex.Matcher
</code>```

Here is the code:

```<code>                def binaryName = "298_application_V2_00_Build_07.hex"

                def matches = (binaryName =~ /(V)(\d+)(_)(\d+)(_)(Build)(_)(\d+)/)
                versionTag = ""+matches[0].getAt(0)
                echo "${matches}"
                echo "$versionTag"
                bat("git tag $versionTag")
                bat("git push origin --tags")
</code>```

How can I get the matched string from the regex?

答:
This problem is caused by Jenkins' CPS, which serializes all pipeline executions to store as resumable state.

Calls to non-serializable methods have to be wrapped in a method annotated with @NonCPS:

@NonCPS
String getVersion(String binaryName) {
  def matches = (binaryName =~ /(V)(\d+)(_)(\d+)(_)(Build)(_)(\d+)/)
  versionTag = ""+matches[0].getAt(0)
  versionTag
}
```

this method can now be called from your pipeline. In case your Jenkins master restarts during execution of this method, it would just run through it completely - which is in many cases, such as yours, absolutely no problem.

Body:
I'm trying to get the matched string from a regex in groovy. The matched string prints to the console  without problems, but when I try use the matched string in a git command I get the following error:

Err: Incremental Build failed with Error: java.io.NotSerializableException: java.util.regex.Matcher

Here is the code:

                def binaryName = "298_application_V2_00_Build_07.hex"

                def matches = (binaryName =~ /(V)(\d+)(_)(\d+)(_)(Build)(_)(\d+)/)
                versionTag = ""+matches[0].getAt(0)
                echo "${matches}"
                echo "$versionTag"
                bat("git tag $versionTag")
                bat("git push origin --tags")

How can I get the matched string from the regex?

Body:
This problem is caused by Jenkins' CPS, which serializes all pipeline executions to store as resumable state.

Calls to non-serializable methods have to be wrapped in a method annotated with @NonCPS:

@NonCPS
String getVersion(String binaryName) {
  def matches = (binaryName =~ /(V)(\d+)(_)(\d+)(_)(Build)(_)(\d+)/)
  versionTag = ""+matches[0].getAt(0)
  versionTag
}

this method can now be called from your pipeline. In case your Jenkins master restarts during execution of this method, it would just run through it completely - which is in many cases, such as yours, absolutely no problem.


问:
Passing the string value to background service
Please guide me in this. Appreciate all your help.

My background service is toasting ABC

//-------------------String displayingText = "ABC";-----------------

And I have two strings, ABC and DEF declared in mainactivity.java

How do I pass the value displayingText from main activity to this service.

How do I change the displayingText to DEF after the toast ABC finished.

MyService.Java

```<code>public class MyService extends Service {
public static final long INTERVAL=3000;//variable to execute services every 5 second
private Handler mHandler=new Handler(); // run on another Thread to avoid crash
private Timer mTimer=null; // timer handling
</code>```

//the get intent dont work. where or how should i put it?

```<code>Intent myIntent = getIntent();
    if (myIntent !=null && myIntent.getExtras()!=null)
String value = myIntent.getExtras().getString(PassToService);

@Nullable
@Override
public IBinder onBind(Intent intent) {
    throw new UnsupportedOperationException("unsupported Operation");
}
@Override
public void onCreate() {

    // cancel if service is  already existed
    if(mTimer!=null)
        mTimer.cancel();
    else
        mTimer=new Timer(); // recreate new timer
    mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(),0,INTERVAL);// schedule task

}

    @Override
public void onTaskRemoved(Intent rootIntent) {
    stopSelf();///its will stop service
    super.onTaskRemoved(rootIntent);
}
@Override
public void onDestroy() {
    Toast.makeText(this, "In Destroy", Toast.LENGTH_SHORT).show();//display toast when method called
    mTimer.cancel();//cancel the timer
    super.onDestroy();

}

//inner class of TimeDisplayTimerTask
private class TimeDisplayTimerTask extends TimerTask {
    @Override
    public void run() {

        // run on another thread
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                // display toast at every 10 second
                //String displayingText = "ABC";
                String displayingText = myIntent.getStringExtra("PassToService");
                final Toast Notify = Toast.makeText(getApplicationContext(), displayingText, Toast.LENGTH_SHORT);
                Notify.setGravity(Gravity.CENTER, 0, 0);
                Notify.show();

                Handler cancelToast = new Handler();
                cancelToast.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Notify.cancel();
                    }
                }, 1000);

            }
        });
    }
}
</code>```

}

答:
You can do it by passing value from activity to service-

startService(new Intent(YourActivity.Service.class).putExtra("key","value"));

Body:
Please guide me in this. Appreciate all your help.

My background service is toasting ABC

//-------------------String displayingText = "ABC";-----------------

And I have two strings, ABC and DEF declared in mainactivity.java

How do I pass the value displayingText from main activity to this service.

How do I change the displayingText to DEF after the toast ABC finished.

MyService.Java

public class MyService extends Service {
public static final long INTERVAL=3000;//variable to execute services every 5 second
private Handler mHandler=new Handler(); // run on another Thread to avoid crash
private Timer mTimer=null; // timer handling

//the get intent dont work. where or how should i put it?

Intent myIntent = getIntent();
    if (myIntent !=null && myIntent.getExtras()!=null)
String value = myIntent.getExtras().getString(PassToService);

@Nullable
@Override
public IBinder onBind(Intent intent) {
    throw new UnsupportedOperationException("unsupported Operation");
}
@Override
public void onCreate() {

    // cancel if service is  already existed
    if(mTimer!=null)
        mTimer.cancel();
    else
        mTimer=new Timer(); // recreate new timer
    mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(),0,INTERVAL);// schedule task

}

    @Override
public void onTaskRemoved(Intent rootIntent) {
    stopSelf();///its will stop service
    super.onTaskRemoved(rootIntent);
}
@Override
public void onDestroy() {
    Toast.makeText(this, "In Destroy", Toast.LENGTH_SHORT).show();//display toast when method called
    mTimer.cancel();//cancel the timer
    super.onDestroy();

}

//inner class of TimeDisplayTimerTask
private class TimeDisplayTimerTask extends TimerTask {
    @Override
    public void run() {

        // run on another thread
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                // display toast at every 10 second
                //String displayingText = "ABC";
                String displayingText = myIntent.getStringExtra("PassToService");
                final Toast Notify = Toast.makeText(getApplicationContext(), displayingText, Toast.LENGTH_SHORT);
                Notify.setGravity(Gravity.CENTER, 0, 0);
                Notify.show();

                Handler cancelToast = new Handler();
                cancelToast.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Notify.cancel();
                    }
                }, 1000);

            }
        });
    }
}

}


问:
MySQL - Set maximum number of result sets per query
When running a large stored procedure mysql script, I am getting the following error
The maximum number of result sets per query is reached (100).

After looking around I have found a few articles that say I can change that limit specifically in mysql workbench, but I am looking for a config option for my my.ini file to apply it across the entire server I am running.

It would be awesome to simply do something like
max_result_set=5000 or something.

Thanks for all help, in advance.

答:
Huge thanks to Spencer for the thought to check the client settings! (duh!)

There was a setting burried deep in the Advanced tab of the Data Sources and Drivers configuration box. Just for anyone also using that Jetbrain Database Tools and SQL plugin (https://www.jetbrains.com/datagrip/)


问:
Should calls to a public shared functions be locked for thread safety
As in the title. Should be calls to public shared functions be locked for thread safety ?</p>

答: If your class is a component or bean and runs on multi thread environment like tomcat server then the function (object) must be locked if it writes data in shared memory</p>


问:
Rails many-to-many same class bi-directional relationship.. how?
So heres the deal.. i'm writing a rails application to manage contact data..

I have a contact model and that contact needs to have many family members (still the contact class).. that relationship needs associated relationship data.. ie

```<code>ContactA | ContactB | Relationship
1          2          Contact A is Contact B's Father
</code>```

How can i relate 2 objects of the same class and attach some data and be able to traverse te relationship bidirectionally like so:

```<code>@guy1 = Contact.find(1) #Guy A
@guy1.family_relationships
>>> [[guyb, "f"], [guyc, "s"]]
@guy2 = @guy1.family_members.first
@guy1.family_members
>>> [[guya]]
</code>```

Thats probably not 100% correct but its late and ive been battling with a server all day so please forgive me!!

I've heard you have to do all kinds of hacky SQL to do it..

Thanks!

Daniel

答:
Thanks for the great answers but found the answer here:

http://railscasts.com/episodes/163-self-referential-association

Railscasts is awesome!

Body:
So heres the deal.. i'm writing a rails application to manage contact data..

I have a contact model and that contact needs to have many family members (still the contact class).. that relationship needs associated relationship data.. ie

ContactA | ContactB | Relationship
1          2          Contact A is Contact B's Father

How can i relate 2 objects of the same class and attach some data and be able to traverse te relationship bidirectionally like so:

@guy1 = Contact.find(1) #Guy A
@guy1.family_relationships
>>> [[guyb, "f"], [guyc, "s"]]
@guy2 = @guy1.family_members.first
@guy1.family_members
>>> [[guya]]

Thats probably not 100% correct but its late and ive been battling with a server all day so please forgive me!!

I've heard you have to do all kinds of hacky SQL to do it..

Thanks!

Daniel


问:
possible all combinations of list of length n in python without itertools
How can i get all possible combinations of list of length n in python i have written a code for string but list i am not able to do can any one help me.

```<code>def combo(w, l):
    lst = []
    for i in range(len(w)):
        if l == 1:
            lst.append(w[i])
        for c in combo(w[i+1:], l-1):
            lst.append(w[i] + c)
    return lst

comb=map(list,combo('12345',3))
</code>```

above code is to get the combinations of string it gives correct output:

```<code>['12', '13', '14', '15', '23', '24', '25', '34', '35', '45']
</code>```

答:
Of course, there are utils in itertools, but you can fix your function by adjusting two lines as follows:

```<code># note the '[]' around w[i] in those lines
lst.append([w[i]])
# ...
lst.append([w[i]] + c)
# ...
</code>```

Strings are unique sequences in the sense that their elements (chars so to speak) are strings themselves and can be concatenated by +. With most other sequence/iterable types, you have to clearly differentiate between the sequence and its elements. In this case you want to concatenate (sub)lists, not elements.

Body:
How can i get all possible combinations of list of length n in python i have written a code for string but list i am not able to do can any one help me.

def combo(w, l):
    lst = []
    for i in range(len(w)):
        if l == 1:
            lst.append(w[i])
        for c in combo(w[i+1:], l-1):
            lst.append(w[i] + c)
    return lst

comb=map(list,combo('12345',3))

above code is to get the combinations of string it gives correct output:

['12', '13', '14', '15', '23', '24', '25', '34', '35', '45']

Body:
Of course, there are utils in itertools, but you can fix your function by adjusting two lines as follows:

# note the '[]' around w[i] in those lines
lst.append([w[i]])
# ...
lst.append([w[i]] + c)
# ...

Strings are unique sequences in the sense that their elements (chars so to speak) are strings themselves and can be concatenated by +. With most other sequence/iterable types, you have to clearly differentiate between the sequence and its elements. In this case you want to concatenate (sub)lists, not elements.


问:
Appending list to character
I'm attempting to append the Head of a list to an atom, recursively, however prolog keeps returning false and I'm unable to determine why.

My original code:

```<code>listpicket(K, [H1|T1], L) :-
    append([K], [H1], L),
    listpicket(K, T1, L).
</code>```

Run like:

```<code>?- listpicket(k, [a,b,c], L).
</code>```

Expected output:

```<code>[k, a, k, b, k, c].
</code>```

Actual output:

```<code>false.
</code>```

Suspecting the false is coming from the last recursive iteration, where there is no tail (T1, here), I tried handing that case like so:

```<code>listpicket(K, [H1|T1], L) :-
    (
        not(is_list(T1)),
        [K|T1]
    );
    append([K], [H1], L),
    listpicket(K, T1, L).
</code>```

But I also get false as the result.

What am I doing wrong?

答:
The fail comes because when second time you call the append/3 you must have an unistantiated variable but L is at that time isntantiated.

append/3 says give me two lists and one variable/un-instantiated and i will return concatenated lists.

You can adjust your code like this:

`

```<code>listpicket(K, [H1|T1], [NewL|L]) :-
   append([K], [H1], NewL),
   listpicket(K, T1, L).`
</code>```

and the base-case:

```<code>listpicket(_,[],[]).
</code>```

This code will work but still you will not get expected result because you are created lists in a list. Everytime append/3 returns a list and we add it as the head of the list.

Well, i will work this out like this:

```<code>listpicket(_,[],[]).
listpicket(K,[H|T],[K,H|L]):-
  listpicket(K,T,L).
</code>```

Title: Appending list to character

Body:
I'm attempting to append the Head of a list to an atom, recursively, however prolog keeps returning false and I'm unable to determine why.

My original code:

listpicket(K, [H1|T1], L) :-
    append([K], [H1], L),
    listpicket(K, T1, L).

Run like:

?- listpicket(k, [a,b,c], L).

Expected output:

[k, a, k, b, k, c].

Actual output:

false.

Suspecting the false is coming from the last recursive iteration, where there is no tail (T1, here), I tried handing that case like so:

listpicket(K, [H1|T1], L) :-
    (
        not(is_list(T1)),
        [K|T1]
    );
    append([K], [H1], L),
    listpicket(K, T1, L).

But I also get false as the result.

What am I doing wrong?

Body:
The fail comes because when second time you call the append/3 you must have an unistantiated variable but L is at that time isntantiated.

append/3 says give me two lists and one variable/un-instantiated and i will return concatenated lists.

You can adjust your code like this:

`

listpicket(K, [H1|T1], [NewL|L]) :-
   append([K], [H1], NewL),
   listpicket(K, T1, L).`

and the base-case:

listpicket(_,[],[]).

This code will work but still you will not get expected result because you are created lists in a list. Everytime append/3 returns a list and we add it as the head of the list.

Well, i will work this out like this:

listpicket(_,[],[]).
listpicket(K,[H|T],[K,H|L]):-
  listpicket(K,T,L).


问:
ReactJS POST Parameters Not Sent
I'm simply trying to get POST parameters on my PHP server, sent from my ReactJS app. In the server response, I can see that 'myParameter' is null. I think this is because of the Cross Origin issue, but I've tried many suggestions from answers to similar questions and nothing I've tried has worked. I believe that I'm looking for the proper code to add to my PHP file. It's been days now of this issue and I'm hoping someone here can help.

Background information (in case it matters at all). My PHP file is on my server hosted with hostgator. GET requests with URL parameters work perfectly, but POST parameters seem to be blocked. I'm trying to send more data than the URL option allows.

Thank you so much!

ReactJS Code:

```<code>axios.post('https://mywebsite.com/endpoint.php', {
  myParameter: 'test',
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});
</code>```

PHP Code:

```<code><?php

header("Access-Control-Allow-Origin: *");

echo json_encode($_POST['myParameter']);

?>
</code>```

I also tried this, but it did not change the result:

```<code><?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Max-Age: 86400');

echo json_encode($_POST['myParameter']);

?>
</code>```

EDIT:

Based on the answer from the post linked by Aaqib, I was able to successfully get the data on my server!

答:
i usually prefer the axios constructor with properties. its much more clearer then the short hand methods.</p>

```<code>axios({
  method:'POST',
  url:'https://mywebsite.com/endpoint.php',
  headers:{},
  data:{
    myParameter: 'test'
  }

}).then((res)=>{})
.catch((err)=>{});
</code>```

Title: ReactJS POST Parameters Not Sent

Body:
I'm simply trying to get POST parameters on my PHP server, sent from my ReactJS app. In the server response, I can see that 'myParameter' is null. I think this is because of the Cross Origin issue, but I've tried many suggestions from answers to similar questions and nothing I've tried has worked. I believe that I'm looking for the proper code to add to my PHP file. It's been days now of this issue and I'm hoping someone here can help.

Background information (in case it matters at all). My PHP file is on my server hosted with hostgator. GET requests with URL parameters work perfectly, but POST parameters seem to be blocked. I'm trying to send more data than the URL option allows.

Thank you so much!

ReactJS Code:

axios.post('https://mywebsite.com/endpoint.php', {
  myParameter: 'test',
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

PHP Code:

<?php

header("Access-Control-Allow-Origin: *");

echo json_encode($_POST['myParameter']);

?>

I also tried this, but it did not change the result:

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Max-Age: 86400');

echo json_encode($_POST['myParameter']);

?>

EDIT:

Based on the answer from the post linked by Aaqib, I was able to successfully get the data on my server!

Body:
i usually prefer the axios constructor with properties. its much more clearer then the short hand methods.

axios({
  method:'POST',
  url:'https://mywebsite.com/endpoint.php',
  headers:{},
  data:{
    myParameter: 'test'
  }

}).then((res)=>{})
.catch((err)=>{});


问:
Kotlin lambdas without using objects
I am trying to convert from java to kotlin. The current java interface is something like this:

```<code>interface MyInterface {
    void foo(int x, int y);
}

MyInterface testing = (int a, int b) -> System.out.print("TESTING");
</code>```

My current kotlin conversion is:

```<code>interface MyInterface {
    fun foo(x:Int, y:Int)
}

val kotlinConversion = object: MyInterface {
    override fun foo(x: Int, y: Int) {
        println("TESTING")
    }
}
</code>```

Is there a way to write the variable kotlinConversion such that it is similar to the one in java without having to override the function?

答:
Without  override the function you can directly use like this way</p>

```<code>var kotlinConversion = { a: Int, b: Int -> print("TESTING") }
</code>```

Title: Kotlin lambdas without using objects

Body:
I am trying to convert from java to kotlin. The current java interface is something like this:

interface MyInterface {
    void foo(int x, int y);
}

MyInterface testing = (int a, int b) -> System.out.print("TESTING");

My current kotlin conversion is:

interface MyInterface {
    fun foo(x:Int, y:Int)
}

val kotlinConversion = object: MyInterface {
    override fun foo(x: Int, y: Int) {
        println("TESTING")
    }
}

Is there a way to write the variable kotlinConversion such that it is similar to the one in java without having to override the function?

Body:
Without  override the function you can directly use like this way

var kotlinConversion = { a: Int, b: Int -> print("TESTING") }


问:
group all directly and indirectly related records using python pandas
thanks in advance:

I am trying to generate a group identifier in a many to many relationship table which has 2 columns defining IDs of parent entities and a child entities:

Example dataframe below: (parent (p), and child (c))

```<code>df = pd.DataFrame(np.array([[1,7],[1,3],[1,4],[3,2],[5,1],[6,0]]))
df.columns= ['p', 'c']
</code>```

Table looks like below:

```<code>p  c
1  7
1  3
1  4
3  2
5  1
6  0
</code>```

I am trying to get all directly and indirectly linked records in a group. For example:

Parent Record 1 is parent of [7,3,4], and

Parent Record 5 is the parent of 1

Parent Record 3 has is parent of 2 and 2 is grand-child of 1

So I want to generate an ID for all related record. where parent record 6 is not related to any record, I will move it to another group, a sample result like below:

```<code>p  c  grp
1  7  A
1  3  A
1  4  A
3  2  A
5  1  A
6  0  B
</code>```

My current way of thinking :

For each record, if it doesn't have a group yet:

Getting all directly related record IDs

Then for each directly related record IDs Recursively perform the same function to find all related record for the child until they have no child record

Then assign a group to the group of record IDs (list)

I am not sure if it is the right way to do it, and it seemed to be unnecessarily slow, and I have to pass down all the parent records in the chain to the child record in order for it not to perform the same search for already searched results.

Would really appreciate if someone can give me a better solution. :)

答:
You can check networkx

```<code>import networkx as nx

G=nx.from_pandas_dataframe(df, 'c', 'p')
l=list(nx.connected_components(G))
dfmap=pd.DataFrame.from_dict(l)
dfmap.index=['B','A']
dfmap=dfmap.stack()
d=dict(list(zip(dfmap.values.astype(int),dfmap.index.get_level_values(0))))
df['grp']=df.replace(d).p
df
Out[14]:
   p  c grp
0  1  7   A
1  1  3   A
2  1  4   A
3  3  2   A
4  5  1   A
5  6  0   B
</code>```

More Info

```<code>import matplotlib.pyplot as plt
nx.draw(G)
</code>```

Body:
thanks in advance:

I am trying to generate a group identifier in a many to many relationship table which has 2 columns defining IDs of parent entities and a child entities:

Example dataframe below: (parent (p), and child (c))

df = pd.DataFrame(np.array([[1,7],[1,3],[1,4],[3,2],[5,1],[6,0]]))
df.columns= ['p', 'c']

Table looks like below:

p  c
1  7
1  3
1  4
3  2
5  1
6  0

I am trying to get all directly and indirectly linked records in a group. For example:

Parent Record 1 is parent of [7,3,4], and

Parent Record 5 is the parent of 1

Parent Record 3 has is parent of 2 and 2 is grand-child of 1

So I want to generate an ID for all related record. where parent record 6 is not related to any record, I will move it to another group, a sample result like below:

p  c  grp
1  7  A
1  3  A
1  4  A
3  2  A
5  1  A
6  0  B

My current way of thinking :

For each record, if it doesn't have a group yet:

Getting all directly related record IDs

Then for each directly related record IDs Recursively perform the same function to find all related record for the child until they have no child record

Then assign a group to the group of record IDs (list)

I am not sure if it is the right way to do it, and it seemed to be unnecessarily slow, and I have to pass down all the parent records in the chain to the child record in order for it not to perform the same search for already searched results.

Would really appreciate if someone can give me a better solution. :)

Body:
You can check networkx

import networkx as nx

G=nx.from_pandas_dataframe(df, 'c', 'p')
l=list(nx.connected_components(G))
dfmap=pd.DataFrame.from_dict(l)
dfmap.index=['B','A']
dfmap=dfmap.stack()
d=dict(list(zip(dfmap.values.astype(int),dfmap.index.get_level_values(0))))
df['grp']=df.replace(d).p
df
Out[14]:
   p  c grp
0  1  7   A
1  1  3   A
2  1  4   A
3  3  2   A
4  5  1   A
5  6  0   B

More Info

import matplotlib.pyplot as plt
nx.draw(G)


问:
Can I use a lambda function or std::function object in place of a function pointer?
I've got a library that I need to use that defines the following:

```<code>typedef void CallbackFunction(const int& i);
</code>```

and has a function to register your callback that looks like:

```<code>void registerCallback(CallbackFunction* pCallback);
</code>```

Because I'd like to capture the state of several variables to be used in the callback, I can't simply use a plain function. What I'd prefer to use is a lambda function, but the following doesn't compile:

```<code>auto fCallback = [](const int& i) {
    cout << i << endl;
};
registerCallback(fCallback);
</code>```

instead I get the error:

```<code>error C2664: 'registerCallback' : cannot convert parameter 1 from '`anonymous-namespace'::<lambda0>' to 'CallbackFunction (__cdecl *)'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
</code>```

I've been reading up on this topic a lot, and trying a few different (probably idiotic) approaches, but I can't seem to get this to work. Casting the function allows the code to compile, but (not surprisingly) it crashes. It may be that I've overlooked the solution either here on StackOverflow or elsewhere, so a link will suffice. (Though, since I'm a bit new to some of these techniques, please make sure that the correspondence is clear enough for a newbie. For instance, if this conversation contains my answer, I don't understand. Please simplify or explain the correspondence.) FYI, I'm using Visual C++ 2010.

Please let me know if there is anything I can do to clarify my question. Thanks in advance for the help!

答:
In general, no you can't use a lambda or function object where a function pointer is required.  Function objects are full-fledged objects that have overloaded the application operator (()) so you can use them as functions syntactically.

The standard algorithms are written as templates, which allows you to pass either a function address (pointer) or a function object to them, because they use the same syntax.  When you pass a function object, a template is instantiated which accepts that function object; when you pass a function pointer, a different template is instantiated.

So to get lambdas/function objects to work with your code, you would need to modify the library you're using.

Body:
I've got a library that I need to use that defines the following:

typedef void CallbackFunction(const int& i);

and has a function to register your callback that looks like:

void registerCallback(CallbackFunction* pCallback);

Because I'd like to capture the state of several variables to be used in the callback, I can't simply use a plain function. What I'd prefer to use is a lambda function, but the following doesn't compile:

auto fCallback = [](const int& i) {
    cout << i << endl;
};
registerCallback(fCallback);

instead I get the error:

error C2664: 'registerCallback' : cannot convert parameter 1 from '`anonymous-namespace'::<lambda0>' to 'CallbackFunction (__cdecl *)'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

I've been reading up on this topic a lot, and trying a few different (probably idiotic) approaches, but I can't seem to get this to work. Casting the function allows the code to compile, but (not surprisingly) it crashes. It may be that I've overlooked the solution either here on StackOverflow or elsewhere, so a link will suffice. (Though, since I'm a bit new to some of these techniques, please make sure that the correspondence is clear enough for a newbie. For instance, if this conversation contains my answer, I don't understand. Please simplify or explain the correspondence.) FYI, I'm using Visual C++ 2010.

Please let me know if there is anything I can do to clarify my question. Thanks in advance for the help!


问:
Failed resolution of: Ldagger/internal/Preconditions
My app worked well but due to some problem with my operating system Debian I decided to reinstall it and I choose to install Ubuntu-16.04 instead of the last Debian. Now everything is OK.

The problem is my android application. After reinstalling android-studio the stable version, I can not test my application anymore.

Why? Because every time I launch the application, I got this error. I don't know what it means, and after some searching on the internet, I didn't get anywhere.

Here is the stack trace:

```<code>10-13 07:47:10.749 1631-1631/com.gre E/AndroidRuntime: FATAL EXCEPTION: main
                                                      Process: com.gre, PID: 1631
                                                      java.lang.NoClassDefFoundError: Failed resolution of: Ldagger/internal/Preconditions;
                                                          at com.gre.di.components.DaggerApplicationComponent$Builder.applicationModule(DaggerApplicationComponent.java:209)
                                                          at com.gre.GreApplication.onCreate(GreApplication.java:47)
                                                          at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1012)
                                                          at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4593)
                                                          at android.app.ActivityThread.access$1600(ActivityThread.java:154)
                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1382)
                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                          at android.os.Looper.loop(Looper.java:135)
                                                          at android.app.ActivityThread.main(ActivityThread.java:5294)
                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                          at java.lang.reflect.Method.invoke(Method.java:372)
                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
                                                       Caused by: java.lang.ClassNotFoundException: Didn't find class "dagger.internal.Preconditions" on path: DexPathList[[zip file "/data/app/com.gre-1/base.apk", zip file "/data/app/com.gre-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.gre-1/lib/arm, /vendor/lib, /system/lib]]
                                                          at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
                                                          at com.gre.di.components.DaggerApplicationComponent$Builder.applicationModule(DaggerApplicationComponent.java:209)
                                                          at com.gre.GreApplication.onCreate(GreApplication.java:47)
                                                          at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1012)
                                                          at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4593)
                                                          at android.app.ActivityThread.access$1600(ActivityThread.java:154)
                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1382)
                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                          at android.os.Looper.loop(Looper.java:135)
                                                          at android.app.ActivityThread.main(ActivityThread.java:5294)
                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                          at java.lang.reflect.Method.invoke(Method.java:372)
                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
                                                        Suppressed: java.lang.ClassNotFoundException: dagger.internal.Preconditions
                                                          at java.lang.Class.classForName(Native Method)
                                                          at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
                                                          at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
                                                                ... 14 more
                                                       Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
</code>```

How to solve it please ??

Here is my build.gradle file

    apply plugin: 'com.android.application'
     apply plugin: 'realm-android'
     // apply plugin: 'com.neenbedankt.android-apt'

     android {
         compileSdkVersion 25
         buildToolsVersion '25.0.2' // '23.0.2'

    defaultConfig {
        applicationId "com.gre"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        /*debug {
            applicationIdSuffix ".debug"
        }*/

        /**
         * The 'initWith' property allows you to copy configurations from other build types,
         * so you don't have to configure one from the beginning. You can then configure
         * just the settings you want to change. The following line initializes
         * 'jnidebug' using the debug build type, and changes only the
         * applicationIdSuffix and versionNameSuffix settings.
         */

        jnidebug {

            // This copies the debuggable attribute and debug signing configurations.
            initWith debug

            applicationIdSuffix ".jnidebug"
            jniDebuggable true
        }
    }
    dexOptions {
        // javaMaxHeapSize "2048M"
        javaMaxHeapSize "4g"
    }
    configurations.all {
        // all*.exclude group: 'com.squareup.okhttp3', module: 'okhttp'configurations.all {
        // OkHttp 3.5.0+ includes the websockets API, so we need this to prevent a conflict
        exclude module: 'okhttp-ws'
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile('io.socket:socket.io-client:0.8.1') {
        exclude group: 'org.json', module: 'json'
    }

    /*compile 'com.google.android.gms:play-services-auth:10.0.1'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    compile 'com.google.android.gms:play-services-appindexing:10.0.1'*/

    // compile 'com.android.support.constraint:constraint-layout:1.0.2'

    // Android
    // Glide

    // Facebook Stetho
    // OkHttp
    // SquareUp
    // Rx
    // Dragger
    // Realm

    // RippleButton
    compile 'com.balysv:material-ripple:1.0.2'
    compile 'com.android.support:appcompat-v7:'
    compile "com.android.support:cardview-v7:${buildTools}"
    compile "com.android.support:recyclerview-v7:${buildTools}"
    compile "com.android.support:design:${buildTools}"
    compile "com.android.support:support-v13:${buildTools}"
    compile "com.android.support:support-v4:${buildTools}"
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.github.bumptech.glide:glide:4.0.0-RC0'
    compile 'com.github.florent37:materialtextfield:1.0.7'
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
    compile 'com.splitwise:tokenautocomplete:2.0.8@aar'
    compile 'com.github.Plumillon:ChipView:1.2.0'
    compile 'com.github.clans:fab:1.6.4'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
    compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.google.android.gms:play-services-location:10.2.6'
    compile 'com.google.android.gms:play-services-maps:10.2.6'
    compile 'com.google.firebase:firebase-core:9.2.0'
    compile 'com.google.firebase:firebase-messaging:9.2.0'
    compile 'com.bignerdranch.android:recyclerview-multiselect:+'
    compile 'com.facebook.stetho:stetho:1.5.0'
    compile 'com.uphyca:stetho_realm:2.0.0'
    compile 'com.lapism:searchview:4.0'
    compile 'com.miguelcatalan:materialsearchview:1.4.0'
    compile 'com.github.arimorty:floatingsearchview:2.1.1'
    compile 'me.philio:pinentryview:1.0.6'
    compile 'com.alimuzaffar.lib:pinentryedittext:1.3.1'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.github.pchmn:MaterialChipsInput:1.0.8'

    /*----- Retrofit 2 */
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
    compile 'com.squareup.okhttp3:okhttp-ws:3.4.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'io.reactivex.rxjava2:rxjava:2.0.2'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
    compile 'com.google.dagger:dagger:2.11'
    compile 'com.google.dagger:dagger-android:2.11'
    compile 'javax.inject:javax.inject:1'
    compile 'io.realm:android-adapters:2.0.0'
    compile 'org.parceler:parceler-api:1.1.6'
    compile 'com.jakewharton:butterknife:8.5.1'
    compile 'com.theartofdev.edmodo:android-image-cropper:2.4.+'
    compile 'com.github.yalantis:ucrop:2.2.1-native'
    compile 'jp.wasabeef:picasso-transformations:2.1.2'
    compile 'jp.co.cyberagent.android.gpuimage:gpuimage-library:1.4.1'
    compile 'com.github.dmytrodanylyk:android-morphing-button:98a4986e56'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    annotationProcessor 'com.google.dagger:dagger-android-processor:2.11'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.11'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0-RC0'
    annotationProcessor 'org.parceler:parceler:1.1.6'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
    provided 'javax.annotation:jsr250-api:1.0'
    compile 'com.mikhaellopez:circularimageview:3.0.2'          // circle image view
}

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

答:
I faced the same problem and spent 2 - 3 hours over it and I am able to find that this problem is caused by dex limit. In your app.gradle file please make following changes:

```<code>defaultConfig {
    multiDexEnabled true
}
</code>```

And inside dependencies section add

```<code>compile 'com.android.support:multidex:1.0.2'
</code>```

and the last thing you need todo is,

```<code>public class YourApplication extends MultiDexApplication {
...
}
</code>```

you have to use MultiDexApplication rather than Application class. Hope some dev comes out using this solution.

Body:
My app worked well but due to some problem with my operating system Debian I decided to reinstall it and I choose to install Ubuntu-16.04 instead of the last Debian. Now everything is OK.

The problem is my android application. After reinstalling android-studio the stable version, I can not test my application anymore.

Why? Because every time I launch the application, I got this error. I don't know what it means, and after some searching on the internet, I didn't get anywhere.

Here is the stack trace:

10-13 07:47:10.749 1631-1631/com.gre E/AndroidRuntime: FATAL EXCEPTION: main
                                                      Process: com.gre, PID: 1631
                                                      java.lang.NoClassDefFoundError: Failed resolution of: Ldagger/internal/Preconditions;
                                                          at com.gre.di.components.DaggerApplicationComponent$Builder.applicationModule(DaggerApplicationComponent.java:209)
                                                          at com.gre.GreApplication.onCreate(GreApplication.java:47)
                                                          at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1012)
                                                          at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4593)
                                                          at android.app.ActivityThread.access$1600(ActivityThread.java:154)
                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1382)
                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                          at android.os.Looper.loop(Looper.java:135)
                                                          at android.app.ActivityThread.main(ActivityThread.java:5294)
                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                          at java.lang.reflect.Method.invoke(Method.java:372)
                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
                                                       Caused by: java.lang.ClassNotFoundException: Didn't find class "dagger.internal.Preconditions" on path: DexPathList[[zip file "/data/app/com.gre-1/base.apk", zip file "/data/app/com.gre-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.gre-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.gre-1/lib/arm, /vendor/lib, /system/lib]]
                                                          at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
                                                          at com.gre.di.components.DaggerApplicationComponent$Builder.applicationModule(DaggerApplicationComponent.java:209)
                                                          at com.gre.GreApplication.onCreate(GreApplication.java:47)
                                                          at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1012)
                                                          at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4593)
                                                          at android.app.ActivityThread.access$1600(ActivityThread.java:154)
                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1382)
                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                          at android.os.Looper.loop(Looper.java:135)
                                                          at android.app.ActivityThread.main(ActivityThread.java:5294)
                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                          at java.lang.reflect.Method.invoke(Method.java:372)
                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
                                                        Suppressed: java.lang.ClassNotFoundException: dagger.internal.Preconditions
                                                          at java.lang.Class.classForName(Native Method)
                                                          at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
                                                          at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
                                                          at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
                                                                ... 14 more
                                                       Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

How to solve it please ??

Here is my build.gradle file

    apply plugin: 'com.android.application'
     apply plugin: 'realm-android'
     // apply plugin: 'com.neenbedankt.android-apt'

     android {
         compileSdkVersion 25
         buildToolsVersion '25.0.2' // '23.0.2'

    defaultConfig {
        applicationId "com.gre"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        /*debug {
            applicationIdSuffix ".debug"
        }*/

        /**
         * The 'initWith' property allows you to copy configurations from other build types,
         * so you don't have to configure one from the beginning. You can then configure
         * just the settings you want to change. The following line initializes
         * 'jnidebug' using the debug build type, and changes only the
         * applicationIdSuffix and versionNameSuffix settings.
         */

        jnidebug {

            // This copies the debuggable attribute and debug signing configurations.
            initWith debug

            applicationIdSuffix ".jnidebug"
            jniDebuggable true
        }
    }
    dexOptions {
        // javaMaxHeapSize "2048M"
        javaMaxHeapSize "4g"
    }
    configurations.all {
        // all*.exclude group: 'com.squareup.okhttp3', module: 'okhttp'configurations.all {
        // OkHttp 3.5.0+ includes the websockets API, so we need this to prevent a conflict
        exclude module: 'okhttp-ws'
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile('io.socket:socket.io-client:0.8.1') {
        exclude group: 'org.json', module: 'json'
    }

    /*compile 'com.google.android.gms:play-services-auth:10.0.1'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    compile 'com.google.android.gms:play-services-appindexing:10.0.1'*/

    // compile 'com.android.support.constraint:constraint-layout:1.0.2'

    // Android
    // Glide

    // Facebook Stetho
    // OkHttp
    // SquareUp
    // Rx
    // Dragger
    // Realm

    // RippleButton
    compile 'com.balysv:material-ripple:1.0.2'
    compile 'com.android.support:appcompat-v7:'
    compile "com.android.support:cardview-v7:${buildTools}"
    compile "com.android.support:recyclerview-v7:${buildTools}"
    compile "com.android.support:design:${buildTools}"
    compile "com.android.support:support-v13:${buildTools}"
    compile "com.android.support:support-v4:${buildTools}"
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.github.bumptech.glide:glide:4.0.0-RC0'
    compile 'com.github.florent37:materialtextfield:1.0.7'
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
    compile 'com.splitwise:tokenautocomplete:2.0.8@aar'
    compile 'com.github.Plumillon:ChipView:1.2.0'
    compile 'com.github.clans:fab:1.6.4'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.amulyakhare:com.amulyakhare.textdrawable:1.0.1'
    compile 'com.google.android.gms:play-services:10.2.6'
    compile 'com.google.android.gms:play-services-location:10.2.6'
    compile 'com.google.android.gms:play-services-maps:10.2.6'
    compile 'com.google.firebase:firebase-core:9.2.0'
    compile 'com.google.firebase:firebase-messaging:9.2.0'
    compile 'com.bignerdranch.android:recyclerview-multiselect:+'
    compile 'com.facebook.stetho:stetho:1.5.0'
    compile 'com.uphyca:stetho_realm:2.0.0'
    compile 'com.lapism:searchview:4.0'
    compile 'com.miguelcatalan:materialsearchview:1.4.0'
    compile 'com.github.arimorty:floatingsearchview:2.1.1'
    compile 'me.philio:pinentryview:1.0.6'
    compile 'com.alimuzaffar.lib:pinentryedittext:1.3.1'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.github.pchmn:MaterialChipsInput:1.0.8'

    /*----- Retrofit 2 */
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
    compile 'com.squareup.okhttp3:okhttp-ws:3.4.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'io.reactivex.rxjava2:rxjava:2.0.2'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
    compile 'com.google.dagger:dagger:2.11'
    compile 'com.google.dagger:dagger-android:2.11'
    compile 'javax.inject:javax.inject:1'
    compile 'io.realm:android-adapters:2.0.0'
    compile 'org.parceler:parceler-api:1.1.6'
    compile 'com.jakewharton:butterknife:8.5.1'
    compile 'com.theartofdev.edmodo:android-image-cropper:2.4.+'
    compile 'com.github.yalantis:ucrop:2.2.1-native'
    compile 'jp.wasabeef:picasso-transformations:2.1.2'
    compile 'jp.co.cyberagent.android.gpuimage:gpuimage-library:1.4.1'
    compile 'com.github.dmytrodanylyk:android-morphing-button:98a4986e56'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    annotationProcessor 'com.google.dagger:dagger-android-processor:2.11'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.11'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0-RC0'
    annotationProcessor 'org.parceler:parceler:1.1.6'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
    provided 'javax.annotation:jsr250-api:1.0'
    compile 'com.mikhaellopez:circularimageview:3.0.2'          // circle image view
}

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

Body:
I faced the same problem and spent 2 - 3 hours over it and I am able to find that this problem is caused by dex limit. In your app.gradle file please make following changes:

defaultConfig {
    multiDexEnabled true
}

And inside dependencies section add

compile 'com.android.support:multidex:1.0.2'

and the last thing you need todo is,

public class YourApplication extends MultiDexApplication {
...
}

you have to use MultiDexApplication rather than Application class. Hope some dev comes out using this solution.


问:
How to implement logout in django in template?
This is my views.py

```<code>from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
import os

# Create your views here.
@csrf_exempt
def index(request):
    if('loggedIn' in request.session):
        id = request.session['uid'];
        return render(request,"index.html",{'uid':id});
    else:
        return render(request,"index.html",{});
</code>```

urls.py

```<code>from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index) ]
</code>```

This is the first time I am doing a Django project. I was able to log in and now see the index page. Now I have a logout button as  Logout

So, what can I need to do to log out from the system.. Please I am not getting idea behind the same.. It will be great If, somebody helped me.

答:
This is a custom view for logout and this will do your work. However, as others have rightly pointed out Django has builtin authentication system and this is basically redoing the same.

(urls.py)

```<code>url(r'^logout', views.logout, name='logout'),
</code>```

(view.py)

```<code>from django.contrib.auth import logout as auth_logout

def logout(request):
    auth_logout(request)
    return render(request,"your logout page");
</code>```

Body:
This is my views.py

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
import os

# Create your views here.
@csrf_exempt
def index(request):
    if('loggedIn' in request.session):
        id = request.session['uid'];
        return render(request,"index.html",{'uid':id});
    else:
        return render(request,"index.html",{});

urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index) ]

This is the first time I am doing a Django project. I was able to log in and now see the index page. Now I have a logout button as  Logout

So, what can I need to do to log out from the system.. Please I am not getting idea behind the same.. It will be great If, somebody helped me.

Body:
This is a custom view for logout and this will do your work. However, as others have rightly pointed out Django has builtin authentication system and this is basically redoing the same.

(urls.py)

url(r'^logout', views.logout, name='logout'),

(view.py)

from django.contrib.auth import logout as auth_logout

def logout(request):
    auth_logout(request)
    return render(request,"your logout page");


问:
ToolProvider.getSystemJavaCompiler() returning null in JDK 9
My project in Eclipse is running WITH SYSTEM JRE 9. When I try to set Java home to JDK 9 to get the system compiler I got null.

```<code>System.setProperty("java.home", "C:\\Program Files\\Java\\jdk-9.0.1");
System.out.println(System.getProperty("java.home")); // print C:\Program Files\Java\jdk-9.0.1
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); // returns null
</code>```

This code previously works fine with JDK 8 (running from JRE 8)

```<code>System.setProperty("java.home", "C:\\Program Files\\Java\\jdk1.8.0_152");
System.out.println(System.getProperty("java.home")); // print C:\Program Files\Java\jdk1.8.0_152
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); // returns compiler
</code>```

Has there been any change to how ToolProvider.getSystemJavaCompiler requirement works?

Update: not sure if it matters but getSystemJavaCompiler() works fine if I run my project from JDK 9 (change to java.home is no longer required) as opposed to JRE 9.

答:
Correspondingly changing the path on Unix to /Contents/Home works for me :

```<code>System.setProperty("java.home",
                   "/Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home/");
</code>```

Though there doesn't seem to be a need of setting the property at all. Since the following line of code even independently executes fine as well:

```<code>JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
</code>```

with JAVA_HOMEon my system set to point to JDK9 Home directory.

Body:
My project in Eclipse is running WITH SYSTEM JRE 9. When I try to set Java home to JDK 9 to get the system compiler I got null.

System.setProperty("java.home", "C:\\Program Files\\Java\\jdk-9.0.1");
System.out.println(System.getProperty("java.home")); // print C:\Program Files\Java\jdk-9.0.1
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); // returns null

This code previously works fine with JDK 8 (running from JRE 8)

System.setProperty("java.home", "C:\\Program Files\\Java\\jdk1.8.0_152");
System.out.println(System.getProperty("java.home")); // print C:\Program Files\Java\jdk1.8.0_152
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); // returns compiler

Has there been any change to how ToolProvider.getSystemJavaCompiler requirement works?

Update: not sure if it matters but getSystemJavaCompiler() works fine if I run my project from JDK 9 (change to java.home is no longer required) as opposed to JRE 9.

Body:
Correspondingly changing the path on Unix to /Contents/Home works for me :

System.setProperty("java.home",
                   "/Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home/");

Though there doesn't seem to be a need of setting the property at all. Since the following line of code even independently executes fine as well:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

with JAVA_HOMEon my system set to point to JDK9 Home directory.


答:
is this helpful</p>

```<code>    create table #tmp (Date float, Name varchar(10))

    insert into #tmp values(9.53,'ron')
    insert into #tmp values(9.57,'ron')
    insert into #tmp values(9.87,'ron')

    insert into #tmp values(10.2,'jess')
    insert into #tmp values(10.2,'jess')

    insert into #tmp values(11.3,'mike')
    insert into #tmp values(11.3,'mike')

    insert into #tmp values(16.58,'ron')
    insert into #tmp values(16.33,'ron')
    insert into #tmp values(16.45,'ron')

    insert into #tmp values(22.43,'jess')
    insert into #tmp values(22.88,'jess')

    insert into #tmp values(19.2,'mike')
    insert into #tmp values(19.51,'mike')

    SELECT DISTINCT floor(Date) AS Date,Name from #tmp

    drop table #tmp
</code>```

Title: SQL Return distinct rows based on two columns by rounding column to nearest value

Body:
Following is the Table:

ID  C1  C2  C3  Date    C5  C6  Name
1   ### ### ### 9.53    ### ### ron
1   ### ### ### 9.57    ### ### ron
1   ### ### ### 9.87    ### ### ron
1   ### ### ### 10.2    ### ### jess
1   ### ### ### 10.2    ### ### jess
1   ### ### ### 11.3    ### ### mike
1   ### ### ### 11.3    ### ### mike
2   ### ### ### 16.58   ### ### ron
2   ### ### ### 16.33   ### ### ron
2   ### ### ### 16.45   ### ### ron
2   ### ### ### 22.43   ### ### jess
2   ### ### ### 22.88   ### ### jess
2   ### ### ### 19.2    ### ### mike
2   ### ### ### 19.51   ### ### mike

Following is what i am expecting:

Gettting distinct rows based on ID and Name, grouping by Date to nearest round number.

ID  C1  C2  C3  Date    C5  C6  Name
1   ### ### ### 9      ###  ### ron
1   ### ### ### 10     ###  ### jess
1   ### ### ### 11     ###  ### mike
2   ### ### ### 16     ###  ### ron
2   ### ### ### 22     ###  ### jess
2   ### ### ### 19     ###  ### mike

Can anyone help me on this?

Body:
is this helpful

    create table #tmp (Date float, Name varchar(10))

    insert into #tmp values(9.53,'ron')
    insert into #tmp values(9.57,'ron')
    insert into #tmp values(9.87,'ron')

    insert into #tmp values(10.2,'jess')
    insert into #tmp values(10.2,'jess')

    insert into #tmp values(11.3,'mike')
    insert into #tmp values(11.3,'mike')

    insert into #tmp values(16.58,'ron')
    insert into #tmp values(16.33,'ron')
    insert into #tmp values(16.45,'ron')

    insert into #tmp values(22.43,'jess')
    insert into #tmp values(22.88,'jess')

    insert into #tmp values(19.2,'mike')
    insert into #tmp values(19.51,'mike')

    SELECT DISTINCT floor(Date) AS Date,Name from #tmp

    drop table #tmp


问:
images for carousel are not showing in firefox
The images for my carousel are not showing, only in Firefox and when you maximize the browser. I can see the controls at bottom of carousel where it says next and prev.

Everything is showing fine in chrome and IE, and when you minimize the Firefox browser.

http://www.henschen.com/siteTemplates/2014-16/

```<code><div id="owl-demo" class="owl-carousel owl-theme">
     <div class="item"><img src="images/slider1.png" alt="test"></div>
     <div class="item"><img src="images/slider2.png" alt="test"></div>
     <div class="item"><img src="images/slider3.png" alt="test"></div>
</div>

#owl-demo .item img {
      display: block;
      width: 100%;
      height: auto;
}
</code>```

答:
First ensure to confirm that you don't have any @media definition that takes out the carousel if that is not the case  then

look for this css definition
"@media all and (transform-3d), (-webkit-transform-3d) {"
change to
"@media all and (transform-3d), (-webkit-transform-3d), (-moz-transform-3d) {"
some how firefox has issues with transform-3d
also
then check if you have any css definition for the carousel  that defines position . ensure to take out the position attribute and try again . Hope it works for you

Body:
The images for my carousel are not showing, only in Firefox and when you maximize the browser. I can see the controls at bottom of carousel where it says next and prev.

Everything is showing fine in chrome and IE, and when you minimize the Firefox browser.

http://www.henschen.com/siteTemplates/2014-16/

#owl-demo .item img {
      display: block;
      width: 100%;
      height: auto;
}


问:
Flex dynamic tabs using ViewStack
I'm having problems creating dynamic tabs
here's my code:

mxml:

```<code><s:TabBar x="1" y="1" height="32" width="100%" dataProvider="{tabHolder}" chromeColor="#EF8B01"/>
    <mx:ViewStack x="2" y="34" id="tabHolder" width="100%" height="214" creationPolicy="all">
        <s:NavigatorContent label="Home" width="100%" height="100%">
            <mx:Image x="6" y="8" height="181" width="402"/>
        </s:NavigatorContent>
    </mx:ViewStack>
</code>```

as:

```<code> var newTab:NavigatorContent = new NavigatorContent();
            newTab.label = "Dynamic";
            var lab:Label = new Label();
            lab.text = "Dynamic context";
            newTab.addChild(lab);

            tabHolder.addChild(newTab);
</code>```

tab wasn't added, what is wrong?

答:
The following worked for me. The only thing I changed was using the addElement() method instead of addChild() to add the tab to the viewstack.

MXML:

```<code><mx:Button id="myButton" label="Add Tab" click="myButton_clickHandler(event)" />
<s:TabBar x="1" y="31" height="32" width="100%" dataProvider="{tabHolder}" chromeColor="#EF8B01"/>
<mx:ViewStack x="2" y="64" id="tabHolder" width="100%" height="214" creationPolicy="all">
  <s:NavigatorContent label="Home" width="100%" height="100%">
    <mx:Image x="6" y="8" height="181" width="402"/>
  </s:NavigatorContent>
</mx:ViewStack>
</code>```

ActionScript:

```<code>protected function myButton_clickHandler(event:MouseEvent):void
{
  var newTab:NavigatorContent = new NavigatorContent();
  newTab.label = "Dynamic";
  var lab:Label = new Label();
  lab.text = "Dynamic context";
  newTab.addElement(lab);
  tabHolder.addElement(newTab);
}
</code>```

Title: Flex dynamic tabs using ViewStack

Body:
I'm having problems creating dynamic tabs
here's my code:

mxml:

<s:TabBar x="1" y="1" height="32" width="100%" dataProvider="{tabHolder}" chromeColor="#EF8B01"/>
    <mx:ViewStack x="2" y="34" id="tabHolder" width="100%" height="214" creationPolicy="all">
        <s:NavigatorContent label="Home" width="100%" height="100%">
            <mx:Image x="6" y="8" height="181" width="402"/>
        </s:NavigatorContent>
    </mx:ViewStack>

as:

 var newTab:NavigatorContent = new NavigatorContent();
            newTab.label = "Dynamic";
            var lab:Label = new Label();
            lab.text = "Dynamic context";
            newTab.addChild(lab);

            tabHolder.addChild(newTab);

tab wasn't added, what is wrong?

Body:
The following worked for me. The only thing I changed was using the addElement() method instead of addChild() to add the tab to the viewstack.

MXML:

<mx:Button id="myButton" label="Add Tab" click="myButton_clickHandler(event)" />
<s:TabBar x="1" y="31" height="32" width="100%" dataProvider="{tabHolder}" chromeColor="#EF8B01"/>
<mx:ViewStack x="2" y="64" id="tabHolder" width="100%" height="214" creationPolicy="all">
  <s:NavigatorContent label="Home" width="100%" height="100%">
    <mx:Image x="6" y="8" height="181" width="402"/>
  </s:NavigatorContent>
</mx:ViewStack>

ActionScript:

protected function myButton_clickHandler(event:MouseEvent):void
{
  var newTab:NavigatorContent = new NavigatorContent();
  newTab.label = "Dynamic";
  var lab:Label = new Label();
  lab.text = "Dynamic context";
  newTab.addElement(lab);
  tabHolder.addElement(newTab);
}


问:
How to merge two the same objects in Ruby
I have two objects that look like this:

```<code>obj1 = { hostname: "test",
         cpu: 20,
         disk_space: nil,
         ram: nil,
         check_time: "2017-12-05 01:28" }

obj2 = { hostname: "test",
         cpu: nil,
         disk_space: 3000,
         ram: nil,
         check_time: "2017-12-05 01:28"}
</code>```

I want to overwrite disk_space: nil with disk_space: 3000 from obj2. I want to basicaly overwrite nils.

```<code>new_obj = { hostname: "test",
            cpu: 20,
            disk_space: 3000,
            ram: nil,
            check_time: "2017-12-05 01:28" }
</code>```

How can I achieve this in Ruby?

答:
I prefer @StefanPochman's answer, but since that approach was taken, here's another.</p>

```<code>obj1.merge obj2.select { |k,_| obj1[k].nil? }
  #=> {:hostname=>"test", :cpu=>20, :disk_space=>3000, :ram=>nil,
  #    :check_time=>"2017-12-05 01:28"}
</code>```

Body:
I have two objects that look like this:

obj1 = { hostname: "test",
         cpu: 20,
         disk_space: nil,
         ram: nil,
         check_time: "2017-12-05 01:28" }

obj2 = { hostname: "test",
         cpu: nil,
         disk_space: 3000,
         ram: nil,
         check_time: "2017-12-05 01:28"}

I want to overwrite disk_space: nil with disk_space: 3000 from obj2. I want to basicaly overwrite nils.

new_obj = { hostname: "test",
            cpu: 20,
            disk_space: 3000,
            ram: nil,
            check_time: "2017-12-05 01:28" }

How can I achieve this in Ruby?

Body:
I prefer @StefanPochman's answer, but since that approach was taken, here's another.

obj1.merge obj2.select { |k,_| obj1[k].nil? }
  #=> {:hostname=>"test", :cpu=>20, :disk_space=>3000, :ram=>nil,
  #    :check_time=>"2017-12-05 01:28"}


问:
Crash : requires android.permission.READ_CALL_LOG or android.permission.WRITE_CALL_LOG On some devices
I have made an app that tracks call log in background using ContentObserver and service(runs in foreground).
Manifest.permission.CALL_PHONE
This is the permission i am checking for

```<code>if (CallTrackingHelper.isCallPermissionEnabled(appContext)) {
        val task = OneoffTask.Builder()
                .setService(CallLogService::class.java)
                .setExecutionWindow(0, 6)
                .setTag("call-track")
                .setRequiredNetwork(Task.NETWORK_STATE_ANY)
                .setRequiresCharging(false)
                .setUpdateCurrent(true)
                .build()

        val mGcmNetworkManager = GcmNetworkManager.getInstance(appContext)
        mGcmNetworkManager.schedule(task)
    }
</code>```

i start a gcmtaskservice that uploads call-log to server

```<code> override fun onRunTask(p0: TaskParams?): Int {
    val callLogs = CallTrackingHelper.getCallLog(lastSyncedIndex, this)
    //
}
</code>```

in service i fetch contact

```<code> fun getCallLog(id: Long, service: CallLogService): ArrayList<CallLogModel> {
    val callLogList = ArrayList<CallLogModel>()
    if (!isCallPermissionEnabled(service)) {
        return callLogList
    }
    var mCursor: Cursor? = null
    try {
        val args = arrayOf(id.toString())
        if (id != 0L) {
            mCursor = UCApplication
                    .getInstance()
                    .applicationContext
                    .contentResolver
                    .query(
                            CallLog.Calls.CONTENT_URI,
                            null,
                            "_id > ? ",
                            args,
                            null
                    )
        } else {
            mCursor = UCApplication
                    .getInstance()
                    .applicationContext
                    .contentResolver
                    .query(
                            CallLog.Calls.CONTENT_URI,
                            null,
                            null,
                            null,
                            CallLog.Calls._ID + " DESC" + " LIMIT 200 "
                    )
        }
    } catch (e: SecurityException) {
        //
    }
  //
    return callLogList
}

fun isCallPermissionEnabled(context: Context?): Boolean {
    if (context == null || ContextCompat.checkSelfPermission(context, PERMISSIONS)
            != PackageManager.PERMISSION_GRANTED) {
        return false
    }
    return true
}
</code>```

Still i am getting lot of securityException so I have to add try and catch

答:
Issue was that if user already has an app without
<uses-permission android:name="android.permission.READ_CALL_LOG"></uses-permission>
<uses-permission android:name="android.permission.WRITE_CALL_LOG"></uses-permission>

in manifest and gives call permission or phone permission , after update  if these are added in update call/phone permission is still their but call log permission is not so you need to ask again.
Fresh install was working fine for me

Body:
I have made an app that tracks call log in background using ContentObserver and service(runs in foreground).
Manifest.permission.CALL_PHONE
This is the permission i am checking for

if (CallTrackingHelper.isCallPermissionEnabled(appContext)) {
        val task = OneoffTask.Builder()
                .setService(CallLogService::class.java)
                .setExecutionWindow(0, 6)
                .setTag("call-track")
                .setRequiredNetwork(Task.NETWORK_STATE_ANY)
                .setRequiresCharging(false)
                .setUpdateCurrent(true)
                .build()

        val mGcmNetworkManager = GcmNetworkManager.getInstance(appContext)
        mGcmNetworkManager.schedule(task)
    }

i start a gcmtaskservice that uploads call-log to server

 override fun onRunTask(p0: TaskParams?): Int {
    val callLogs = CallTrackingHelper.getCallLog(lastSyncedIndex, this)
    //
}

in service i fetch contact

 fun getCallLog(id: Long, service: CallLogService): ArrayList<CallLogModel> {
    val callLogList = ArrayList<CallLogModel>()
    if (!isCallPermissionEnabled(service)) {
        return callLogList
    }
    var mCursor: Cursor? = null
    try {
        val args = arrayOf(id.toString())
        if (id != 0L) {
            mCursor = UCApplication
                    .getInstance()
                    .applicationContext
                    .contentResolver
                    .query(
                            CallLog.Calls.CONTENT_URI,
                            null,
                            "_id > ? ",
                            args,
                            null
                    )
        } else {
            mCursor = UCApplication
                    .getInstance()
                    .applicationContext
                    .contentResolver
                    .query(
                            CallLog.Calls.CONTENT_URI,
                            null,
                            null,
                            null,
                            CallLog.Calls._ID + " DESC" + " LIMIT 200 "
                    )
        }
    } catch (e: SecurityException) {
        //
    }
  //
    return callLogList
}

fun isCallPermissionEnabled(context: Context?): Boolean {
    if (context == null || ContextCompat.checkSelfPermission(context, PERMISSIONS)
            != PackageManager.PERMISSION_GRANTED) {
        return false
    }
    return true
}

Still i am getting lot of securityException so I have to add try and catch


问:
Merge rows together if : is present shell script
I have data in below format in a text file.

```<code>desc            : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Mana
gement
ldesc            : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Man
agement (BCD-WQ-UIO, BCD-WQ-BN)
date                          :
</code>```

I am trying to get the output in below format .

```<code>desc                          : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Management
ldesc                          : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Management (BCD-WQ-UIO, BCD-WQ-BN)
</code>```

Basically I want any row which has colon but nothing following a colon should be deleted and if any row doesn't have a colon it should be merged with previous row including space if any.

I tried using awk but I am unable to proceed.

Regards.

答:
To merge a line with the previous line, you must avoid printing the newline until you know whether to merge or not.  Don't forget printing the final newline when you reach the end of the file!</p>

```<code>awk '/:./ { printf "%s", $0; pending=1; next }
     /:$/ { if (pending) printf "\n"; pending=0; next }
     pending { printf "%s\n", $0; pending=0 }
     END { if (pending) printf "\n" }' file
</code>```

Body:
I have data in below format in a text file.

desc            : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Mana
gement
ldesc            : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Man
agement (BCD-WQ-UIO, BCD-WQ-BN)
date                          :

I am trying to get the output in below format .

desc                          : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Management
ldesc                          : Abced ONE 12345678 Suites YUITREWQ & RTYUIO Management (BCD-WQ-UIO, BCD-WQ-BN)

Basically I want any row which has colon but nothing following a colon should be deleted and if any row doesn't have a colon it should be merged with previous row including space if any.

I tried using awk but I am unable to proceed.

Regards.

Body:
To merge a line with the previous line, you must avoid printing the newline until you know whether to merge or not.  Don't forget printing the final newline when you reach the end of the file!

awk '/:./ { printf "%s", $0; pending=1; next }
     /:$/ { if (pending) printf "\n"; pending=0; next }
     pending { printf "%s\n", $0; pending=0 }
     END { if (pending) printf "\n" }' file


问:
Image and document upload/download in Elasticsearch
I'm looking to build an app around Elasticsearch with image and file upload/download. So a user uploads an image or document (PDF, Word, etc.), the image gets stored, and retrieved later by users and admin. It looks like Elastic can import/ingest data from files and images, but it is not clear to me if the image/file itself can be uploaded and retrieved. I just need to know if that is possible. If not I'll need to include another system into my app.</p>

答:
You need first to ingest attachment processor for storing any media files into elasticsearch.

So first you need to install elasticsearch plugin.

```<code>sudo bin/elasticsearch-plugin install ingest-attachment
</code>```

After this ingest pipeline  processor

```<code>PUT _ingest/pipeline/attachment
{
  "description" : "Extract attachment information",
  "processors" : [
    {
      "attachment" : {
        "field" : "data"
      }
    }
  ]
}
</code>```

Here "data" is your filed name where you want to store media files.

After this you can successfully insert the document into index. for ex .

```<code>PUT my_index/my_type/my_id?pipeline=attachment
{
  "data": "e1xydGYxXGFuc2kNCkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0DQpccGFyIH0="
}
</code>```

The data field wants encoded Base64 String of media files.

So first you need to convert media files to byte array to Base64 encoded string.

Source is : Attachment in elasticsearch

Body:
You need first to ingest attachment processor for storing any media files into elasticsearch.

So first you need to install elasticsearch plugin.

sudo bin/elasticsearch-plugin install ingest-attachment

After this ingest pipeline  processor

PUT _ingest/pipeline/attachment
{
  "description" : "Extract attachment information",
  "processors" : [
    {
      "attachment" : {
        "field" : "data"
      }
    }
  ]
}

Here "data" is your filed name where you want to store media files.

After this you can successfully insert the document into index. for ex .

PUT my_index/my_type/my_id?pipeline=attachment
{
  "data": "e1xydGYxXGFuc2kNCkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0DQpccGFyIH0="
}

The data field wants encoded Base64 String of media files.

So first you need to convert media files to byte array to Base64 encoded string.

Source is : Attachment in elasticsearch