问:
How do forward fill missing value imputation for a PySpark dataframe with single column?
I have a PySpark dataframe with single column.

| Rank
|----------
| 10
| 10
| null
| null
| 15
| null
| 20
| null
| null
| 15
| null
| 10
```

<p>I want to impute the missing values using forward fill like pandas ffill() function.</p>

<p><strong><em>Desired Output</em></strong></p>

<pre class="lang-none prettyprint-override"><code>| Rank
|----------
| 10
| 10
| 10
| 10
| 15
| 15
| 20
| 20
| 20
| 15
| 15
| 10
</code>```

Disclaimer: I have some some solutions in stackoverflow but they wont work when you only have a single column as input.

答:
Please check out the lag and lead functions in spark.

lag and lead are used to only for getting one offset. Simple creating udf with a global variable should do a trick
Below is simple example

```<code>var PRV_RANK = 0f

import spark.implicits._
val data = spark.sparkContext.parallelize(Seq(10f, 10f, Float.NaN, Float.NaN, 15f, Float.NaN, 20f, Float.NaN, Float.NaN, 15f, Float.NaN, 10f))
  .toDF("rank")

val forwardFill = udf((rank: Float) =>
{
  if (rank == null || rank.equals(Float.NaN)){
    PRV_RANK
  }
  else {
    PRV_RANK = rank
    rank
  }
})

data.withColumn("rankNew", forwardFill($"rank")).show()
</code>```

Hope this helps!

Body:
I have a PySpark dataframe with single column.

| Rank
|----------
| 10
| 10
| null
| null
| 15
| null
| 20
| null
| null
| 15
| null
| 10

I want to impute the missing values using forward fill like pandas ffill() function.

Desired Output

| Rank
|----------
| 10
| 10
| 10
| 10
| 15
| 15
| 20
| 20
| 20
| 15
| 15
| 10

Disclaimer: I have some some solutions in stackoverflow but they wont work when you only have a single column as input.

Body:
Please check out the lag and lead functions in spark.

lag and lead are used to only for getting one offset. Simple creating udf with a global variable should do a trick
Below is simple example

var PRV_RANK = 0f

import spark.implicits._
val data = spark.sparkContext.parallelize(Seq(10f, 10f, Float.NaN, Float.NaN, 15f, Float.NaN, 20f, Float.NaN, Float.NaN, 15f, Float.NaN, 10f))
  .toDF("rank")

val forwardFill = udf((rank: Float) =>
{
  if (rank == null || rank.equals(Float.NaN)){
    PRV_RANK
  }
  else {
    PRV_RANK = rank
    rank
  }
})

data.withColumn("rankNew", forwardFill($"rank")).show()

Hope this helps!


来源: stackexchange

问:
Linux shell equivalent on IIS
As a LAMP developer considering moving to a .Net IIS platform, one of my concerns is the loss of productivity due to lack of shell... Has anyone else had this experience?  Is there possibly a Linux shell equivalent for Windows?</p>

答:
Depending on what version of IIS you're considering, I would second lbrandy's recommendation to check out PowerShell. Microsoft is working on a PowerShell provider for IIS (specifically version 7). There is a decent post about this at http://blogs.iis.net/thomad/archive/2008/04/14/iis-7-0-powershell-provider-tech-preview-1.aspx. The upcoming version of PowerShell will also add remoting capabilities so that you can remotely manage machines. PowerShell is quite different from *NIX shells, though, so that is something to consider.

Hope this helps.

ContentLicense: CC BY-SA 2.5

Title: Linux shell equivalent on IIS

LastEditorDisplayName: Adam Mitz

OwnerDisplayName: David Mohundro


问:
I am not able retrieve firebase data in expendable listview
I want to retrieve data from firebase in expandableListView. In header, I want 4 value like table no, invoice no, date, bill amount. Help me to find out the solution
with searching using invoice no and date, when clicking on item expand the item and display item info.

```<code>public class MainActivity extends ActionBarActivity {
private static ExpandableListView expandableListView;
private static ExpandableListAdapter adapter;
private DatabaseReference mRef;
private FirebaseDatabase mFirebaseInstance;
BillModel bill;

 ArrayList<BillModel> billarry = new ArrayList<BillModel>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    expandableListView = (ExpandableListView) findViewById(R.id.simple_expandable_listview);
    mFirebaseInstance = FirebaseDatabase.getInstance();
    // Setting group indicator null for custom indicator
    expandableListView.setGroupIndicator(null);

    setItems();
    setListener();

}
 void setItems() {

    mRef = mFirebaseInstance.getReference();
    DatabaseReference queryrecord = mRef.child("bill");
    queryrecord.addValueEventListener(new ValueEventListener() {
        public void onDataChange(DataSnapshot snapshot) {
            billarry.clear();
            for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                bill = postSnapshot.getValue(BillModel.class);
               String bill_date = bill.getBill_date();
               String Bill_amount = bill.getBill_amount();
               String Bill_tableno = bill.getBill_tableno();
               String Incvoice_no = bill.getIncvoice_no();
                Log.d("result", "Bill---" + bill_date+","+Bill_amount+","+Bill_tableno+","+Incvoice_no);
                billarry.add(bill);
                // here you can access to name property like university.name

            }
        }
 @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });
 // Array list for header
    ArrayList<String> header = new ArrayList<String>();

    // Array list for child items
    List<String> child1 = new ArrayList<String>();
    List<String> child2 = new ArrayList<String>();
    List<String> child3 = new ArrayList<String>();
    List<String> child4 = new ArrayList<String>();

    // Hash map for both header and child
    HashMap<ArrayList<BillModel>, List<String>> hashMap = new HashMap<>();

    // Adding header and childs to hash map
    hashMap.put(billarry, child1);
Log.d("result", "HAsh-Bill---" +  hashMap.put(billarry,child1 ));

    hashMap.put(billmodel.get(1), child2);
    hashMap.put(billmodel.get(2), child3);
    hashMap.put(billmodel.get(3), child4);

    adapter = new ExpandableListAdapter(MainActivity.this, header, hashMap);

    // Setting adpater over expandablelistview
    expandableListView.setAdapter(adapter);
}
void setListener() {

    // This listener will show toast on group click
    expandableListView.setOnGroupClickListener(new OnGroupClickListener() {

        @Override
        public boolean onGroupClick(ExpandableListView listview, View view,
                                    int group_pos, long id) {

            Toast.makeText(MainActivity.this,
                    "You clicked : " + adapter.getGroup(group_pos),
                    Toast.LENGTH_SHORT).show();
            return false;
        }
    });
expandableListView
            .setOnGroupExpandListener(new OnGroupExpandListener() {

                // Default position
                int previousGroup = -1;

                @Override
                public void onGroupExpand(int groupPosition) {
                    if (groupPosition != previousGroup)

                        // Collapse the expanded group
                        expandableListView.collapseGroup(previousGroup);
                    previousGroup = groupPosition;
                }

            });
 // This listener will show toast on child click
    expandableListView.setOnChildClickListener(new OnChildClickListener() {

        @Override
        public boolean onChildClick(ExpandableListView listview, View view,
                                    int groupPos, int childPos, long id) {
            Toast.makeText(
                    MainActivity.this,
                    "You clicked : " + adapter.getChild(groupPos, childPos),
                    Toast.LENGTH_SHORT).show();
            return false;
        }
    });
}
</code>```

}

答:
Because of the asynchronously behaviour, you need to move the declaration of the billarry ArrayList inside the onDataChange() method.

```<code>ArrayList<BillModel> billarry = new ArrayList<BillModel>();
</code>```

So remember, onDataChange is always called asynchronously. This means that the statement that adds objects of BillModel class to the list is executed before onDataChange has been called. That's why your list is empty outside that method.

For other approach, please visit this post and this post.

Hope ot helps.

ContentLicense: CC BY-SA 3.0

Body:
I want to retrieve data from firebase in expandableListView. In header, I want 4 value like table no, invoice no, date, bill amount. Help me to find out the solution
with searching using invoice no and date, when clicking on item expand the item and display item info.

public class MainActivity extends ActionBarActivity {
private static ExpandableListView expandableListView;
private static ExpandableListAdapter adapter;
private DatabaseReference mRef;
private FirebaseDatabase mFirebaseInstance;
BillModel bill;

 ArrayList<BillModel> billarry = new ArrayList<BillModel>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    expandableListView = (ExpandableListView) findViewById(R.id.simple_expandable_listview);
    mFirebaseInstance = FirebaseDatabase.getInstance();
    // Setting group indicator null for custom indicator
    expandableListView.setGroupIndicator(null);

    setItems();
    setListener();

}
 void setItems() {

    mRef = mFirebaseInstance.getReference();
    DatabaseReference queryrecord = mRef.child("bill");
    queryrecord.addValueEventListener(new ValueEventListener() {
        public void onDataChange(DataSnapshot snapshot) {
            billarry.clear();
            for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                bill = postSnapshot.getValue(BillModel.class);
               String bill_date = bill.getBill_date();
               String Bill_amount = bill.getBill_amount();
               String Bill_tableno = bill.getBill_tableno();
               String Incvoice_no = bill.getIncvoice_no();
                Log.d("result", "Bill---" + bill_date+","+Bill_amount+","+Bill_tableno+","+Incvoice_no);
                billarry.add(bill);
                // here you can access to name property like university.name

            }
        }
 @Override
        public void onCancelled(DatabaseError databaseError) {

        }

    });
 // Array list for header
    ArrayList<String> header = new ArrayList<String>();

    // Array list for child items
    List<String> child1 = new ArrayList<String>();
    List<String> child2 = new ArrayList<String>();
    List<String> child3 = new ArrayList<String>();
    List<String> child4 = new ArrayList<String>();

    // Hash map for both header and child
    HashMap<ArrayList<BillModel>, List<String>> hashMap = new HashMap<>();

    // Adding header and childs to hash map
    hashMap.put(billarry, child1);
Log.d("result", "HAsh-Bill---" +  hashMap.put(billarry,child1 ));

    hashMap.put(billmodel.get(1), child2);
    hashMap.put(billmodel.get(2), child3);
    hashMap.put(billmodel.get(3), child4);

    adapter = new ExpandableListAdapter(MainActivity.this, header, hashMap);

    // Setting adpater over expandablelistview
    expandableListView.setAdapter(adapter);
}
void setListener() {

    // This listener will show toast on group click
    expandableListView.setOnGroupClickListener(new OnGroupClickListener() {

        @Override
        public boolean onGroupClick(ExpandableListView listview, View view,
                                    int group_pos, long id) {

            Toast.makeText(MainActivity.this,
                    "You clicked : " + adapter.getGroup(group_pos),
                    Toast.LENGTH_SHORT).show();
            return false;
        }
    });
expandableListView
            .setOnGroupExpandListener(new OnGroupExpandListener() {

                // Default position
                int previousGroup = -1;

                @Override
                public void onGroupExpand(int groupPosition) {
                    if (groupPosition != previousGroup)

                        // Collapse the expanded group
                        expandableListView.collapseGroup(previousGroup);
                    previousGroup = groupPosition;
                }

            });
 // This listener will show toast on child click
    expandableListView.setOnChildClickListener(new OnChildClickListener() {

        @Override
        public boolean onChildClick(ExpandableListView listview, View view,
                                    int groupPos, int childPos, long id) {
            Toast.makeText(
                    MainActivity.this,
                    "You clicked : " + adapter.getChild(groupPos, childPos),
                    Toast.LENGTH_SHORT).show();
            return false;
        }
    });
}

}

Body:
Because of the asynchronously behaviour, you need to move the declaration of the billarry ArrayList inside the onDataChange() method.

ArrayList<BillModel> billarry = new ArrayList<BillModel>();

So remember, onDataChange is always called asynchronously. This means that the statement that adds objects of BillModel class to the list is executed before onDataChange has been called. That's why your list is empty outside that method.

For other approach, please visit this post and this post.

Hope ot helps.


问:
Nothing happens when I click submit on Mailchimp Opt in Form
I am trying to add an opt-in Mailchimp form in my blogger website
heres my blog :
https://ahoycollege.blogspot.com/
   This is the code I added to my posts

```<code>     <hr />
    <!-- Begin MailChimp Signup Form --> <link href="https://fonts.googleapis.com/css?family=Lily+Script+One" rel="stylesheet">
</link><link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet"></link>
<br />
<center>
<div id="mailchimp">
<form action="http://blogspot.us15.list-manage.com/subscribe/post u=68ae6aa50c0574fa1460be555&id=cf51777197" class="validate" id="mc-embedded subscribe-form" method="post" name="mc-embedded-subscribe-form" novalidate="" target="_blank">
<div id="mc_embed_signup_scroll">
<span data-redactor-style="font-family: 'Lily Script One', cursive; " style="color: #57627c; font-family: "lily script one" , cursive; font size: 25px;"> Join the Fun!</span></div>
</form>
<span style="color: #c32b40; font-family: "quicksand" , sans serif;"> <span c92a3e="" e=""> Get Access to the AC Resource Library with just one click!</span></span>
</div>
<br />
<input class="" id="mce-FNAME" name="FNAME" onblur="if(this.value=='')this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue)this.value='';" size="30" type="text" value="*Your First Name" /><br />
<br />
<input class="required email" id="mce-EMAIL" name="EMAIL" onblur="if(this.value=='')this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue)this.value='';" size="30" type="email" value="*Email Address" /><br />
<br />
<input class="" id="mce-FBID" name="FBID" onblur="if(this.value=='')this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue)this.value='';" size="30" type="text" value="Facebook ID URL" />
  <br />
 <div class="clear" id="mce-responses">
<div class="response" id="mce-error-response" style="display: none;">
</div>
<div class="response" id="mce-success-response" style="display: none;">
</div>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<br />
<div aria-hidden="true" style="left: -5000px; position: absolute;">
<input name="b_68ae6aa50c0574fa1460be555_cf51777197" tabindex="-1" type="text" value="" /></div>
<input class="button" id="mc-embedded-subscribe" name="subscribe" type="submit" value="Count me In!" /></center>
<!--End mc_embed_signup-->
</code>```

And this was the CSS styling I used :

```<code>  #mc_embed_signup_scroll h2 {
font-size: 15px;
margin-bottom: 20px;
text-transform: uppercase;
letter-spacing: 2px;
text-align: center;

 }
.mc-field-group {
margin-bottom: 8px;
}
input#mce-FNAME, input#mce-EMAIL, input#mce-FBID {
border: 1px solid #7ACCCD;

padding: 12px;
font-size: 14px;
 }
#mc-embedded-subscribe {
background: #C8E8E8;
width: 21%;
font-size: 15px;
letter-spacing: 2px;
margin-top: 8px;
border-radius: 20px;
-moz-border-radius: 20px;
-webkit-border-radius: 20px;
}
#mc-embedded-subscribe:hover {
opacity:0.7;
color : #B53240
}
#mc_embed_signup {
background: #C8E8E8;
padding: 30px;
}
</code>```

When I click submit, nothing really happens at all.

Please let me know if there are any errors in the code that I should fix.
I used the Naked form of the opt in in mailchimp and customised it.

答:
this is because wrong pattern of html, form tag must be close after all the input tag.

Form tag action needs to take care of.

```<code><form action="http://blogspot.us15.list-manage.com/subscribe/post u=68ae6aa50c0574fa1460be555&id=cf51777197" class="validate" id="mc-embedded subscribe-form" method="post" name="mc-embedded-subscribe-form" novalidate="" target="_blank">
   <div id="mc_embed_signup_scroll">
     <span data-redactor-style="font-family: 'Lily Script One', cursive; " style="color: #57627c; font-family: "lily script one" , cursive; font size: 25px;"> Join the Fun!</span></div>

..
..
..
..
</form> <!-- form tag close here -->
</center><!--End mc_embed_signup-->
</code>```

Hope this will help.

Body:
I am trying to add an opt-in Mailchimp form in my blogger website
heres my blog :
https://ahoycollege.blogspot.com/
   This is the code I added to my posts

     <link href="https://fonts.googleapis.com/css?family=Lily+Script+One" rel="stylesheet">
</link><link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet"></link>

<form action="http://blogspot.us15.list-manage.com/subscribe/post u=68ae6aa50c0574fa1460be555&id=cf51777197" class="validate" id="mc-embedded subscribe-form" method="post" name="mc-embedded-subscribe-form" novalidate="" target="_blank">

 Join the Fun!

</form>
  Get Access to the AC Resource Library with just one click!

<input class="" id="mce-FNAME" name="FNAME" onblur="if(this.value=='')this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue)this.value='';" size="30" type="text" value="*Your First Name" />

<input class="required email" id="mce-EMAIL" name="EMAIL" onblur="if(this.value=='')this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue)this.value='';" size="30" type="email" value="*Email Address" />

<input class="" id="mce-FBID" name="FBID" onblur="if(this.value=='')this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue)this.value='';" size="30" type="text" value="Facebook ID URL" />

<input name="b_68ae6aa50c0574fa1460be555_cf51777197" tabindex="-1" type="text" value="" />

<input class="button" id="mc-embedded-subscribe" name="subscribe" type="submit" value="Count me In!" />

And this was the CSS styling I used :

  #mc_embed_signup_scroll h2 {
font-size: 15px;
margin-bottom: 20px;
text-transform: uppercase;
letter-spacing: 2px;
text-align: center;

 }
.mc-field-group {
margin-bottom: 8px;
}
input#mce-FNAME, input#mce-EMAIL, input#mce-FBID {
border: 1px solid #7ACCCD;

padding: 12px;
font-size: 14px;
 }
#mc-embedded-subscribe {
background: #C8E8E8;
width: 21%;
font-size: 15px;
letter-spacing: 2px;
margin-top: 8px;
border-radius: 20px;
-moz-border-radius: 20px;
-webkit-border-radius: 20px;
}
#mc-embedded-subscribe:hover {
opacity:0.7;
color : #B53240
}
#mc_embed_signup {
background: #C8E8E8;
padding: 30px;
}

When I click submit, nothing really happens at all.

Please let me know if there are any errors in the code that I should fix.
I used the Naked form of the opt in in mailchimp and customised it.

Body:
this is because wrong pattern of html, form tag must be close after all the input tag.

Form tag action needs to take care of.

<form action="http://blogspot.us15.list-manage.com/subscribe/post u=68ae6aa50c0574fa1460be555&amp;id=cf51777197" class="validate" id="mc-embedded subscribe-form" method="post" name="mc-embedded-subscribe-form" novalidate="" target="_blank">
   <div id="mc_embed_signup_scroll">
     <span data-redactor-style="font-family: 'Lily Script One', cursive; " style="color: #57627c; font-family: &quot;lily script one&quot; , cursive; font size: 25px;"> Join the Fun!</span></div>

..
..
..
..
</form> <!-- form tag close here -->
</center><!--End mc_embed_signup-->

Hope this will help.


问:
How to get the Title of inner frame in selenium webdriver?
In my program, I am trying to get the Title of the inner frame by switching the driver control to inner frame with the help of getTitle() method. But,it is still return the title of main page.
please find the below bit of code I tried with

```<code>WebDriver driver = new FirefoxDriver();
driver.get("url");
driver.switchTo().frame("frame name/id");
driver.getTitle();
</code>```

Is there any way to get the Title of the inner frame in selenium webdriver using Java.

答:
Use Below code to achieve the same

```<code>// before switching frame

driver.getTitle();
//or

driver.find_element_by_tag_name("title").get_attribute("innerHTML")
</code>```

and after switching frame

```<code>driver.switchTo().frame("frame name/id");
driver.find_element_by_tag_name("title").get_attribute("innerHTML")
</code>```

Hope This will help as I'm able to do the same using this code

Body:
In my program, I am trying to get the Title of the inner frame by switching the driver control to inner frame with the help of getTitle() method. But,it is still return the title of main page.
please find the below bit of code I tried with

WebDriver driver = new FirefoxDriver();
driver.get("url");
driver.switchTo().frame("frame name/id");
driver.getTitle();

Is there any way to get the Title of the inner frame in selenium webdriver using Java.

Body:
Use Below code to achieve the same

// before switching frame

driver.getTitle();
//or

driver.find_element_by_tag_name("title").get_attribute("innerHTML")

and after switching frame

driver.switchTo().frame("frame name/id");
driver.find_element_by_tag_name("title").get_attribute("innerHTML")

Hope This will help as I'm able to do the same using this code


问:
Google Maps JS API Suggestion AutocompletionService does not returns the same address all the time
The Google Maps API Suggestion does not return the same address all the time. We have a probe that runs every 10 minutes, and about 8 times per days the PlaceService.GetPlaceDetails does not return the same address.

Here are the HTTP calls :

Most of the time :

```<code>GET https://maps.googleapis.com/maps/api/place/js/AutocompletionService.GetPredictions?1s169%20Avenue%20Boll%C3%A9e%2C%20Le%20Mans%2C%20France&4sfr-FR&7scountry%3Afr&15e3&client=*******&callback=_xdc_._ca6qq&token=18520 HTTP/1.1
HTTP/1.1 200 OK ../.. ["169 Avenue Bollée, Le Mans, France", ../..
</code>```

then the Google JS API calls:

```<code>GET https://maps.googleapis.com/maps/api/place/js/PlaceService.GetPlaceDetails
HTTP/1.1 200 OK
../..
     {
        "long_name" : "169",
        "short_name" : "169",
        "types" : [ "street_number" ]
     },
</code>```

And about 8 times per day :

the same request

```<code>GET https://maps.googleapis.com/maps/api/place/js/AutocompletionService.GetPredictions?1s169%20Avenue%20Boll%C3%A9e%2C%20Le%20Mans%2C%20France&4sfr-FR&7scountry%3Afr&15e3&client=******&callback=_xdc_._ca6qq&token=123244 HTTP/1.1
HTTP/1.1 200 OK ../.. ["169 Avenue Bollée, Le Mans, France", ../..
</code>```

but the GetPlaceDetails returns another street number (notice the "181-167" instead of "169")

```<code>GET https://maps.googleapis.com/maps/api/place/js/PlaceService.GetPlaceDetails?2sfr-FR&8sEiMxNjkgQXZlbnVlIEJvbGzDqWUsIExlIE1hbnMsIEZyYW5jZQ&10e3&client=gme-giecovea1&callback=_xdc_._8rimfj&token=108576 HTTP/1.1
HTTP/1.1 200 OK
../..
         {
            "long_name" : "181-167",
            "short_name" : "181-167",
            "types" : [ "street_number" ]
         },
</code>```

Does anyone know how it can be possible ? I don't see any other HTTP call between these one. It causes me error in the probe process because it cannot find the corresponding client of the address in 181-167.

答:
Answer from Google Map Premium (translated from French) :

The Places database changes all the time due to the interactions with the Google Services, in order to improve continiously the results. In your case the location is the same (same coords) but the address binded to this location slighty differs. Google results won't be changed. You should either:

change your code to accept street number range

or use the adresse selected by the user

Actually, as the result switches from a accurate adress to a street numbers range, I think it is due to a bad cluster sync as @xomena stated it.

Secondly, we noticed that this "random" address was a building address and in a way Google is right to said that this address cannot be always accurate : as you can see on Street View

We decided to choose another test address with less risk of low accurate suggestion.

Body:
The Google Maps API Suggestion does not return the same address all the time. We have a probe that runs every 10 minutes, and about 8 times per days the PlaceService.GetPlaceDetails does not return the same address.

Here are the HTTP calls :

Most of the time :

GET https://maps.googleapis.com/maps/api/place/js/AutocompletionService.GetPredictions?1s169%20Avenue%20Boll%C3%A9e%2C%20Le%20Mans%2C%20France&4sfr-FR&7scountry%3Afr&15e3&client=*******&callback=_xdc_._ca6qq&token=18520 HTTP/1.1
HTTP/1.1 200 OK ../.. ["169 Avenue Bollée, Le Mans, France", ../..

then the Google JS API calls:

GET https://maps.googleapis.com/maps/api/place/js/PlaceService.GetPlaceDetails
HTTP/1.1 200 OK
../..
     {
        "long_name" : "169",
        "short_name" : "169",
        "types" : [ "street_number" ]
     },

And about 8 times per day :

the same request

GET https://maps.googleapis.com/maps/api/place/js/AutocompletionService.GetPredictions?1s169%20Avenue%20Boll%C3%A9e%2C%20Le%20Mans%2C%20France&4sfr-FR&7scountry%3Afr&15e3&client=******&callback=_xdc_._ca6qq&token=123244 HTTP/1.1
HTTP/1.1 200 OK ../.. ["169 Avenue Bollée, Le Mans, France", ../..

but the GetPlaceDetails returns another street number (notice the "181-167" instead of "169")

GET https://maps.googleapis.com/maps/api/place/js/PlaceService.GetPlaceDetails?2sfr-FR&8sEiMxNjkgQXZlbnVlIEJvbGzDqWUsIExlIE1hbnMsIEZyYW5jZQ&10e3&client=gme-giecovea1&callback=_xdc_._8rimfj&token=108576 HTTP/1.1
HTTP/1.1 200 OK
../..
         {
            "long_name" : "181-167",
            "short_name" : "181-167",
            "types" : [ "street_number" ]
         },

Does anyone know how it can be possible ? I don't see any other HTTP call between these one. It causes me error in the probe process because it cannot find the corresponding client of the address in 181-167.


问:
Android open new activity when click link from textview(autolink)
I have a view display textview and enable autolink.

```<code><TextView
   android:id="@+id/txt_contents"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="30dp"
   android:textColor="@color/txt_code_itemlist"
   android:autoLink="web"
   android:textSize="22sp" />
</code>```

Now, when I click link from textview it's will open browser. But I want to find way to open new activity when I click same link.

答:
You can use Linkify in TextView,

```<code>    TextView sample = (TextView) findViewById(R.id.txt_contents);

    String webUrlOrText = "www.google.com a search Engine";
    Spannable spannableString = new SpannableString(Html.fromHtml(webUrlOrText));

    Linkify.addLinks(spannableString, Linkify.WEB_URLS); // It will make only Weblink clickable

    URLSpan[] urlSpans = spannableString.getSpans(0, spannableString.length(), URLSpan.class);
    for (URLSpan urlSpan : urlSpans) {
        LinkSpan linkSpan = new LinkSpan(urlSpan.getURL());
        int spanStart = spannableString.getSpanStart(urlSpan);
        int spanEnd = spannableString.getSpanEnd(urlSpan);
        spannableString.setSpan(linkSpan, spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.removeSpan(urlSpan);
    }

    sample.setText(spannableString);
    sample.setMovementMethod(LinkMovementMethod.getInstance());
</code>```

And LinkSpan class,

```<code>private class LinkSpan extends URLSpan {
    private LinkSpan(String url) {
        super(url);
    }

    @Override
    public void onClick(View view) {
        String url = getURL();

        if (url != null) {
           // Open the Activity here
           Log.d(TAG, "Url clicked");
        }
    }
}
</code>```

Body:
I have a view display textview and enable autolink.

<TextView
   android:id="@+id/txt_contents"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="30dp"
   android:textColor="@color/txt_code_itemlist"
   android:autoLink="web"
   android:textSize="22sp" />

Now, when I click link from textview it's will open browser. But I want to find way to open new activity when I click same link.

Body:
You can use Linkify in TextView,

    TextView sample = (TextView) findViewById(R.id.txt_contents);

    String webUrlOrText = "www.google.com a search Engine";
    Spannable spannableString = new SpannableString(Html.fromHtml(webUrlOrText));

    Linkify.addLinks(spannableString, Linkify.WEB_URLS); // It will make only Weblink clickable

    URLSpan[] urlSpans = spannableString.getSpans(0, spannableString.length(), URLSpan.class);
    for (URLSpan urlSpan : urlSpans) {
        LinkSpan linkSpan = new LinkSpan(urlSpan.getURL());
        int spanStart = spannableString.getSpanStart(urlSpan);
        int spanEnd = spannableString.getSpanEnd(urlSpan);
        spannableString.setSpan(linkSpan, spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.removeSpan(urlSpan);
    }

    sample.setText(spannableString);
    sample.setMovementMethod(LinkMovementMethod.getInstance());

And LinkSpan class,

private class LinkSpan extends URLSpan {
    private LinkSpan(String url) {
        super(url);
    }

    @Override
    public void onClick(View view) {
        String url = getURL();

        if (url != null) {
           // Open the Activity here
           Log.d(TAG, "Url clicked");
        }
    }
}


问:
What indexes are needed for the following scenario
I have a single table holding stock of single-use voucher codes. Each row is a separate code. For simplicity the table looks like this:

```<code>| id (AUTO_INCREMENTING) | owner (VARCHAR) | brand (VARCHAR) | currency (CHAR) | value (INTEGER) | activated_at (TIMESTAMP) | expires_at (DATE) |
|------------------------|-----------------|-----------------|-----------------|-----------------|--------------------------|-------------------|
| 1                      | first-owner     | brand-one       | gbp             | 10              | NULL                     | 2018-06-06        |
| 2                      | second-owner    | brand-one       | gbp             | 15              | NULL                     | 2018-06-06        |
| 3                      | second-owner    | brand-one       | gbp             | 15              | NULL                     | 2018-06-06        |
</code>```

I know I can normalise the table and extract all the fields into their own tables and have the stock table just contain the ids, however so far that hasn't proven to give a performance gain, and, for the sake of simplicity and user readability I am inclined to leave it as is.

When querying this table, I want to be able to optionally pass the owner, the brand, or both.

What indexes do I need on this table for the following queries and why?

Querying the table without supplying an owner or brand:

```<code>SELECT
    `owner`,
    `brand`,
    `currency`,
    `value`,
    count(*) AS 'quantity_of_codes',
    (count(*) * `value`) AS 'total_face_value'
FROM `inventory`
WHERE `activated_at` IS NULL
AND `expires_at` >= '2018-06-05'
GROUP BY `owner`, `brand`, `currency`, `value`
</code>```

If I run explain I can see that the index is used:

```<code>| select_type | table     | type | possible_keys | key | key_len | ref   | rows   | Extra                                                     |
|-------------|-----------|------|---------------|-----|---------|-------|--------|-----------------------------------------------------------|
| SIMPLE      | inventory | ref  |               |     | 766     | const | 416144 | Using where; Using index; Using temporary; Using filesort |
</code>```

When I supply an owner the index is used but it creates a temporary table and uses filesort which I believe isn't good.

```<code>SELECT
    `brand`,
    `owner`,
    `currency`,
    `value`,
    count(*) AS 'quantity_of_codes',
    (count(*) * `value`) AS 'total_face_value'
FROM `inventory`
WHERE `owner` = 'first-owner'
AND `activated_at` IS NULL
AND `expires_at` >= '2017-06-06'
GROUP BY `brand`, `owner`, `currency`, `value`
</code>```

Running explain shows:

```<code>| select_type | table     | type  | possible_keys                                            | key                                                      | key_len | ref | rows | Extra                                                     |
|-------------|-----------|-------|----------------------------------------------------------|----------------------------------------------------------|---------|-----|------|-----------------------------------------------------------|
| SIMPLE      | inventory | index | brand_owner_currency_value_activated_at_expires_at_index | brand_owner_currency_value_activated_at_expires_at_index | 2310    |     | 87   | Using where; Using index; Using temporary; Using filesort |
</code>```

When I also provide a brand I get:

```<code>SELECT
    `brand`,
    `owner`,
    `currency`,
    `value`,
    count(*) AS 'quantity_of_codes',
    (count(*) * `value`) AS 'total_face_value'
FROM `inventory`
WHERE `owner` = 'first-owner'
AND `brand` = 'brand-one'
AND `activated_at` IS NULL
AND `expires_at` >= '2018-06-05'
GROUP BY `brand`, `owner`, `currency`, `value`
</code>```

Lastly, when I run explain I get:

```<code>| select_type | table     | type | possible_keys                                            | key                                                      | key_len | ref | rows | Extra                                                     |
|-------------|-----------|------|----------------------------------------------------------|----------------------------------------------------------|---------|-----|------|-----------------------------------------------------------|
| SIMPLE      | inventory | ref  | brand_owner_currency_value_activated_at_expires_at_index | brand_owner_currency_value_activated_at_expires_at_index | 1532    |     | 1    | Using where; Using index; Using temporary; Using filesort |
</code>```

As mentioned, I have an index across the brand, owner, currency, value, activated_at, and expires_at fields although this isn't used when I don't include brand in the where part of the query.

答:
http://use-the-index-luke.com/ is a fine reference for getting the chops to design your indexes skilfully.

You're on the right track by choosing a compound index for this kind of query. Your query has these WHERE-clause items.

```<code> WHERE `owner` = 'an-owner'
   AND `activated_at` IS NULL
   AND `expires_at` >= '2017-06-06'
</code>```

You're looking for equality on the first item, IS NULL on the second one, and a range scan on the third.  So, an index on (owner, activated_at, expires_at) can allow the query planner to jump to the correct row and then scan the index for consecutive rows. An index on (activated_at, owner, expires_at) will also work.

Your index, on ( brand, owner, currency, value, _activated_at, _expires_at) can't be range scanned for the query you showed. So the query planner ignores it.

Pro tip: Don't create indexes for tables just because they seem like they might be useful. Design them to speed up the queries you need sped up.

Pro tip #2: Using temporary; Using filesort is not a sure sign of poor performance. temporary means that some result set needs to be put into an ephemeral table-like data structure in the server. filesort means that result set needs sorting before delivery. When you use GROUP BY the query planner often needs a temporary structure to fulfill your query. Read this.  https://www.percona.com/blog/2009/03/05/what-does-using-filesort-mean-in-mysql/

Your EXPLAIN output looks pretty darn good to me. One row? Great,

Body:
I have a single table holding stock of single-use voucher codes. Each row is a separate code. For simplicity the table looks like this:

| id (AUTO_INCREMENTING) | owner (VARCHAR) | brand (VARCHAR) | currency (CHAR) | value (INTEGER) | activated_at (TIMESTAMP) | expires_at (DATE) |
|------------------------|-----------------|-----------------|-----------------|-----------------|--------------------------|-------------------|
| 1                      | first-owner     | brand-one       | gbp             | 10              | NULL                     | 2018-06-06        |
| 2                      | second-owner    | brand-one       | gbp             | 15              | NULL                     | 2018-06-06        |
| 3                      | second-owner    | brand-one       | gbp             | 15              | NULL                     | 2018-06-06        |

I know I can normalise the table and extract all the fields into their own tables and have the stock table just contain the ids, however so far that hasn't proven to give a performance gain, and, for the sake of simplicity and user readability I am inclined to leave it as is.

When querying this table, I want to be able to optionally pass the owner, the brand, or both.

What indexes do I need on this table for the following queries and why?

Querying the table without supplying an owner or brand:

SELECT
    `owner`,
    `brand`,
    `currency`,
    `value`,
    count(*) AS 'quantity_of_codes',
    (count(*) * `value`) AS 'total_face_value'
FROM `inventory`
WHERE `activated_at` IS NULL
AND `expires_at` >= '2018-06-05'
GROUP BY `owner`, `brand`, `currency`, `value`

If I run explain I can see that the index is used:

| select_type | table     | type | possible_keys | key | key_len | ref   | rows   | Extra                                                     |
|-------------|-----------|------|---------------|-----|---------|-------|--------|-----------------------------------------------------------|
| SIMPLE      | inventory | ref  |               |     | 766     | const | 416144 | Using where; Using index; Using temporary; Using filesort |

When I supply an owner the index is used but it creates a temporary table and uses filesort which I believe isn't good.

SELECT
    `brand`,
    `owner`,
    `currency`,
    `value`,
    count(*) AS 'quantity_of_codes',
    (count(*) * `value`) AS 'total_face_value'
FROM `inventory`
WHERE `owner` = 'first-owner'
AND `activated_at` IS NULL
AND `expires_at` >= '2017-06-06'
GROUP BY `brand`, `owner`, `currency`, `value`

Running explain shows:

| select_type | table     | type  | possible_keys                                            | key                                                      | key_len | ref | rows | Extra                                                     |
|-------------|-----------|-------|----------------------------------------------------------|----------------------------------------------------------|---------|-----|------|-----------------------------------------------------------|
| SIMPLE      | inventory | index | brand_owner_currency_value_activated_at_expires_at_index | brand_owner_currency_value_activated_at_expires_at_index | 2310    |     | 87   | Using where; Using index; Using temporary; Using filesort |

When I also provide a brand I get:

SELECT
    `brand`,
    `owner`,
    `currency`,
    `value`,
    count(*) AS 'quantity_of_codes',
    (count(*) * `value`) AS 'total_face_value'
FROM `inventory`
WHERE `owner` = 'first-owner'
AND `brand` = 'brand-one'
AND `activated_at` IS NULL
AND `expires_at` >= '2018-06-05'
GROUP BY `brand`, `owner`, `currency`, `value`

Lastly, when I run explain I get:

| select_type | table     | type | possible_keys                                            | key                                                      | key_len | ref | rows | Extra                                                     |
|-------------|-----------|------|----------------------------------------------------------|----------------------------------------------------------|---------|-----|------|-----------------------------------------------------------|
| SIMPLE      | inventory | ref  | brand_owner_currency_value_activated_at_expires_at_index | brand_owner_currency_value_activated_at_expires_at_index | 1532    |     | 1    | Using where; Using index; Using temporary; Using filesort |

As mentioned, I have an index across the brand, owner, currency, value, activated_at, and expires_at fields although this isn't used when I don't include brand in the where part of the query.

Body:
http://use-the-index-luke.com/ is a fine reference for getting the chops to design your indexes skilfully.

You're on the right track by choosing a compound index for this kind of query. Your query has these WHERE-clause items.

 WHERE `owner` = 'an-owner'
   AND `activated_at` IS NULL
   AND `expires_at` >= '2017-06-06'

You're looking for equality on the first item, IS NULL on the second one, and a range scan on the third.  So, an index on (owner, activated_at, expires_at) can allow the query planner to jump to the correct row and then scan the index for consecutive rows. An index on (activated_at, owner, expires_at) will also work.

Your index, on ( brand, owner, currency, value, _activated_at, _expires_at) can't be range scanned for the query you showed. So the query planner ignores it.

Pro tip: Don't create indexes for tables just because they seem like they might be useful. Design them to speed up the queries you need sped up.

Pro tip #2: Using temporary; Using filesort is not a sure sign of poor performance. temporary means that some result set needs to be put into an ephemeral table-like data structure in the server. filesort means that result set needs sorting before delivery. When you use GROUP BY the query planner often needs a temporary structure to fulfill your query. Read this.  https://www.percona.com/blog/2009/03/05/what-does-using-filesort-mean-in-mysql/

Your EXPLAIN output looks pretty darn good to me. One row? Great,


问:
string split using regex PHP
My string is "30OKOKOKOKOKOKOKOK30OKOKOKOKOKOKOKOKOKOKOKOKOKOK120"
i want to split it in digits and 'OK' string, my expected output is

```<code>array(0=>30,1=>OK,2=>OK,......,n=>120)
</code>```

currently i am using this

```<code>preg_match_all('!\d+!', $str, $matches);
</code>```

but it only returns me digits i.e. 30,30,120
please help me to get above expected output

答:
Starting from least efficient down to most efficient patterns, given your input sample:

/\d+|OK/         (96 steps)    <-- Shammel's pattern

/OK|\d+/         (77 steps)    #faster alternative first

/\d+|[^\d]{2}    (74 steps)    #make OK delimiter non-literal

/[^\d]{2}|\d+/   (55 steps)    #faster alternative first

I'd say use the 55 steps one.

```<code>$in = '30OKOKOKOKOKOKOKOK30OKOKOKOKOKOKOKOKOKOKOKOKOKOK120';
var_export(preg_match_all('/[^\d]{2}|\d+/', $in, $out) ? $out[0] : []);
</code>```

Note, preg_match_all() creates a multi-dim array.

Another option is to use preg_split().  By using a couple of flags in its fourth parameter, the same result can be achieve with an amazingly brief pattern with minimal efficiency loss compared to my best pattern above.

```<code>var_export(preg_split('/(OK)/', $in, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE));
// or /([^\d]{2})/
</code>```

This method returns a 1-dim array (not a true/false with a variable to reference) with a four-character pattern in 110 steps (or 104 with non-literal OK delimiting) .  So for this case preg_match_all() is twice as fast.

Title: string split using regex PHP

Body:
My string is "30OKOKOKOKOKOKOKOK30OKOKOKOKOKOKOKOKOKOKOKOKOKOK120"
i want to split it in digits and 'OK' string, my expected output is

array(0=>30,1=>OK,2=>OK,......,n=>120)

currently i am using this

preg_match_all('!\d+!', $str, $matches);

but it only returns me digits i.e. 30,30,120
please help me to get above expected output

Body:
Starting from least efficient down to most efficient patterns, given your input sample:

/\d+|OK/         (96 steps)    <-- Shammel's pattern

/OK|\d+/         (77 steps)    #faster alternative first

/\d+|[^\d]{2}    (74 steps)    #make OK delimiter non-literal

/[^\d]{2}|\d+/   (55 steps)    #faster alternative first

I'd say use the 55 steps one.

$in = '30OKOKOKOKOKOKOKOK30OKOKOKOKOKOKOKOKOKOKOKOKOKOK120';
var_export(preg_match_all('/[^\d]{2}|\d+/', $in, $out) ? $out[0] : []);

Note, preg_match_all() creates a multi-dim array.

Another option is to use preg_split().  By using a couple of flags in its fourth parameter, the same result can be achieve with an amazingly brief pattern with minimal efficiency loss compared to my best pattern above.

var_export(preg_split('/(OK)/', $in, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE));
// or /([^\d]{2})/

This method returns a 1-dim array (not a true/false with a variable to reference) with a four-character pattern in 110 steps (or 104 with non-literal OK delimiting) .  So for this case preg_match_all() is twice as fast.

ContentLicense: CC BY-SA 4.0


问:
Why can't I move an element into vector of non-copyables?
The compiler tells me I'm trying to access a deleted function (i.e. the copy constructor of a lambda expression).  But I don't see where.

```<code>std::vector<std::function<void()>> tasks;
std::packaged_task<int()> task{ [] { return 1; } };
tasks.emplace_back(
    [ t = std::move(task) ] () mutable { t(); });
</code>```

(code is also here)

(I'm trying to find out why they use shared_ptr<task> in https://www.slideshare.net/GlobalLogicUkraine/c11-multithreading-futures).

On Gcc and MSVC I get the same error - I fear I'm doing something wrong...

```<code>error: use of deleted function
'main()::<lambda()>::<lambda>(const main()::<lambda()>&)'
</code>```

Why can't I emplace this std::function onto the vector?

答:
The constructor of std::function requires the passed function object to be CopyConstructible, but std::packaged_task<F> is not (for any F). std::function performs type erasure where the dynamic type is not visible in the static type. Consider e.g.:

```<code>int invoke(std::function<int()> f) { return f(); }

int main()
{
    std::packaged_task<int()> p{/*etc*/};
    auto l = [] { return 5; };
    std::function<int()> f( /* either p or l */ );
    std::cout << invoke(f) << '\n';
}
</code>```

The call to invoke requires copying f (pass by value). However, f is copyable if it has been made from l, but not copyable if it has been made from p, and this has nothing to do with the static type of f. There are basically three approaches to this problem:

Forbid copying of std::function at compile time.

Allow copying std::function at compile time, but throw a run time error if the contained type is not copyable.

Allow copying std::function at compile time, and require any function object that you put into it to be copyable.

Approach #1 is very restrictive on how functions may be stored, passed and shared, and basically forbids common use cases in favor of the uncommon case of using a non-copyable function object.

Approach #2 is problematic because users would need to be educated that copying a std::function may fail in some cases and use great diligence when writing their code. Also, if the design requires sharing functions they may need to be wrapped in a std::shared_ptr. And if they need to be copied and may be stateful, it becomes even worse.

No matter how you view approach #3, it is the one that was standardized. But in light of the above-mentioned problems, it is also easily to defend.

As a matter of fact, I have written a unique_function class template that uses approach #1 for my current project because for us the use case of storing non-copyable asynchronous task objects is quite common, and copying or sharing such a task isn't necessary.

Body:
The compiler tells me I'm trying to access a deleted function (i.e. the copy constructor of a lambda expression).  But I don't see where.

std::vector<std::function<void()>> tasks;
std::packaged_task<int()> task{ [] { return 1; } };
tasks.emplace_back(
    [ t = std::move(task) ] () mutable { t(); });

(code is also here)

(I'm trying to find out why they use shared_ptr<task> in https://www.slideshare.net/GlobalLogicUkraine/c11-multithreading-futures).

On Gcc and MSVC I get the same error - I fear I'm doing something wrong...

error: use of deleted function
'main()::<lambda()>::<lambda>(const main()::<lambda()>&)'

Why can't I emplace this std::function onto the vector?

Body:
The constructor of std::function requires the passed function object to be CopyConstructible, but std::packaged_task<F> is not (for any F). std::function performs type erasure where the dynamic type is not visible in the static type. Consider e.g.:

int invoke(std::function<int()> f) { return f(); }

int main()
{
    std::packaged_task<int()> p{/*etc*/};
    auto l = [] { return 5; };
    std::function<int()> f( /* either p or l */ );
    std::cout << invoke(f) << '\n';
}

The call to invoke requires copying f (pass by value). However, f is copyable if it has been made from l, but not copyable if it has been made from p, and this has nothing to do with the static type of f. There are basically three approaches to this problem:

Forbid copying of std::function at compile time.

Allow copying std::function at compile time, but throw a run time error if the contained type is not copyable.

Allow copying std::function at compile time, and require any function object that you put into it to be copyable.

Approach #1 is very restrictive on how functions may be stored, passed and shared, and basically forbids common use cases in favor of the uncommon case of using a non-copyable function object.

Approach #2 is problematic because users would need to be educated that copying a std::function may fail in some cases and use great diligence when writing their code. Also, if the design requires sharing functions they may need to be wrapped in a std::shared_ptr. And if they need to be copied and may be stateful, it becomes even worse.

No matter how you view approach #3, it is the one that was standardized. But in light of the above-mentioned problems, it is also easily to defend.

As a matter of fact, I have written a unique_function class template that uses approach #1 for my current project because for us the use case of storing non-copyable asynchronous task objects is quite common, and copying or sharing such a task isn't necessary.


问:
Running .NET .exe in Azure Data Factory
I have an .exe (console application) file written in C# , which I want to run using Azure Data Factory.

What are the steps I need to do to achieve this?

I know that for .dll files we have options to run them in azure, but what about .exe files?

答:
You can't. Stop trying to put a square peg in a round hole. It will have to be wrapped up as an ADF custom activity.

You need to inherit from the ADF base class and call the IDictionary execute method.

For example:

```<code>using System;
using System.Collections.Generic;
using System.Linq;

using Microsoft.Azure;
using Microsoft.Azure.Management.DataFactories.Models;
using Microsoft.Azure.Management.DataFactories.Runtime;

namespace ClassLibrary1
{
    public class Class1 : IDotNetActivity
    {
        public IDictionary string, string Execute(
                IEnumerable linkedServices,
                IEnumerable datasets,
                Activity activity,
                IActivityLogger logger)
        {
            logger.Write("Start");

            //Get extended properties
            DotNetActivity dotNetActivityPipeline = (DotNetActivity)activity.TypeProperties;

            string sliceStartString = dotNetActivityPipeline.ExtendedProperties["SliceStart"];

            //Get linked service details
            Dataset inputDataset = datasets.Single(dataset = dataset.Name == activity.Inputs.Single().Name);
            Dataset outputDataset = datasets.Single(dataset = dataset.Name == activity.Outputs.Single().Name);

            /*
                DO STUFF
            */

            logger.Write("End");

            return new Dictionary string, string();
        }
    }
}
</code>```

Source: https://www.purplefrogsystems.com/paul/2016/11/creating-azure-data-factory-custom-activities/

Whatever methods you have in the console app just rewrite them as a class that can be instantiated by the Azure Batch Service compute pool, which is where ADF passed the compiled to.

This is how ADF does it.

Hope this helps.

Title: Running .NET .exe in Azure Data Factory

Body:
You can't. Stop trying to put a square peg in a round hole. It will have to be wrapped up as an ADF custom activity.

You need to inherit from the ADF base class and call the IDictionary execute method.

For example:

using System;
using System.Collections.Generic;
using System.Linq;

using Microsoft.Azure;
using Microsoft.Azure.Management.DataFactories.Models;
using Microsoft.Azure.Management.DataFactories.Runtime;

namespace ClassLibrary1
{
    public class Class1 : IDotNetActivity
    {
        public IDictionary string, string Execute(
                IEnumerable linkedServices,
                IEnumerable datasets,
                Activity activity,
                IActivityLogger logger)
        {
            logger.Write("Start");

            //Get extended properties
            DotNetActivity dotNetActivityPipeline = (DotNetActivity)activity.TypeProperties;

            string sliceStartString = dotNetActivityPipeline.ExtendedProperties["SliceStart"];

            //Get linked service details
            Dataset inputDataset = datasets.Single(dataset = dataset.Name == activity.Inputs.Single().Name);
            Dataset outputDataset = datasets.Single(dataset = dataset.Name == activity.Outputs.Single().Name);

            /*
                DO STUFF
            */

            logger.Write("End");

            return new Dictionary string, string();
        }
    }
}

Source: https://www.purplefrogsystems.com/paul/2016/11/creating-azure-data-factory-custom-activities/

Whatever methods you have in the console app just rewrite them as a class that can be instantiated by the Azure Batch Service compute pool, which is where ADF passed the compiled to.

This is how ADF does it.

Hope this helps.


问:
Why the wildfly-swarm-plugin tries to download the dependencies from jboss group repository no matter what I configure in settings xml?
When I use the JBoss Wildfly Swarm Plugin it tries to download the dependencies from the repository.jboss.org maven repository, even though I set up a repository with the same id in settings.xml

```<code>[INFO]  --- wildfly-swarm-plugin:2017.5.0:package (default) @ my-swarm-driver ---
[INFO] Downloading: https://repository.jboss.org/nexus/content/groups/public/com/test/java-client/1.0-SNAPSHOT/maven-metadata.xml
[WARNING] Could not transfer metadata com...
</code>```

How to force the plugin to use my enterprise repository?

答:
You have to set up a new mirror in your settings.xml (better use the private one under HOME_DIR/.m2/settings.xml

```<code><settings>
  ...
  <mirrors>
    <mirror>
      <id>jboss-public-repository-group-axa</id>
      <name>My Mirror JBoss Public Group Central</name>
      <url>https://myserver.com/nexus/content/groups/my-group</url>
      <mirrorOf>jboss-public-repository-group</mirrorOf>
    </mirror>

</mirrors>
</code>```

Body:
When I use the JBoss Wildfly Swarm Plugin it tries to download the dependencies from the repository.jboss.org maven repository, even though I set up a repository with the same id in settings.xml

[INFO]  --- wildfly-swarm-plugin:2017.5.0:package (default) @ my-swarm-driver ---
[INFO] Downloading: https://repository.jboss.org/nexus/content/groups/public/com/test/java-client/1.0-SNAPSHOT/maven-metadata.xml
[WARNING] Could not transfer metadata com...

How to force the plugin to use my enterprise repository?

Body:
You have to set up a new mirror in your settings.xml (better use the private one under HOME_DIR/.m2/settings.xml

<settings>
  ...
  <mirrors>
    <mirror>
      <id>jboss-public-repository-group-axa</id>
      <name>My Mirror JBoss Public Group Central</name>
      <url>https://myserver.com/nexus/content/groups/my-group</url>
      <mirrorOf>jboss-public-repository-group</mirrorOf>
    </mirror>

</mirrors>


问:
Jquery DOM Manipulation Advanced Selection
I am working with some sort of E-Shop Template and I can only manipulate some stuff with Jquery and JS.

Problem No 1:

I want to give the first box with the Content "Hello and Welcome!" and  some background-Image. Problem is, that this box has some padding and I need to set the Background to the parent "inner-Wrapper" of this Div.

Is there a way to select the first "inner-wrapper" and check if the Content is "hello and welcome!" in the Content-box?

Problem No 2:

Box 1 - Box 4 Need another Background-Image.

I know some basic Jquery stuff but I struggle with those advanced stuff. And after 4 hours of trial and error I have to ask you guys.

I hope you can help me, and thanks in advance!

                Hello and Welcome!

            Box 1

            Box 2

            Box 3

            Box 4

```

答:
Instead of checking the text you can add an extra class and check for that class Or you can give a seperate background image for the   $('.content-box')   inside the first .inner-wrapper

$(function(){
  $('.content-box').each(function(){
    if($(this).hasClass('firstBox')){

        $(this).parent().css('background-image', 'url(http://via.placeholder.com/350x150)');
    }else{
     $(this).parent().css('background-image', 'url(http://via.placeholder.com/150x150)');
    }
  })
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.inner-wrapper{
  width:100px;
  height:100px;
  background-size: cover;
  border:1px solid #ddd;
}</code>```

                Hello and Welcome!

            Box 1

            Box 2

            Box 3

            Box 4

```

Body:
Instead of checking the text you can add an extra class and check for that class Or you can give a seperate background image for the   $('.content-box')   inside the first .inner-wrapper

$(function(){
  $('.content-box').each(function(){
    if($(this).hasClass('firstBox')){

        $(this).parent().css('background-image', 'url(http://via.placeholder.com/350x150)');
    }else{
     $(this).parent().css('background-image', 'url(http://via.placeholder.com/150x150)');
    }
  })
})

.inner-wrapper{
  width:100px;
  height:100px;
  background-size: cover;
  border:1px solid #ddd;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">

    <div class="inner-wrapper">
            <div class="content-box firstBox">

                Hello and Welcome!

            </div>
    </div>
    <div class="inner-wrapper">
            <div class="content-box">

                <img src="" alt="">

            </div>
    </div>

</div>

<div class="row">
    <div class="inner-wrapper">
        <div class="content-box">

            Box 1

        </div>
    </div>
    <div class="inner-wrapper">
        <div class="content-box">

            Box 2

        </div>
    </div>
    <div class="inner-wrapper">
        <div class="content-box">

            Box 3

        </div>
    </div>
    <div class="inner-wrapper">
        <div class="content-box">

            Box 4

        </div>
    </div>

</div>


问:
update an entry in contentful with an reference field
I am working on a project with Contentful, using the contentful-management node module, with Javascript.
I am trying to create an reference in an entry containing a new entry.

I get the following message in the browser console:

```<code>     Uncaught (in promise) Error: {
     "request": {
"url": "https://api.contentful.com:443/spaces/59mi8sr8zemv/entries/2Bxpz2RgA4AQImQOssey8w/published",
"headers": {
  "Accept": "application/json, text/plain, */*",
  "Content-Type": "application/vnd.contentful.management.v1+json",
  "X-Contentful-User-Agent": "contentful-management.js/1.3.1",
  "Authorization": "Bearer <my management-api key>",
  "X-Contentful-Version": 373
  },
   "method": "put",
   "payloadData": null
    },
    "status": 422,
    "statusText": "Unprocessable Entity",
    "requestId": "d00dde60cd564a8db84da90cd671b19f",
    "message": "Validation error",
    "details": {
    "errors": [
    {
    "name": "notResolvable",
    "link": {
      "id": "2Yfc2H8q9OSoOccGcSg4aU",
      "linkType": "Entry",
      "type": "Link"
    },
    "path": [
      "fields",
      "link",
      "en-US",
      7
    ]
  }
]
}
}
 at errorHandler (main-addTrack.bundle.js:3096)
</code>```

When I look in the contentful web app the new entry is there, but saved as a draft. The entry I am trying to add an entry to, says that it needs to be updated.

This is the function i use to create and update the new entry.

```<code>    function publishTrack(){
        //-- Creates the new track in events, with ref to korrekt date
        client.getSpace(<my_spaceId>)
            .then((space) => {
            space.createEntry('events', newTrack)
                .then( event => {

                eventID = event.sys.id;

               (entry) => entry.publish()

                //This function is gets the entry of choosen date
                space.getEntry(dateId)
                    .then((entry) => {

                    //Gets the ID from the newly created event
                    var newId = {sys: {
                        id: eventID,
                        linkType: "Entry",
                        type:"Link"
                    }}

                    //Creates a reference field in dates for show & do
                    entry.fields.link["en-US"].push(newId)

                    //update the event
                    return entry.update()
                    space.getEntry(eventID)
                    .then ((eventID) => entry.publish())

                })
                  space.getEntry(dateId)
                    .then ((entry) => entry.publish());

            })

            publishModal.style.display = 'block';
            publishModal.style.opacity = '1';
            publishModal.style.pointerEvents = 'auto';
            publishModal.style.zIndex = '99999';

        })

    }//end publish track
</code>```

Please apologize for any mistakes, this is my first post on stackowerflow.

答: Looks like one of your reference entries can't be resolved specifically the one at fields.link["en-US"][7] (note the "path" property in the error message), make sure it was created and published before you create the event.

Body:
I am working on a project with Contentful, using the contentful-management node module, with Javascript.
I am trying to create an reference in an entry containing a new entry.

I get the following message in the browser console:

     Uncaught (in promise) Error: {
     "request": {
"url": "https://api.contentful.com:443/spaces/59mi8sr8zemv/entries/2Bxpz2RgA4AQImQOssey8w/published",
"headers": {
  "Accept": "application/json, text/plain, */*",
  "Content-Type": "application/vnd.contentful.management.v1+json",
  "X-Contentful-User-Agent": "contentful-management.js/1.3.1",
  "Authorization": "Bearer <my management-api key>",
  "X-Contentful-Version": 373
  },
   "method": "put",
   "payloadData": null
    },
    "status": 422,
    "statusText": "Unprocessable Entity",
    "requestId": "d00dde60cd564a8db84da90cd671b19f",
    "message": "Validation error",
    "details": {
    "errors": [
    {
    "name": "notResolvable",
    "link": {
      "id": "2Yfc2H8q9OSoOccGcSg4aU",
      "linkType": "Entry",
      "type": "Link"
    },
    "path": [
      "fields",
      "link",
      "en-US",
      7
    ]
  }
]
}
}
 at errorHandler (main-addTrack.bundle.js:3096)

When I look in the contentful web app the new entry is there, but saved as a draft. The entry I am trying to add an entry to, says that it needs to be updated.

This is the function i use to create and update the new entry.

    function publishTrack(){
        //-- Creates the new track in events, with ref to korrekt date
        client.getSpace(<my_spaceId>)
            .then((space) => {
            space.createEntry('events', newTrack)
                .then( event => {

                eventID = event.sys.id;

               (entry) => entry.publish()

                //This function is gets the entry of choosen date
                space.getEntry(dateId)
                    .then((entry) => {

                    //Gets the ID from the newly created event
                    var newId = {sys: {
                        id: eventID,
                        linkType: "Entry",
                        type:"Link"
                    }}

                    //Creates a reference field in dates for show & do
                    entry.fields.link["en-US"].push(newId)

                    //update the event
                    return entry.update()
                    space.getEntry(eventID)
                    .then ((eventID) => entry.publish())

                })
                  space.getEntry(dateId)
                    .then ((entry) => entry.publish());

            })

            publishModal.style.display = 'block';
            publishModal.style.opacity = '1';
            publishModal.style.pointerEvents = 'auto';
            publishModal.style.zIndex = '99999';

        })

    }//end publish track

Please apologize for any mistakes, this is my first post on stackowerflow.


问:
Compare two records in two table in trigger sql server 2005
i want that if DELETED and INSERTED table have the same record then i will not update a another table. so please tell me how can i compare two rows in two different table DELETED and INSERTED having same structure.

please help me with sample code.

thanks

答:
You have to test each and every column

```<code>INSERT OtherTable (keycol, col1, col2, ...)
SELECT
     I.keycol, I.Col1, I.Col2, ..
FROM
     INSERTED I
     JOIN
     DELETED D On I.keycol = D.keycol
WHERE
     I.col1 <> I.col1
     OR
     I.col2 <> I.col2
     OR
     ISNULL(I.col3, 0) <> ISNULL(I.col3, 0) --nullable columns
     OR
     ...
</code>```

You can also use HASHBYTES

```<code>INSERT ...
SELECT
     I.keycol, I.Col1, I.Col2, ..
FROM
     INSERTED I
     JOIN
     DELETED D On I.keycol = D.keycol
WHERE
     HashBytes('SHA1', CAST(I.col1 AS nvarchar) + I.col2 + etc)
     <>
     HashBytes('SHA1', CAST(D.col1 AS nvarchar) + D.col2 + etc)
</code>```

Not 100% reliable, use CHECKSUM

```<code>INSERT ...
SELECT
     I.keycol, I.Col1, I.Col2, ..
FROM
     INSERTED I
     JOIN
     DELETED D On I.keycol = D.keycol
WHERE
     CHECKSUM(I.*) <> CHECKSUM(D.*)
</code>```

Body:
You have to test each and every column

INSERT OtherTable (keycol, col1, col2, ...)
SELECT
     I.keycol, I.Col1, I.Col2, ..
FROM
     INSERTED I
     JOIN
     DELETED D On I.keycol = D.keycol
WHERE
     I.col1 <> I.col1
     OR
     I.col2 <> I.col2
     OR
     ISNULL(I.col3, 0) <> ISNULL(I.col3, 0) --nullable columns
     OR
     ...

You can also use HASHBYTES

INSERT ...
SELECT
     I.keycol, I.Col1, I.Col2, ..
FROM
     INSERTED I
     JOIN
     DELETED D On I.keycol = D.keycol
WHERE
     HashBytes('SHA1', CAST(I.col1 AS nvarchar) + I.col2 + etc)
     <>
     HashBytes('SHA1', CAST(D.col1 AS nvarchar) + D.col2 + etc)

Not 100% reliable, use CHECKSUM

INSERT ...
SELECT
     I.keycol, I.Col1, I.Col2, ..
FROM
     INSERTED I
     JOIN
     DELETED D On I.keycol = D.keycol
WHERE
     CHECKSUM(I.*) <> CHECKSUM(D.*)


问:
How to create a event form similar to fb in android
I want to create a event form something like this o exactly like this, is there a library for this kind of a event form or how can i do this? Sorry im newbie in android. I've creating a event app for android. Thank you for any help.

https://ibb.co/bwnTLv

答:
First of all use recyclerview Horizontal
then use cardview to design your card as per your design

http://www.androidhive.info/2016/05/android-working-with-card-view-and-recycler-view/

here is the demo of both the things.


问:
Why can't the signal handler in the child process be triggered?
My intention is to create a time out of 1 sec for fgets. If no input is received in 1 sec, then the program terminates.

The design I come up with is:
the parent registers a signal handler for SIGALRM. Then it forks a child which will trigger SIGALRM and it goes ahead and call fgets. The SIGALRM will trigger the handler which kills the parent process. But when I execute this on a ubuntu 14.04 64-bit, the handler is not triggered and the program just waits for user to input for fgets forever.

Why would this happen and how can I fix this?

```<code>#include "csapp.h"

void handler() {
  printf("lazy man\n");
  kill(SIGKILL, getppid());
  exit(0);
}

int main() {
  char buf[100];
  signal(SIGALRM, handler);
  pid_t pid;
  if ((pid = fork()) == 0) {
    alarm(1);
  } else {
    fgets(buf, 100, stdin);
    printf("%s", buf);
  }
  return 0;
}
</code>```

~

答: This forking and killing seems wrong.  Just set the alarm, register an empty signal handler for SIGALRM, and then check the return value from fgets() - if it fails, check whether errno == EINTR; if it does - it was interrupted by signal.</p>

Body:
My intention is to create a time out of 1 sec for fgets. If no input is received in 1 sec, then the program terminates.

The design I come up with is:
the parent registers a signal handler for SIGALRM. Then it forks a child which will trigger SIGALRM and it goes ahead and call fgets. The SIGALRM will trigger the handler which kills the parent process. But when I execute this on a ubuntu 14.04 64-bit, the handler is not triggered and the program just waits for user to input for fgets forever.

Why would this happen and how can I fix this?

#include "csapp.h"

void handler() {
  printf("lazy man\n");
  kill(SIGKILL, getppid());
  exit(0);
}

int main() {
  char buf[100];
  signal(SIGALRM, handler);
  pid_t pid;
  if ((pid = fork()) == 0) {
    alarm(1);
  } else {
    fgets(buf, 100, stdin);
    printf("%s", buf);
  }
  return 0;
}

~


问:
How do I run a Python program in the Command Prompt in Windows 7?
I'm trying to figure out how to run Python programs with the Command Prompt on Windows 7. (I should have figured this out by now...)

When I typed "python" into the command prompt, I got the following error:

'python' is not recognized as an internal or external command,
operable program or batch file.

The first place I found when looking for help was this site: http://docs.python.org/faq/windows.html#how-do-i-run-a-python-program-under-windows.

It was somewhat helpful, but the tutorial was written for Windows 2000 and older, so it was minimally helpful for my Windows 7 machine. I attempted the following:

For older versions of Windows the easiest way to do this is to edit the C:\AUTOEXEC.BAT >file. You would want to add a line like the following to AUTOEXEC.BAT:

This file did not exist on my machine (unless I'm mistaken).

Next, I tried this: (here: How do I run a Python program?)

Putting Python In Your Path

Windows

In order to run programs, your operating system looks in various places, and tries to match the name of the program / command you typed with some programs along the way.

In windows:

control panel > system > advanced > |Environmental Variables| > system variables -> Path

this needs to include: C:\Python26; (or equivalent). If you put it at the front, it will be the first place looked. You can also add it at the end, which is possibly saner.

Then restart your prompt, and try typing 'python'. If it all worked, you should get a ">>>" prompt.

This was relevant enough for Windows 7, and I made my way to the System Variables. I added a variable "python"  with the value "C:\Python27"

I continued to get the error, even after restarting my computer.

Anyone know how to fix this?

答:
Goto the Start Menu
Right Click "Computer"
Select "Properties"
A dialog should pop up with a link on the left called "Advanced system settings". Click it.
In the System Properties dialog, click the button called "Environment Variables".
In the Environment Variables dialog look for "Path" under the System Variables window.
Add ";C:\Python27" to the end of it. The semicolon is the path separator on windows.
Click Ok and close the dialogs.
Now open up a new command prompt and type "python"

If still the problem persists then type "py" instead of "python" in command prompt. might help!!!!


问:
How to display a difference modal popup According to click button
Hello friends  i have 4 modal popup, and i want to display one by one according to click buttons. this buttons is in foreach
this is my foreach

```<code>  <div class="col-sm-6 poleA">
      @foreach($competences as $competence)
        <?php $var = $var+1; ?>
     <div class="developemnt">
     <div class="poleaa"><img src="{{ asset('storage/'.$competence->image) }}" class="img-responsive icone" alt="Placeholder image">
      <h1 class="titrepole"> {{ $competence->titre }} </h1>
      <p class="parapole">
        {{ $competence->description }}
       </p>
       <button type="button" class="btn btn-sm btn-default btnpole" data-
       toggle="modal" data-target="#mymodal">Demander Votre Devis</button>
      </div>
      </div>
        @if($var == 2)
        @break;
        @endif
      @endforeach
        <?php $var = 0; ?>
    </div>
</code>```

When i click a button i want to display a modal according the event select.

答:
You want to customise your data-target to reference a unique modal that corresponds to your $var / iteration:

```<code><button type="button" class="btn btn-sm btn-default btnpole" data-
   toggle="modal" data-target="#mymodal{{$var}}">Demander Votre Devis</button>

<button type="button" class="btn btn-sm btn-default btnpole" data-
   toggle="modal" data-target="#mymodal{{$var}}">Demander Votre Devis</button>
</code>```

If you have modals with that ID in your code, they'll be triggered :)

Body:
Hello friends  i have 4 modal popup, and i want to display one by one according to click buttons. this buttons is in foreach
this is my foreach

      @foreach($competences as $competence)
        <?php $var = $var+1; ?>

image) }}" class="img-responsive icone" alt="Placeholder image">

 {{ $competence->titre }}

        {{ $competence->description }}

       <button type="button" class="btn btn-sm btn-default btnpole" data-
       toggle="modal" data-target="#mymodal">Demander Votre Devis</button>

        @if($var == 2)
        @break;
        @endif
      @endforeach
        <?php $var = 0; ?>

When i click a button i want to display a modal according the event select.

Body:
You want to customise your data-target to reference a unique modal that corresponds to your $var / iteration:

<button type="button" class="btn btn-sm btn-default btnpole" data-
   toggle="modal" data-target="#mymodal{{$var}}">Demander Votre Devis</button>

<button type="button" class="btn btn-sm btn-default btnpole" data-
   toggle="modal" data-target="#mymodal{{$var}}">Demander Votre Devis</button>

If you have modals with that ID in your code, they'll be triggered :)


问:
Angularjs formData.append is not working
Hi I am developing angularjs application. I have file upload module. I am appending file data to FormData as below.

```<code> var filesformdata = new FormData();
    angular.forEach(this.pendingFiles, function (value, key) {
                filesformdata.append(key, value);
            });
            for (var pair of filesformdata.entries()) {
                console.log(pair[0] + ', ' + pair[1]);
            }
</code>```

This is My angular code.

```<code>angular.module('RoslpApp').factory('fileUpload', ['$http', function ($http) {
    debugger;
    var fileuploadurl = "http://localhost:19144/" + 'api/Customer/UploadLeaseFiles/' + 2;
    var service = {
        uploadUrl: fileuploadurl,
        pendingFiles: [],
        doUpload: doUpload
    };
    return service;

    function doUpload() {
        debugger;
        var filesformdata = new FormData();
        angular.forEach(this.pendingFiles, function (value, key) {
            filesformdata.append(key, value);
        });
        for (var pair of filesformdata.entries()) {
            console.log(pair[0] + ', ' + pair[1]);
        }

        return $http.post(this.uploadUrl, filesformdata, {
            transformRequest: angular.identity,
            headers: {
                'Content-Type': undefined
            }
        })
    }
}]);
</code>```

This is directive code.

```<code>myapp.directive('fileModel', ['fileUpload', function (fileUpload) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.bind("change", function (evt) {
                fileUpload.pendingFiles[attrs.fileModel] = evt.target.files[0];
            });
        }
    };
}]);
</code>```

This is upload function

```<code>  $scope.upload = function (filename) {
                debugger;
                fileUpload.doUpload().success(function (success) {
                   console.log(success);
                });
            };
</code>```

This is html code.

```<code><div class="upload-button" ng-repeat="file in files">
                <div class="upload-button-icon">
                    <img src="images/folder-small.png">
                    <div class="upload-text">{{file}}</div>
                    <input type="file" id="file1" name="file1" file-data="{{file}}" file-model="{{file}}"/>
                </div>
            </div>
   <input type="submit" value="{{ 'NEXT' | translate }}" class="blue-button" ng-click="upload()">
</code>```

Eventough i have files in this.pendingFiles when i display using console.log or in api using below code i dont get files.

```<code>  System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
                // CHECK THE FILE COUNT.
                UploadedLeaseFiles totalDocumentInserted = null;
                for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
</code>```

I have files inside this.pendingFiles. Please see the screen shot.

My filesformdata FormData is empty always. May i get some help here to fix this? Thanks.

答: The data in a FormData object filesformdata is not revealed by inspecting it with console.log(). It is there, you just can't see it. But however you can view it in networks tab under request payload.</p>

Body:
Hi I am developing angularjs application. I have file upload module. I am appending file data to FormData as below.

 var filesformdata = new FormData();
    angular.forEach(this.pendingFiles, function (value, key) {
                filesformdata.append(key, value);
            });
            for (var pair of filesformdata.entries()) {
                console.log(pair[0] + ', ' + pair[1]);
            }

This is My angular code.

angular.module('RoslpApp').factory('fileUpload', ['$http', function ($http) {
    debugger;
    var fileuploadurl = "http://localhost:19144/" + 'api/Customer/UploadLeaseFiles/' + 2;
    var service = {
        uploadUrl: fileuploadurl,
        pendingFiles: [],
        doUpload: doUpload
    };
    return service;

    function doUpload() {
        debugger;
        var filesformdata = new FormData();
        angular.forEach(this.pendingFiles, function (value, key) {
            filesformdata.append(key, value);
        });
        for (var pair of filesformdata.entries()) {
            console.log(pair[0] + ', ' + pair[1]);
        }

        return $http.post(this.uploadUrl, filesformdata, {
            transformRequest: angular.identity,
            headers: {
                'Content-Type': undefined
            }
        })
    }
}]);

This is directive code.

myapp.directive('fileModel', ['fileUpload', function (fileUpload) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.bind("change", function (evt) {
                fileUpload.pendingFiles[attrs.fileModel] = evt.target.files[0];
            });
        }
    };
}]);

This is upload function

  $scope.upload = function (filename) {
                debugger;
                fileUpload.doUpload().success(function (success) {
                   console.log(success);
                });
            };

This is html code.

{{file}}

                    <input type="file" id="file1" name="file1" file-data="{{file}}" file-model="{{file}}"/>

   <input type="submit" value="{{ 'NEXT' | translate }}" class="blue-button" ng-click="upload()">

Eventough i have files in this.pendingFiles when i display using console.log or in api using below code i dont get files.

  System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
                // CHECK THE FILE COUNT.
                UploadedLeaseFiles totalDocumentInserted = null;
                for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)

I have files inside this.pendingFiles. Please see the screen shot.

My filesformdata FormData is empty always. May i get some help here to fix this? Thanks.


问:
Show custom field in comment/response interface (RT)
I've created a custom field in order to detail what person's answer I'm waiting for.

Just an combo box that needs to apply to a ticket (queue or transaction doesn't work for me, because I need to filter the tickets using this field).

Now, I send a comment asking for something and I need to go all the way to the custom fields form to complete the field 'waiting for'. This is very tedious.

I would like to fill my custom field in the comment interface, under the ticket and transaction or message menu.

I've looked in RT documentation but I couldn't find anything similar (except changing the custom field to apply on transaction).

答: The "natural" way is to use the Jumbo link to update the whole ticket. Or you can install the CustomFieldsOnUpdate extension.


问:
Detecting complex shapes with opencv python
I'm working on a project where I need to be able to see the difference between all 4 playing card symbols: heart, spade, diamond and club in real-time. This means that the angle, lighting, and distance to the symbol(s) constantly change (and therefore detecting objects based on contour area won't be an option).

So when I hold a heart symbol in front of my camera I'm trying to draw the word 'heart' inside it. if I do the same with a spade, I want it to write "spade", etc.

I have tried doing this in various different ways, but all attempts failed or didn't work as good as I want it to.

The methods I've tried:

haarcascades

template matching, doesn't work due to the rotations that are possible

color detection, which only does half the job since there are 2 symbols per color

feature matching: this tutorial doesn't work because the symbols don't have enough detail to find the keypoints

I can add source codes of these attempts if needed, but I don't think it will add any value, since they didn't really get me anywhere.

The Images I'm using:

答:
Since you're dealing with relative low complex symbols why don't you try contour match shaping? You might have to adapt to some more complex cases but I think that could be a first good approach:

Contours : More Functions

Structural Analysis and Shape Descriptors

Remember that you also have the color information to use in your app. Anyway, also take a look at this.


问:
Sorting in SQL Server
I am trying to sort a week column with the datatype varchar because the weeks are in this format 2017_6, 2017_7. As we all know SQL sorts varchar numbers like 2017_1, 2017_10, 2017_11 etc.

How can I get it to sort numerically, without changing the weeks format? I tried nvarchar but that didn't work.

答:
Trick using PARSENAME, this will work with any year range:

```<code>ORDER BY CAST(PARSENAME(Replace(ColumnName, '_', '.'), 2) AS INT),
         CAST(PARSENAME(Replace(ColumnName, '_', '.'), 1) AS INT);
</code>```

Sample execution with sample data:

```<code>DECLARE @TestTable TABLE (MonthValue VARCHAR (10));

INSERT INTO @TestTable (MonthValue) VALUES
('2017_6'), ('2017_7'),  ('2016_12'), ('2017_10'), ('2017_11');

SELECT *
FROM @TestTable
ORDER BY CAST(PARSENAME(Replace(MonthValue, '_', '.'), 2) AS INT),
         CAST(PARSENAME(Replace(MonthValue, '_', '.'), 1) AS INT)
</code>```

Result:

```<code>2016_12
2017_6
2017_7
2017_10
2017_11
</code>```

Title: Sorting in SQL Server

Body:
Trick using PARSENAME, this will work with any year range:

ORDER BY CAST(PARSENAME(Replace(ColumnName, '_', '.'), 2) AS INT),
         CAST(PARSENAME(Replace(ColumnName, '_', '.'), 1) AS INT);

Sample execution with sample data:

DECLARE @TestTable TABLE (MonthValue VARCHAR (10));

INSERT INTO @TestTable (MonthValue) VALUES
('2017_6'), ('2017_7'),  ('2016_12'), ('2017_10'), ('2017_11');

SELECT *
FROM @TestTable
ORDER BY CAST(PARSENAME(Replace(MonthValue, '_', '.'), 2) AS INT),
         CAST(PARSENAME(Replace(MonthValue, '_', '.'), 1) AS INT)

Result:

2016_12
2017_6
2017_7
2017_10
2017_11


问:
Hyperledger Composer Failed to load connector module "composer-connector-hlfv1" for connection profile "hlfv1"
I was following the developer guide they have on the composer website and I encountered this error while trying to deploy the business network definition to the fabric.I'm using:

composer-client v0.7.6

node - v6.10.3

npm - v5.0.2

xcode - 4.8.4

These are the logs.

These are the npm logs

答: The problem was solved by uninstalling and reinstalling docker</p>


问:
Two UINavigationControllers side-by-side on iPad iOS 4 without UISplitViewController
How can I create an interface like the settings app on the iPad where the left side does not collapse as does in the UISplitViewController?

I need to create a UI where the left (master if you will) is a UITableViewController and the right pane (detail) is a UINavigationController.

Any help is greatly appreciated.  I had a UI previously using a UISplitViewController but as of iOS 4 on the iPad regardless of what I do it hides the master (left) view.

Thank you

答: u can do this by taking two layers, i.e, divide your screen(view) into 2 layers by setting the frames. Now, u can do what ever you want with them since they are 2 independent views. </p>


问:
How to avoid negative time between time difference?
I'm developing an app in which I'm using Java8 Time. I'm facing an issue.

Let's say Time A is 08:00 and Time B is 17:00, so the difference of between these two times will be 9h which in my case is correct, but if Time A is 18:00 and Time B is 02:00 it should be 8h, but in my case my program is returning -16. Kindly someone guide me how to solve this.

My code:

```<code>@Test
public void testTime()
{
    DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm");

    String s = "18:00";
    String e = "02:00";

    // Parse datetime string to java.time.LocalDateTime instance
    LocalTime startTime = LocalTime.parse(s, format);
    LocalTime endTime = LocalTime.parse(e, format);

    String calculatedTime = ChronoUnit.HOURS.between(startTime, endTime)%24 + ":"
            + ChronoUnit.MINUTES.between(startTime, endTime)%60;

    System.out.println(calculatedTime);

}
</code>```

答:
Why not use the Duration class? It’s meant for situations like yours.

```<code>    Duration calculatedTime = Duration.between(startTime, endTime);
    if (calculatedTime.isNegative()) {
        calculatedTime = calculatedTime.plusDays(1);
    }

    System.out.println(calculatedTime);
</code>```

This prints the duration in ISO 8601 format:

```<code>PT8H
</code>```

To format it in Java 8:

```<code>    long hours = calculatedTime.toHours();
    calculatedTime = calculatedTime.minusHours(hours);
    String formattedTime = String.format(Locale.getDefault(), "%d:%02d",
                                         hours, calculatedTime.toMinutes());
    System.out.println(formattedTime);
</code>```

This prints

```<code>8:00
</code>```

To format in Java 9 (not tested):

```<code>    String formattedTime = String.format("%d:%02d",
                                         calculatedTime.toHoursPart(),
                                         calculatedTime.toMinutesPart());
</code>```

Body:
I'm developing an app in which I'm using Java8 Time. I'm facing an issue.

Let's say Time A is 08:00 and Time B is 17:00, so the difference of between these two times will be 9h which in my case is correct, but if Time A is 18:00 and Time B is 02:00 it should be 8h, but in my case my program is returning -16. Kindly someone guide me how to solve this.

My code:

@Test
public void testTime()
{
    DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm");

    String s = "18:00";
    String e = "02:00";

    // Parse datetime string to java.time.LocalDateTime instance
    LocalTime startTime = LocalTime.parse(s, format);
    LocalTime endTime = LocalTime.parse(e, format);

    String calculatedTime = ChronoUnit.HOURS.between(startTime, endTime)%24 + ":"
            + ChronoUnit.MINUTES.between(startTime, endTime)%60;

    System.out.println(calculatedTime);

}

Body:
Why not use the Duration class? It’s meant for situations like yours.

    Duration calculatedTime = Duration.between(startTime, endTime);
    if (calculatedTime.isNegative()) {
        calculatedTime = calculatedTime.plusDays(1);
    }

    System.out.println(calculatedTime);

This prints the duration in ISO 8601 format:

PT8H

To format it in Java 8:

    long hours = calculatedTime.toHours();
    calculatedTime = calculatedTime.minusHours(hours);
    String formattedTime = String.format(Locale.getDefault(), "%d:%02d",
                                         hours, calculatedTime.toMinutes());
    System.out.println(formattedTime);

This prints

8:00

To format in Java 9 (not tested):

    String formattedTime = String.format("%d:%02d",
                                         calculatedTime.toHoursPart(),
                                         calculatedTime.toMinutesPart());


问:
How to set up file permissions for Laravel?
I'm using Apache Web Server that has the owner set to _www:_www. I never know what is the best practice with file permissions, for example when I create new Laravel 5 project.

Laravel 5 requires /storage folder to be writable. I found plenty of different approaches to make it work and I usually end with making it 777 chmod recursively. I know it's not the best idea though.

The official doc says:

Laravel may require some permissions to be configured: folders within
  storage and vendor require write access by the web server.

Does it mean that the web server needs access to the storage and vendor folders themselves too or just their current contents?

I assume that what is much better, is changing the owner instead of permissions. I changed all Laravel's files permissions recursively to _www:_www and that made the site work correctly, as if I changed chmod to 777. The problem is that now my text editor asks me for password each time I want to save any file and the same happens if I try to change anything in Finder, like for example copy a file.

What is the correct approach to solve these problems?

Change chmod

Change the owner of the files to match those of the
    web server and perhaps set the text editor (and Finder?) to skip
    asking for password, or make them use sudo

Change the owner of the web server to match the os user (I don't
know the consequences)

Something else

答:
Most folders should be normal "755" and files, "644"

Laravel requires some folders to be writable for the web server user. You can use this command on unix based OSs.

```<code>sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache
</code>```

Body:
Most folders should be normal "755" and files, "644"

Laravel requires some folders to be writable for the web server user. You can use this command on unix based OSs.

sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache


问:
Django - How to filter a ManyToMany model object?
I have the following models which are linked via a foreign key and ManyToMany relationship.

```<code>from django.db import models
from django.contrib.auth.models import User

class AssetMetadata(models.Model):

    id = models.DecimalField(6).auto_creation_counter
    material_id = models.CharField(max_length=256, blank=True)
    series_title = models.CharField(max_length=256, blank=True)
    season_title = models.CharField(max_length=256, blank=True)
    season_number = models.IntegerField(default=0)
    episode_title = models.CharField(max_length=256, blank=True)
    episode_number = models.IntegerField(default=0)
    synopsis = models.TextField(max_length=1024, blank=True)
    ratings = models.CharField(max_length=256, blank=True)

    def __str__(self):
        return self.material_id

class Batch(models.Model):
    material_id = models.ManyToManyField(AssetMetadata)
    user = models.ForeignKey(User, unique=True)

    def __str__(self):
        return 'Batch_' + str(self.pk) + '_' + self.user.username
</code>```

I can see that this has worked and the models have been created and the relationships work as you would expect. As you can see from the console output:

```<code>>>> from asset_db.models import Batch
>>> Batch.objects.values()
<QuerySet [{'user_id': 1, 'id': 1}, {'user_id': 3, 'id': 2}]>
</code>```

When i migrated the models it created the following tables (added so you can see the relationships).

asset_db_batch:

```<code>id | user_id
____________
1  |    1
2  |    3
</code>```

asset_db_batch_material_id:

```<code>id    |   batch_id  |  assetmetadata_id
______|_____________|________________
1     |      1      |        1
2     |      1      |        2
3     |      1      |        6
4     |      1      |        8
5     |      1      |        4
6     |      2      |        8
7     |      2      |        2
8     |      2      |        4
9     |      2      |        7
</code>```

My question is how do I filter the Batch object to return the items associated to a batch_id? Basically how do i recreate this SQL query in Django:

```<code>SELECT * FROM asset_db_batch_material_id
  INNER JOIN asset_db_batch
    ON asset_db_batch_material_id.batch_id = asset_db_batch.id
  INNER JOIN asset_db_assetmetadata
    ON asset_db_batch_material_id.assetmetadata_id = asset_db_assetmetadata.id
WHERE user_id = 1
</code>```

答:
Similar to how you do with ForeignKey</p>

```<code>AssetMetadata.objects.filter(batch__user__id=1)
</code>```

Body:
I have the following models which are linked via a foreign key and ManyToMany relationship.

from django.db import models
from django.contrib.auth.models import User

class AssetMetadata(models.Model):

    id = models.DecimalField(6).auto_creation_counter
    material_id = models.CharField(max_length=256, blank=True)
    series_title = models.CharField(max_length=256, blank=True)
    season_title = models.CharField(max_length=256, blank=True)
    season_number = models.IntegerField(default=0)
    episode_title = models.CharField(max_length=256, blank=True)
    episode_number = models.IntegerField(default=0)
    synopsis = models.TextField(max_length=1024, blank=True)
    ratings = models.CharField(max_length=256, blank=True)

    def __str__(self):
        return self.material_id

class Batch(models.Model):
    material_id = models.ManyToManyField(AssetMetadata)
    user = models.ForeignKey(User, unique=True)

    def __str__(self):
        return 'Batch_' + str(self.pk) + '_' + self.user.username

I can see that this has worked and the models have been created and the relationships work as you would expect. As you can see from the console output:

>>> from asset_db.models import Batch
>>> Batch.objects.values()
<QuerySet [{'user_id': 1, 'id': 1}, {'user_id': 3, 'id': 2}]>

When i migrated the models it created the following tables (added so you can see the relationships).

asset_db_batch:

id | user_id
____________
1  |    1
2  |    3

asset_db_batch_material_id:

id    |   batch_id  |  assetmetadata_id
______|_____________|________________
1     |      1      |        1
2     |      1      |        2
3     |      1      |        6
4     |      1      |        8
5     |      1      |        4
6     |      2      |        8
7     |      2      |        2
8     |      2      |        4
9     |      2      |        7

My question is how do I filter the Batch object to return the items associated to a batch_id? Basically how do i recreate this SQL query in Django:

SELECT * FROM asset_db_batch_material_id
  INNER JOIN asset_db_batch
    ON asset_db_batch_material_id.batch_id = asset_db_batch.id
  INNER JOIN asset_db_assetmetadata
    ON asset_db_batch_material_id.assetmetadata_id = asset_db_assetmetadata.id
WHERE user_id = 1

Body:
Similar to how you do with ForeignKey

AssetMetadata.objects.filter(batch__user__id=1)


问:
Set Variable Varchar2 to date fields
I have a Script that I update a Date field

this is a part of my script

```<code>    var VARCHAR2(8 char);

var = '01/01/22';
    update table1 t set t.date = to_date(var,'dd/mm/yy');
</code>```

and then I got a null value in field date

why I dont have a 01/01/22 value ??

could you help me please !!

ANSWER       :::::::::::     PETIT PAPA merci :D

I created I new Varible with Date type

and I affecte the to_date to this variable

```<code>date_var Date;

date_var :=to_date(var,'dd/mm/yy');

update table1 t set t.date = date_var where ...;
</code>```

and it work THANK YOU everyONE

答:
Try
    to_date(var,'dd/mm/yy');</p>

Title: Set Variable Varchar2 to date fields

Body:
I have a Script that I update a Date field

this is a part of my script

    var VARCHAR2(8 char);

var = '01/01/22';
    update table1 t set t.date = to_date(var,'dd/mm/yy');

and then I got a null value in field date

why I dont have a 01/01/22 value ??

could you help me please !!

ANSWER       :::::::::::     PETIT PAPA merci :D

I created I new Varible with Date type

and I affecte the to_date to this variable

date_var Date;

date_var :=to_date(var,'dd/mm/yy');

update table1 t set t.date = date_var where ...;

and it work THANK YOU everyONE

Body:
Try
    to_date(var,'dd/mm/yy');