问:
How to render image/pdf in Http Module
I have two website (Web1 and Web2) and one domain (www.web1.com). Domain is mapped to Web1.

I have one http Module registered in Web1. When Request comes to Web1 and web page exist on Web1, it will display the Page. Otherwise page not found (404) on Web1, then module will send request to Web2 and get the response from Web2 and write to display.

Here is my http Module code:

```<code>    public class Testmodule : IHttpModule
{
    public void Dispose()
    {
        //clean-up code here.
    }
    public void Init(HttpApplication context)
    {
        context.PreSendRequestContent += context_PreSendRequestContent;
    }
    private void context_PreSendRequestContent(object sender, EventArgs e)
    {
        HttpContext context = HttpContext.Current;
        if (context.Response.StatusCode == 404)//On 404 on Web1 it will pass the the condition.
        {
            string strSite = WebConfigurationManager.AppSettings["Web2SiteURL"];
            string requestURL = ((HttpApplication)sender).Request.Url.ToString();
            string sourceURL = requestURL.Replace("http://" + HttpContext.Current.Request.Url.Authority, strSite);

            HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(sourceURL);
            HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

            string WebResp_html = string.Empty;
            using (StreamReader sr = new StreamReader(WebResp.GetResponseStream()))
            {
                WebResp_html = sr.ReadToEnd();
            }
            string strCurrentUrl = "http://" + HttpContext.Current.Request.Url.Authority + "/";

            //Replacing the image src Relative URL to Absolute URL in the html source code.
            //If I comment below Replacement code Page is rendering but images are not rendering from Web2 site.
            //Actually  the image/pdf/swg files from html source code with relative path not rendering properly.
            WebResp_html = WebResp_html.Replace(strSite, strCurrentUrl);

            context.Response.Write(WebResp_html);
            context.Response.Flush();
            context.Response.Close();

        }
    }
}
</code>```

Below is code of my code for Web2 Page2

```<code><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        This is my Page 2 on Web2.
        <br/>
    <p><img width="312" height="312" class="images" alt="" src="Images/Img1.jpg"/></p>
    </div>
    </form>
</body>
</html>
</code>```

It works fine for html tag. But could not render images with relative path. If I make the image src to absolute path then it render properly.

If I comment below Replacement code Page is rendering but images are not rendering from Web2 site (with relative path).

```<code>WebResp_html = WebResp_html.Replace(strSite, strCurrentUrl); //converting image src from relative to absolute path.
</code>```

Question : How can I render image on web page with relative path?
  Please help me..

答:
I found solution. For Images/PDF instated of StreamReader I have used BinaryReader and BinaryWrite</p>

```<code>    private void RenderBinaryContent(HttpWebResponse response)
    {
        using (var br = new BinaryReader(response.GetResponseStream()))
        {
            byte[] tempBytes;
            byte[] imageBytes;

            using (MemoryStream ms = new MemoryStream())
            {
                tempBytes = br.ReadBytes(4096);
                while (tempBytes.Length > 0)
                {
                    ms.Write(tempBytes, 0, tempBytes.Length);
                    tempBytes = br.ReadBytes(1024);
                }
                imageBytes = new byte[(int)ms.Length];
                ms.Position = 0;
                ms.Read(imageBytes, 0, imageBytes.Length);
            }

            HttpContext.Current.Response.BinaryWrite(imageBytes);
        }
    }
</code>```

Title: How to render image/pdf in Http Module

Body:
I have two website (Web1 and Web2) and one domain (www.web1.com). Domain is mapped to Web1.

I have one http Module registered in Web1. When Request comes to Web1 and web page exist on Web1, it will display the Page. Otherwise page not found (404) on Web1, then module will send request to Web2 and get the response from Web2 and write to display.

Here is my http Module code:

    public class Testmodule : IHttpModule
{
    public void Dispose()
    {
        //clean-up code here.
    }
    public void Init(HttpApplication context)
    {
        context.PreSendRequestContent += context_PreSendRequestContent;
    }
    private void context_PreSendRequestContent(object sender, EventArgs e)
    {
        HttpContext context = HttpContext.Current;
        if (context.Response.StatusCode == 404)//On 404 on Web1 it will pass the the condition.
        {
            string strSite = WebConfigurationManager.AppSettings["Web2SiteURL"];
            string requestURL = ((HttpApplication)sender).Request.Url.ToString();
            string sourceURL = requestURL.Replace("http://" + HttpContext.Current.Request.Url.Authority, strSite);

            HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(sourceURL);
            HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

            string WebResp_html = string.Empty;
            using (StreamReader sr = new StreamReader(WebResp.GetResponseStream()))
            {
                WebResp_html = sr.ReadToEnd();
            }
            string strCurrentUrl = "http://" + HttpContext.Current.Request.Url.Authority + "/";

            //Replacing the image src Relative URL to Absolute URL in the html source code.
            //If I comment below Replacement code Page is rendering but images are not rendering from Web2 site.
            //Actually  the image/pdf/swg files from html source code with relative path not rendering properly.
            WebResp_html = WebResp_html.Replace(strSite, strCurrentUrl);

            context.Response.Write(WebResp_html);
            context.Response.Flush();
            context.Response.Close();

        }
    }
}

Below is code of my code for Web2 Page2

    <title></title>

    <form id="form1" runat="server">

        This is my Page 2 on Web2.

    </form>

It works fine for html tag. But could not render images with relative path. If I make the image src to absolute path then it render properly.

If I comment below Replacement code Page is rendering but images are not rendering from Web2 site (with relative path).

WebResp_html = WebResp_html.Replace(strSite, strCurrentUrl); //converting image src from relative to absolute path.

Question : How can I render image on web page with relative path?
  Please help me..

Body:
I found solution. For Images/PDF instated of StreamReader I have used BinaryReader and BinaryWrite

    private void RenderBinaryContent(HttpWebResponse response)
    {
        using (var br = new BinaryReader(response.GetResponseStream()))
        {
            byte[] tempBytes;
            byte[] imageBytes;

            using (MemoryStream ms = new MemoryStream())
            {
                tempBytes = br.ReadBytes(4096);
                while (tempBytes.Length > 0)
                {
                    ms.Write(tempBytes, 0, tempBytes.Length);
                    tempBytes = br.ReadBytes(1024);
                }
                imageBytes = new byte[(int)ms.Length];
                ms.Position = 0;
                ms.Read(imageBytes, 0, imageBytes.Length);
            }

            HttpContext.Current.Response.BinaryWrite(imageBytes);
        }
    }


来源: stackexchange

问:
simpleXML node access by index prob!em
I am receiving an XML response based on a request I place to a server and it does in fact return a valid set of results that I can dump on the screen using print_r()
Result set looks like this(edit: this is the exact structure of the file):

```<code><root>
     <main_node1>
         <value1>one</value1>
         <value2>two</value2>
     </main_node1>
     <main_node2>
         <anothervalue>whatever</anothervalue>
     </main_node2>
     <recordset>
        <record>
            <value1>one</value1>
            <value2>two</value2>
        </reocrd>
        <record>
            <value1>one</value1>
            <value2>two</value2>
        </reocrd>
        <record>
            <value1>one</value1>
            <value2>two</value2>
        </reocrd>
     </recordset>
</root>
</code>```

when I use the line:

```<code>$xml = simplexml_load_string($xmlRequest);
$records = $xml->recordset->record;
</code>```

I can walk through the $records array with a foreach loop without any problems however, when I try to access a specific record within the recordset using an index such as

```<code>$record = $xml->recordset->record[$index];
</code>```

I am getting a NULL valeu back. I also tried to cast the result into an (array) with no success so far.

Every document I looked at regarding simpleXML says that it is possible to access the XML node by index, can someone please tell me what I might be doing wrong here?

Edit: so recordset is not the root of the document yet I am able to use the $xml->recordset->record notation to load a list of records in to my $records variable and print it out using the foreach loop.

答:
You're not getting anything back because the 'recordset' node is the root of your $xml variable (not sure if I'm describing this correctly).

This should work:

```<code><?php
    //Example xml, replace this with $xml = simplexml_load_string($xmlRequest);
    $xml = simplexml_load_string('<?xml version="1.0"?>
    <recordset><record><value1>one</value1><value2>two</value2></record>
    <record><value1>one</value1><value2>two</value2></record>
    </recordset>');

    $record = $xml->record[0];
    print_r ($record);
</code>```

?>

ContentLicense: CC BY-SA 3.0

Title: simpleXML node access by index prob!em

Body:
I am receiving an XML response based on a request I place to a server and it does in fact return a valid set of results that I can dump on the screen using print_r()
Result set looks like this(edit: this is the exact structure of the file):

<root>
     <main_node1>
         <value1>one</value1>
         <value2>two</value2>
     </main_node1>
     <main_node2>
         <anothervalue>whatever</anothervalue>
     </main_node2>
     <recordset>
        <record>
            <value1>one</value1>
            <value2>two</value2>
        </reocrd>
        <record>
            <value1>one</value1>
            <value2>two</value2>
        </reocrd>
        <record>
            <value1>one</value1>
            <value2>two</value2>
        </reocrd>
     </recordset>
</root>

when I use the line:

$xml = simplexml_load_string($xmlRequest);
$records = $xml->recordset->record;

I can walk through the $records array with a foreach loop without any problems however, when I try to access a specific record within the recordset using an index such as

$record = $xml->recordset->record[$index];

I am getting a NULL valeu back. I also tried to cast the result into an (array) with no success so far.

Every document I looked at regarding simpleXML says that it is possible to access the XML node by index, can someone please tell me what I might be doing wrong here?

Edit: so recordset is not the root of the document yet I am able to use the $xml->recordset->record notation to load a list of records in to my $records variable and print it out using the foreach loop.

Body:
You're not getting anything back because the 'recordset' node is the root of your $xml variable (not sure if I'm describing this correctly).

This should work:

<?php
    //Example xml, replace this with $xml = simplexml_load_string($xmlRequest);
    $xml = simplexml_load_string('<?xml version="1.0"?>
    <recordset><record><value1>one</value1><value2>two</value2></record>
    <record><value1>one</value1><value2>two</value2></record>
    </recordset>');

    $record = $xml->record[0];
    print_r ($record);

?>

ContentLicense: CC BY-SA 2.5


问:
How to re-populate select options for angular primeng dropdown

I have a form that has a dropdown using primeng components like below:

```<code>    <p-dropdown
          [style]="{'width': '100%', 'border': 'none'}"
          [options]="categories | toSelectItem"
          name="product.category.id"
          class="primeng-custom-dropdown">
               <ng-template let-category pTemplate="item">
                   <div style="position: relative;">
                     <img src="{{category.image}}" style="width:24px;margin: 0 10px 0"/>
                     <div style="font-size:14px;display:inline;">{{category.label}}</div>
                   </div>
              </ng-template>
   </p-dropdown>
</code>```

When the form is already loaded and categories are already shown, I have another component in the form that adds a new category. I would also like to have that new category added to the primeng dropdown.

my ts component looks like below:

```<code>export class ProductFormComponent implements OnInit {
 categories: Category[];
 constructor(
   private api: ApiService
 ) {}

   ngOnInit() {
     this.getCategories();
   }

   getCategories(): void {
      this.api.getCategories()
        .subscribe(categories => {
          this.categories = categories;
       });
   }
}
</code>```

When I call the getCategories() again in a separate function, the list of categories in the dropdown doesn't seem to get the updated list. How do I make the list categories in the primeng dropdown component be updated as well?

答:
As per @Chautran comment. I subscribed to the dialog which adds the new category and return the created category to the main component where the dialog is triggered </p>

```<code>addCategory() {
  let dialogRef = this.dialog.open(CategoryFormDialogComponent, {
    position: {
      top: '80px',
    }
  });
  dialogRef.afterClosed().subscribe(category => {
    this.categories.push(category); // As per @Chautran
    this.getCategories();
  });
}
</code>```

Body:
I have a form that has a dropdown using primeng components like below:

               <ng-template let-category pTemplate="item">

{{category.label}}

              </ng-template>

When the form is already loaded and categories are already shown, I have another component in the form that adds a new category. I would also like to have that new category added to the primeng dropdown.

my ts component looks like below:

export class ProductFormComponent implements OnInit {
 categories: Category[];
 constructor(
   private api: ApiService
 ) {}

   ngOnInit() {
     this.getCategories();
   }

   getCategories(): void {
      this.api.getCategories()
        .subscribe(categories => {
          this.categories = categories;
       });
   }
}

When I call the getCategories() again in a separate function, the list of categories in the dropdown doesn't seem to get the updated list. How do I make the list categories in the primeng dropdown component be updated as well?

Body:
As per @Chautran comment. I subscribed to the dialog which adds the new category and return the created category to the main component where the dialog is triggered

addCategory() {
  let dialogRef = this.dialog.open(CategoryFormDialogComponent, {
    position: {
      top: '80px',
    }
  });
  dialogRef.afterClosed().subscribe(category => {
    this.categories.push(category); // As per @Chautran
    this.getCategories();
  });
}


问:
How do I sort a bunch of letters and their corresponding frequencies from a string?
I am trying to write a function that can analyze a string and print the letters in the string and their corresponding frequencies. This part isn't too much of a challenge because I can just use ascii_lowercase to sort through the string then the count() method available in ascii. The difficult part is sorting the frequencies so that the most frequent letter is the beginning, and the least frequent is at the end. Here is what I have written so far:

```<code>def analyze(codebook):
lst = []
tmp = []
for c in ascii_lowercase:
   count = codebook.count(c)
   print("('%s', %d)" % (c.upper(), count), end=" ")
   lst.append(count)
   tmp.append(c)
lst.sort()
lst.reverse()
print(lst)
print(tmp)
</code>```

All this does is print the letter and it's corresponding frequencies in the order of the alphabet. Here is an example of the string that I am using:

```<code>pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq
</code>```

And here is an example of my desired output:

```<code>('Q', 10) ('W', 9) ('E', 8) ('R', 7) ('T', 6) ('Y', 5) ('U', 4) ('I', 3)

('O', 2) ('P', 1) ('A', 0) ('B', 0) ('C', 0) ('D', 0) ('F', 0) ('G', 0)

('H', 0) ('J', 0) ('K', 0) ('L', 0) ('M', 0) ('N', 0) ('S', 0) ('V', 0)

('X', 0) ('Z', 0)
</code>```

I have also tried using collections; however, that got confusing very quickly. Any help would be appreciated!

答:
Another solution is follows:

```<code>import collections
st = "pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq"
my_list = list(collections.Counter(list(st)).items())
my_list.sort(key=lambda x: x[1], reverse=True)
print(my_list)
</code>```

output:

```<code>[('q', 10), ('w', 9), ('e', 8), ('r', 7), ('t', 6), ('y', 5), ('u', 4), ('i', 3), ('o', 2), ('p', 1)]
</code>```

Body:
I am trying to write a function that can analyze a string and print the letters in the string and their corresponding frequencies. This part isn't too much of a challenge because I can just use ascii_lowercase to sort through the string then the count() method available in ascii. The difficult part is sorting the frequencies so that the most frequent letter is the beginning, and the least frequent is at the end. Here is what I have written so far:

def analyze(codebook):
lst = []
tmp = []
for c in ascii_lowercase:
   count = codebook.count(c)
   print("('%s', %d)" % (c.upper(), count), end=" ")
   lst.append(count)
   tmp.append(c)
lst.sort()
lst.reverse()
print(lst)
print(tmp)

All this does is print the letter and it's corresponding frequencies in the order of the alphabet. Here is an example of the string that I am using:

pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq

And here is an example of my desired output:

('Q', 10) ('W', 9) ('E', 8) ('R', 7) ('T', 6) ('Y', 5) ('U', 4) ('I', 3)

('O', 2) ('P', 1) ('A', 0) ('B', 0) ('C', 0) ('D', 0) ('F', 0) ('G', 0)

('H', 0) ('J', 0) ('K', 0) ('L', 0) ('M', 0) ('N', 0) ('S', 0) ('V', 0)

('X', 0) ('Z', 0)

I have also tried using collections; however, that got confusing very quickly. Any help would be appreciated!

Body:
Another solution is follows:

import collections
st = "pooiiiuuuuyyyyyttttttrrrrrrreeeeeeeewwwwwwwwwqqqqqqqqqq"
my_list = list(collections.Counter(list(st)).items())
my_list.sort(key=lambda x: x[1], reverse=True)
print(my_list)

output:

[('q', 10), ('w', 9), ('e', 8), ('r', 7), ('t', 6), ('y', 5), ('u', 4), ('i', 3), ('o', 2), ('p', 1)]


问:
How to create event in MYSQL database?
I have no idea to create an event in MYSQL database.

I want to create an event that updates a field from 1 to 0. By default value of a field is 0 in the database but after executing some query I set it back to 1 according to the requirement. The problem is I want to set 1 to 0 on 1st of every month. How can I do this through an event?

I will be thankful if you suggest me the solution as I am new in the field of MYSQL database and PHP.

答:
You can create mysql event using simple sql code

```<code>    DELIMITER $$
    CREATE EVENT eventname
    ON SCHEDULE EVERY '1' MONTH
    STARTS '2018-02-01 00:00:00'
    DO
    BEGIN
     -- your logic and code
    END$$

DELIMITER ;
</code>```

Event will start working on '2018-02-01' at '00:00:00' (datetime must be in a future date time).

Do not forget enable global event scheduling thread -

```<code>SET GLOBAL event_scheduler = 1;
</code>```

Title: How to create event in MYSQL database?

Body:
You can create mysql event using simple sql code

    DELIMITER $$
    CREATE EVENT eventname
    ON SCHEDULE EVERY '1' MONTH
    STARTS '2018-02-01 00:00:00'
    DO
    BEGIN
     -- your logic and code
    END$$

DELIMITER ;

Event will start working on '2018-02-01' at '00:00:00' (datetime must be in a future date time).

Do not forget enable global event scheduling thread -

SET GLOBAL event_scheduler = 1;


问:
Struggling with trying to get image from camera to upload to Firebase - java.lang.IllegalStateException: uri must not be null
I've been reading through every post on here relating (as well as the documentation) to this topic and for some reason I just can't get it working. I get to the point where the user takes a photo, hits the checkmark to continue, and then the app crashes.

Specifically at this line:

```<code>val filepath = mFirebaseStorage.child("Users").child(prefs.UID).child(uri.lastPathSegment)
</code>```

My code looks something like this:

onLaunchCamera - called when user selects "Camera" from alert box

```<code>private fun onLaunchCamera() {
    val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    //Ensure there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(packageManager) != null) {
        var photoFile: File? = null
        try {
            photoFile = createImageFile()
        } catch (e: IOException) {
            //log error
            Log.e(TAG, e.toString())
        }
        //continue only if file was successfully created!
        if (photoFile != null) {
            val photoURI = FileProvider.getUriForFile(this,
                    "com.android.projectrc.fileprovider",
                    photoFile)
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
        }
    }
}
</code>```

onActivityResult

```<code>override protected fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        val progressDialog = indeterminateProgressDialog("Uploading...")
        progressDialog.show()
        Log.d(TAG,"URI:: ${photoURI}")
        val uri = data.data

        val filePath = mFirebaseStorage.child("Users").child(prefs.UID)
                .child("ProfileImage").child(uri.lastPathSegment)
        filePath.putFile(photoURI!!).addOnSuccessListener(OnSuccessListener <UploadTask.TaskSnapshot >() {
            fun onSuccess(taskSnapshot : UploadTask.TaskSnapshot) {
                toast("Upload Successful!")
                progressDialog.dismiss()
            }
        }).addOnFailureListener(OnFailureListener () {
            fun onFailure(e : Exception) {
                Log.e(TAG, e.toString())
                toast("Upload Failed!")
            }
        });
        //val bundle = data.extras
    }
}
</code>```

createImageFile

```<code>private fun createImageFile(): File {
    // Create an image file name
    val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)
    val imageFileName = "JPEG_" + timeStamp + "_";
    val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
    val image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.absolutePath;
    return image
}
</code>```

AndroidManifest.xml

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE" />

<application
    android:name=".App"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.android.projectrc.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>
</code>```

files_path.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/com.android.projectrc/files/Pictures" />
</paths>
</code>```

Even photoURI shows up null when the console outputs it - I'm at quite a loss and would appreciate any help!

答:
The answer to this related question explains that when a URI is passed as EXTRA_OUTPUT on the ACTION_IMAGE_CAPTURE intent, the URI is not returned as data on the intent parameter to onActivityResult().

This means you must save the URI in a class variable when it is generated so that it is available in onActivityResult().  It appears you already have photoURI declared as a class variable and that you intended to define it's value with this code in onLaunchCamera():

```<code>        val photoURI = FileProvider.getUriForFile(this,
                "com.android.projectrc.fileprovider",
                photoFile)
</code>```

But the val is creating a new instance of photoURI and the value is not stored in the class field as you want.  Remove val.

Body:
I've been reading through every post on here relating (as well as the documentation) to this topic and for some reason I just can't get it working. I get to the point where the user takes a photo, hits the checkmark to continue, and then the app crashes.

Specifically at this line:

val filepath = mFirebaseStorage.child("Users").child(prefs.UID).child(uri.lastPathSegment)

My code looks something like this:

onLaunchCamera - called when user selects "Camera" from alert box

private fun onLaunchCamera() {
    val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    //Ensure there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(packageManager) != null) {
        var photoFile: File? = null
        try {
            photoFile = createImageFile()
        } catch (e: IOException) {
            //log error
            Log.e(TAG, e.toString())
        }
        //continue only if file was successfully created!
        if (photoFile != null) {
            val photoURI = FileProvider.getUriForFile(this,
                    "com.android.projectrc.fileprovider",
                    photoFile)
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
        }
    }
}

onActivityResult

override protected fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        val progressDialog = indeterminateProgressDialog("Uploading...")
        progressDialog.show()
        Log.d(TAG,"URI:: ${photoURI}")
        val uri = data.data

        val filePath = mFirebaseStorage.child("Users").child(prefs.UID)
                .child("ProfileImage").child(uri.lastPathSegment)
        filePath.putFile(photoURI!!).addOnSuccessListener(OnSuccessListener <UploadTask.TaskSnapshot >() {
            fun onSuccess(taskSnapshot : UploadTask.TaskSnapshot) {
                toast("Upload Successful!")
                progressDialog.dismiss()
            }
        }).addOnFailureListener(OnFailureListener () {
            fun onFailure(e : Exception) {
                Log.e(TAG, e.toString())
                toast("Upload Failed!")
            }
        });
        //val bundle = data.extras
    }
}

createImageFile

private fun createImageFile(): File {
    // Create an image file name
    val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US)
    val imageFileName = "JPEG_" + timeStamp + "_";
    val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
    val image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.absolutePath;
    return image
}

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE" />

<application
    android:name=".App"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.android.projectrc.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>

files_path.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/com.android.projectrc/files/Pictures" />
</paths>

Even photoURI shows up null when the console outputs it - I'm at quite a loss and would appreciate any help!

Body:
The answer to this related question explains that when a URI is passed as EXTRA_OUTPUT on the ACTION_IMAGE_CAPTURE intent, the URI is not returned as data on the intent parameter to onActivityResult().

This means you must save the URI in a class variable when it is generated so that it is available in onActivityResult().  It appears you already have photoURI declared as a class variable and that you intended to define it's value with this code in onLaunchCamera():

        val photoURI = FileProvider.getUriForFile(this,
                "com.android.projectrc.fileprovider",
                photoFile)

But the val is creating a new instance of photoURI and the value is not stored in the class field as you want.  Remove val.


问:
Angular injector error on component downgrading from v5 or v4 to angularJS
I've created simple angular5 component HelloComponent:

```<code>var HelloComponent = function () {
};

HelloComponent.annotations = [
  new ng.core.Component({
    selector: 'hello-world',
    template: 'Hello World!'
  })
];
</code>```

Next I tried to use this component in my angularJS directive like:

```<code>angular.module("app", [])
.directive("helloWorld", ng.upgrade.static.downgradeComponent(HelloComponent))
</code>```

But on running this script I getting this error:

Error: [$injector:unpr] Unknown provider: $$angularLazyModuleRefProvider <- $$angularLazyModuleRef
  http://errors.angularjs.org/1.6.5/$injector/unpr?p0=%24%24angularLazyModuleRefProvider%20%3C-%20%24%24angularLazyModuleRef

See simple example with angular 5 and angularJS: http://plnkr.co/edit/dQJ2tgV2MuInT41ucjq1

How to fix this ?

ADDITIONAL INFO

Example for downgrading component from v4 to v1 also exists: https://hackernoon.com/angular-v4-hybrid-upgrade-application-73d5afba1e01

But when I trying to remake my app with this post, im getting another error:

Unknown provider: $$angularInjectorProvider

See example for v4: http://plnkr.co/edit/9Oxy0QeSg1FYve0cjGYw

Same example for v5 returns old error:

Unknown provider: $$angularLazyModuleRefProvider

See example for v5: http://plnkr.co/edit/eZScm8U41mGuuHJMjApV

答:
You are missing to include something. May be you are not providing the correct path for script.

You can create a new script file, add the script files data in it and add the correct path in the src property.

The below code is working perfectly fine for me.

```<code><!DOCTYPE html>
<html ng-app="app">
<head>
    <script data-semver="1.6.5" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
    <script src="https://unpkg.com/core-js@2.4.1/client/shim.min.js"></script>
    <script src="https://unpkg.com/zone.js@0.6.21/dist/zone.min.js"></script>
    <script src="https://unpkg.com/rxjs@5.0.0-beta.12/bundles/Rx.min.js"></script>
    <script src="https://npmcdn.com/@angular/core@5.0.0/bundles/core.umd.js"></script>
    <script src="https://npmcdn.com/@angular/common@5.0.0/bundles/common.umd.js"></script>
    <script src="https://npmcdn.com/@angular/platform-browser@5.0.0/bundles/platform-browser.umd.js"></script>
    <script src="https://npmcdn.com/@angular/compiler@5.0.0/bundles/compiler.umd.js"></script>
    <script src="https://npmcdn.com/@angular/platform-browser-dynamic@5.0.0/bundles/platform-browser-dynamic.umd.js"></script>
    <script src="https://npmcdn.com/@angular/upgrade@5.0.0/bundles/upgrade-static.umd.js"></script>
    <link rel="stylesheet" href="style.css" />
    <!--<script src="../NewFolder8/script.js"></script>-->
    <script>
        var HelloComponent = function () {
        };

        HelloComponent.annotations = [
          new ng.core.Component({
              selector: 'hello-world',
              template: 'Hello World!'
          })
        ];

        angular.module("app", [])
        .directive("helloWorld", ng.upgrade.static.downgradeComponent(HelloComponent))
    </script>
</head>
<body>
    <h1>Hello Plunker!</h1>
    <hello-world></hello-world>
</body>
</html>
</code>```

Body:
I've created simple angular5 component HelloComponent:

var HelloComponent = function () {
};

HelloComponent.annotations = [
  new ng.core.Component({
    selector: 'hello-world',
    template: 'Hello World!'
  })
];

Next I tried to use this component in my angularJS directive like:

angular.module("app", [])
.directive("helloWorld", ng.upgrade.static.downgradeComponent(HelloComponent))

But on running this script I getting this error:

Error: [$injector:unpr] Unknown provider: $$angularLazyModuleRefProvider <- $$angularLazyModuleRef
  http://errors.angularjs.org/1.6.5/$injector/unpr?p0=%24%24angularLazyModuleRefProvider%20%3C-%20%24%24angularLazyModuleRef

See simple example with angular 5 and angularJS: http://plnkr.co/edit/dQJ2tgV2MuInT41ucjq1

How to fix this ?

ADDITIONAL INFO

Example for downgrading component from v4 to v1 also exists: https://hackernoon.com/angular-v4-hybrid-upgrade-application-73d5afba1e01

But when I trying to remake my app with this post, im getting another error:

Unknown provider: $$angularInjectorProvider

See example for v4: http://plnkr.co/edit/9Oxy0QeSg1FYve0cjGYw

Same example for v5 returns old error:

Unknown provider: $$angularLazyModuleRefProvider

See example for v5: http://plnkr.co/edit/eZScm8U41mGuuHJMjApV

Body:
You are missing to include something. May be you are not providing the correct path for script.

You can create a new script file, add the script files data in it and add the correct path in the src property.

The below code is working perfectly fine for me.

<!DOCTYPE html>
<html ng-app="app">
<head>
    <script data-semver="1.6.5" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
    <script src="https://unpkg.com/core-js@2.4.1/client/shim.min.js"></script>
    <script src="https://unpkg.com/zone.js@0.6.21/dist/zone.min.js"></script>
    <script src="https://unpkg.com/rxjs@5.0.0-beta.12/bundles/Rx.min.js"></script>
    <script src="https://npmcdn.com/@angular/core@5.0.0/bundles/core.umd.js"></script>
    <script src="https://npmcdn.com/@angular/common@5.0.0/bundles/common.umd.js"></script>
    <script src="https://npmcdn.com/@angular/platform-browser@5.0.0/bundles/platform-browser.umd.js"></script>
    <script src="https://npmcdn.com/@angular/compiler@5.0.0/bundles/compiler.umd.js"></script>
    <script src="https://npmcdn.com/@angular/platform-browser-dynamic@5.0.0/bundles/platform-browser-dynamic.umd.js"></script>
    <script src="https://npmcdn.com/@angular/upgrade@5.0.0/bundles/upgrade-static.umd.js"></script>
    <link rel="stylesheet" href="style.css" />
    <!--<script src="../NewFolder8/script.js"></script>-->
    <script>
        var HelloComponent = function () {
        };

        HelloComponent.annotations = [
          new ng.core.Component({
              selector: 'hello-world',
              template: 'Hello World!'
          })
        ];

        angular.module("app", [])
        .directive("helloWorld", ng.upgrade.static.downgradeComponent(HelloComponent))
    </script>
</head>
<body>
    <h1>Hello Plunker!</h1>
    <hello-world></hello-world>
</body>
</html>


问:
Find empty strings in elasticsearch
I'm trying to _search documents that has some specific value in the field.

```<code>{
  "query": {
      "bool": {
        "must": [
         {"field": {"advs.status": "warn"}}
       ]
      }
  }
}
</code>```

That works find. But when I'm trying to find documents that has empty string in that field, I get this error:

```<code>ParseException[Cannot parse '' ...
</code>```

and then - long list of what was expected instead of empty string.

I try this query:

```<code>{
  "query": {
    "bool": {
        "must": [
            {"term": {"advs.status": ""}}
         ]
        }
  }
}
</code>```

It doesn't fails but finds nothing. It works for non empty strings instead. How am I supposed to do this?

My mapping for this type looks exactly like this:

```<code>{
    "reports": {
        "dynamic": "false",
        "_ttl": {
            "enabled": true,
            "default": 7776000000
        },
        "properties": {
            "@fields": {
                "dynamic": "true",
                "properties": {
                    "upstream_status": {
                        "type": "string"
                    }
                }
            },
            "advs": {
                "properties": {
                    "status": {
                        "type": "string",
                        "store": "yes"
                    }
                }
            },
            "advs.status": {
                "type": "string",
                "store": "yes"
            }
        }
    }
}
</code>```

答:
You can try this temporary solution which works but isn't optimal - https://github.com/elastic/elasticsearch/issues/7515</p>

```<code>PUT t/t/1
{
"textContent": ""
}

PUT t/t/2
{
 "textContent": "foo"
}

GET t/t/_search
{
 "query": {
  "bool": {
   "must": [
    {
      "exists": {
        "field": "textContent"
      }
    }
  ],
  "must_not": [
    {
      "wildcard": {
        "textContent": "*"
      }
     }
   ]
  }
 }
}
</code>```

Title: Find empty strings in elasticsearch

Body:
I'm trying to _search documents that has some specific value in the field.

{
  "query": {
      "bool": {
        "must": [
         {"field": {"advs.status": "warn"}}
       ]
      }
  }
}

That works find. But when I'm trying to find documents that has empty string in that field, I get this error:

ParseException[Cannot parse '' ...

and then - long list of what was expected instead of empty string.

I try this query:

{
  "query": {
    "bool": {
        "must": [
            {"term": {"advs.status": ""}}
         ]
        }
  }
}

It doesn't fails but finds nothing. It works for non empty strings instead. How am I supposed to do this?

My mapping for this type looks exactly like this:

{
    "reports": {
        "dynamic": "false",
        "_ttl": {
            "enabled": true,
            "default": 7776000000
        },
        "properties": {
            "@fields": {
                "dynamic": "true",
                "properties": {
                    "upstream_status": {
                        "type": "string"
                    }
                }
            },
            "advs": {
                "properties": {
                    "status": {
                        "type": "string",
                        "store": "yes"
                    }
                }
            },
            "advs.status": {
                "type": "string",
                "store": "yes"
            }
        }
    }
}

Body:
You can try this temporary solution which works but isn't optimal - https://github.com/elastic/elasticsearch/issues/7515

PUT t/t/1
{
"textContent": ""
}

PUT t/t/2
{
 "textContent": "foo"
}

GET t/t/_search
{
 "query": {
  "bool": {
   "must": [
    {
      "exists": {
        "field": "textContent"
      }
    }
  ],
  "must_not": [
    {
      "wildcard": {
        "textContent": "*"
      }
     }
   ]
  }
 }
}


问:
find a file using find command only in particular directories even though that file is present in other directories
I have a file named pqr.txt    This file, is present in many of the subdirectories, but i want to find only the ones whose path is ../../whatever/whatever/pqr/pqr.txt

I am doing this operation with find command using name option but how can i add this constarint that it has to find pqr.txt only in pqr directories?

Also i am passing name parameter as argument from command-line.

find . -name pqr.txt

答:
If you want to find only the pqr.txt that are in a directory named pqr,
you can use the -path option of find:

```<code>find . -path '*/pqr/pqr.txt'
</code>```

Body:
If you want to find only the pqr.txt that are in a directory named pqr,
you can use the -path option of find:

find . -path '*/pqr/pqr.txt'


问:
how to compare date with GETDATE() in sql server 2008
I have a stored procedure, which is used to insert some kind of information to table 'demotable', in that i have a field loginTime where datatype is dateTime.
i am using GETDATE() to get the current datetime, problem is i want to compare whether this GETDATE() is lower than 9:00 AM and then make it as 9:00AM, if not lower keep the output as it is without any changes. -using microsoft sql server 2008.

below is my sample stored procedure

```<code>         //Beg Stored Procedure Contents...

            insert into dbo.demoTable([loginTime],[nStatus]) values(GETDATE(),'1')

         //End
</code>```

答:
This query will check if the current time is before 9:00 AM, if no, it will keep whatever is the result of calling getdate(). Otherwise, it will make it 9:00 AM.

```<code>select iif(DATEPART(HOUR, GETDATE()) < 9,
           dateadd(hh, 9,  DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)),
           getdate())
</code>```

Body:
I have a stored procedure, which is used to insert some kind of information to table 'demotable', in that i have a field loginTime where datatype is dateTime.
i am using GETDATE() to get the current datetime, problem is i want to compare whether this GETDATE() is lower than 9:00 AM and then make it as 9:00AM, if not lower keep the output as it is without any changes. -using microsoft sql server 2008.

below is my sample stored procedure

         //Beg Stored Procedure Contents...

            insert into dbo.demoTable([loginTime],[nStatus]) values(GETDATE(),'1')

         //End

Body:
This query will check if the current time is before 9:00 AM, if no, it will keep whatever is the result of calling getdate(). Otherwise, it will make it 9:00 AM.

select iif(DATEPART(HOUR, GETDATE()) < 9,
           dateadd(hh, 9,  DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)),
           getdate())


问:
What is the best way to delete a component with CLI
I tried using "ng destroy component foo" and it tells me "The destroy command is not supported by Angular-CLI"

How do we properly delete components with Angular CLI?

答:
First of all, remove component folder, which you have to delete
and then remove its entries which you have made in "ts" files.</p>


问:
How to save a web page into a HTML file with PowerShell or C#?
I have the following link , and when I open the link via Chrome and then right-click the page and then choose "save as" to save the page into a HTML file (c:\temp\cu2.html)

After it is saved, I can open this cu2.html file with an HTML editor (say VS2015), and I can see
inside the file, there is  tag as seen below

However, if I open the link with IE11 (instead of Chrome), and then save the same page as HTML file, I cannot find this  tag at all. Actually, the html file saved from IE11 is the same content as what I can extract with PowerShell script below.

```<code>#Requires -version 4.0
$url = 'https://support.microsoft.com/en-us/help/4052574/cumulative-update-2-for-sql-server-2017';

$wr = Invoke-WebRequest $url;
$wr.RawContent.contains('<table') # returns false

$wr.RawContent | out-file -FilePath c:\temp\cu2_ps.html -Force; #same as the file saved from the webpage to html file in IE
</code>```

So my question is:

Why is a web page saved (as html file) in Chrome is different from that in IE?

How can I use PowerShell(or C#) to save such web page into a HTML file (same as the file saved in Chrome)?

答:
The pages uses AngularJS and also jQuery. It means some contents will be loaded after document ready. So when you send the request using Invoke-WebRequest, you only receive the original content of the page. Other contents will be loaded after a while.

To solve the problem, you can automate IE to get expected result. It's enough to wait fr the page to get ready and also wait a bit to run AngularJs logic and download required content, then get content of document element:

```<code>$ie = new-object -ComObject "InternetExplorer.Application"
$url = "https://support.microsoft.com/en-us/help/4052574/cumulative-update-2-for-sql-server-2017"
$ie.silent = $true
$ie.navigate($url)
while($ie.Busy) { Start-Sleep -Milliseconds 100 }
Start-Sleep 10
$ie.Document.documentElement.innerHTML > "C:\Tempfiles\output.html"
$ie.Stop()
$ie.Quit()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following link , and when I open the link via Chrome and then right-click the page and then choose "save as" to save the page into a HTML file (c:\temp\cu2.html)

After it is saved, I can open this cu2.html file with an HTML editor (say VS2015), and I can see
inside the file, there is  tag as seen below

However, if I open the link with IE11 (instead of Chrome), and then save the same page as HTML file, I cannot find this  tag at all. Actually, the html file saved from IE11 is the same content as what I can extract with PowerShell script below.

#Requires -version 4.0
$url = 'https://support.microsoft.com/en-us/help/4052574/cumulative-update-2-for-sql-server-2017';

$wr = Invoke-WebRequest $url;
$wr.RawContent.contains('<table') # returns false

$wr.RawContent | out-file -FilePath c:\temp\cu2_ps.html -Force; #same as the file saved from the webpage to html file in IE

So my question is:

Why is a web page saved (as html file) in Chrome is different from that in IE?

How can I use PowerShell(or C#) to save such web page into a HTML file (same as the file saved in Chrome)?

Body:
The pages uses AngularJS and also jQuery. It means some contents will be loaded after document ready. So when you send the request using Invoke-WebRequest, you only receive the original content of the page. Other contents will be loaded after a while.

To solve the problem, you can automate IE to get expected result. It's enough to wait fr the page to get ready and also wait a bit to run AngularJs logic and download required content, then get content of document element:

$ie = new-object -ComObject "InternetExplorer.Application"
$url = "https://support.microsoft.com/en-us/help/4052574/cumulative-update-2-for-sql-server-2017"
$ie.silent = $true
$ie.navigate($url)
while($ie.Busy) { Start-Sleep -Milliseconds 100 }
Start-Sleep 10
$ie.Document.documentElement.innerHTML > "C:\Tempfiles\output.html"
$ie.Stop()
$ie.Quit()


问:
Get return value from c# function and display in html
I am trying to display the count of a table from my database. I have a function that returns the count of the rows. I'm new to c# and I'm not sure how to call the function in my html so that it displays the returned value.

Here's my c# function that I got from How to count the number of rows from sql table in c#?:

```<code>public int Get_Count(object sender, EventArgs e)
{
    {
        string stmt = "SELECT COUNT(*) FROM dbo.listing";
        int count = 0;

        using (SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"))
        {
            using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
            {
                thisConnection.Open();
                count = (int)cmdCount.ExecuteScalar();
            }
        }
        return count;
    }
}
</code>```

And here's the HTML line that I would like to display the returned count:

```<code><p class="lead text-muted block text-center"><strong>Get_Count()</strong> results found</p>
</code>```

答:
in page load event

```<code>     protected void Page_Load(object sender, EventArgs e)
    {
        this.DataBind();
    }

    public int Get_Count()
   {
      {
          string stmt = "SELECT COUNT(*) FROM dbo.listing";
          int count = 0;

          using (SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"))
            {
               using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
                 {
                    thisConnection.Open();
                    count = (int)cmdCount.ExecuteScalar();
                 }
           }
          return count;
       }
    }
</code>```

then

```<code>    <p class="lead text-muted block text-center"><strong><%# Get_Count() %></strong> results found</p>
</code>```

Body:
I am trying to display the count of a table from my database. I have a function that returns the count of the rows. I'm new to c# and I'm not sure how to call the function in my html so that it displays the returned value.

Here's my c# function that I got from How to count the number of rows from sql table in c#?:

public int Get_Count(object sender, EventArgs e)
{
    {
        string stmt = "SELECT COUNT(*) FROM dbo.listing";
        int count = 0;

        using (SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"))
        {
            using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
            {
                thisConnection.Open();
                count = (int)cmdCount.ExecuteScalar();
            }
        }
        return count;
    }
}

And here's the HTML line that I would like to display the returned count:

Get_Count() results found

Body:
in page load event

     protected void Page_Load(object sender, EventArgs e)
    {
        this.DataBind();
    }

    public int Get_Count()
   {
      {
          string stmt = "SELECT COUNT(*) FROM dbo.listing";
          int count = 0;

          using (SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"))
            {
               using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
                 {
                    thisConnection.Open();
                    count = (int)cmdCount.ExecuteScalar();
                 }
           }
          return count;
       }
    }

then

    <p class="lead text-muted block text-center"><strong><%# Get_Count() %></strong> results found</p>


问:
Filtering data in NLTK
Following the NLTK documentation, here: http://www.nltk.org/howto/twitter.html#Extracting-Parts-of-a-Tweet

I am trying to filter tweets by the boolean tags retweeted and possibly_sensitive status. My example below only tries for the retweeted tag.

The output contains only the following "id,text,retweeted.bool"

```<code>input_file = "/blah/blah/blah/tweets.20171120-202012.json"
from nltk.twitter.common import json2csv_entities
with open(input_file) as fp:
    json2csv_entities(fp, 'tweets.20171120-202012.csv',
                        ['id', 'text'], 'retweeted',['bool'])
</code>```

The .json file is a newline separated json file with a number of tweet objects in it (which vary--some tweet objects do not have the possibly_sensitive tag, which only shows up when a tweet has a link). I suspect that this may be contributing to the problem.

Any ideas as to how I can get this json2csv_entities method to pull the retweeted and possibly_sensitive tags in?

Thanks in advance for your thoughts!

A sample of the input file is not practical to post here because it so long, but structurally it looks looks something like the following:

```<code>{"id":12312312, "text": "RT I love to eat bagels", "retweeted": true, "possibly_sensitive": false}
{"id":34523454, "text": "Here's a link to my sketchy website: http://wefewfwef", "retweeted": false, "possibly_sensitive": true}
</code>```

答:
To read a line-separated JSON file line by line read each line of the file in as a string using the loads() method in python (load String).

I then wrote the following code to get at the keys I was looking for:

```<code>with open(input_file) as tweets_file:
    for line in tweets_file:
        tweet = json.loads(line)
        # try catch handles for possibly_sensitive not being in the tweet metadata..
        try:
            sensitive = tweet['possibly_sensitive']
        except KeyError:
            sensitive = None
</code>```

This worked wonderfully.

Title: Filtering data in NLTK

Body:
Following the NLTK documentation, here: http://www.nltk.org/howto/twitter.html#Extracting-Parts-of-a-Tweet

I am trying to filter tweets by the boolean tags retweeted and possibly_sensitive status. My example below only tries for the retweeted tag.

The output contains only the following "id,text,retweeted.bool"

input_file = "/blah/blah/blah/tweets.20171120-202012.json"
from nltk.twitter.common import json2csv_entities
with open(input_file) as fp:
    json2csv_entities(fp, 'tweets.20171120-202012.csv',
                        ['id', 'text'], 'retweeted',['bool'])

The .json file is a newline separated json file with a number of tweet objects in it (which vary--some tweet objects do not have the possibly_sensitive tag, which only shows up when a tweet has a link). I suspect that this may be contributing to the problem.

Any ideas as to how I can get this json2csv_entities method to pull the retweeted and possibly_sensitive tags in?

Thanks in advance for your thoughts!

A sample of the input file is not practical to post here because it so long, but structurally it looks looks something like the following:

{"id":12312312, "text": "RT I love to eat bagels", "retweeted": true, "possibly_sensitive": false}
{"id":34523454, "text": "Here's a link to my sketchy website: http://wefewfwef", "retweeted": false, "possibly_sensitive": true}

Body:
To read a line-separated JSON file line by line read each line of the file in as a string using the loads() method in python (load String).

I then wrote the following code to get at the keys I was looking for:

with open(input_file) as tweets_file:
    for line in tweets_file:
        tweet = json.loads(line)
        # try catch handles for possibly_sensitive not being in the tweet metadata..
        try:
            sensitive = tweet['possibly_sensitive']
        except KeyError:
            sensitive = None

This worked wonderfully.


问:
How Upload large files to Onedrive using PHP-Curl
I need to upload file size grater than 4MB to onedrive account. I am trying with PHP and curl for this. Is anyone tried for this option, Please help me out to solve this issue.</p>

答:
$url='https://graph.microsoft.com/v1.0/me/drive/root:/filename:/createUploadSession';

```<code>    $data= '{}';
    $header = array('Content-Type: json',
        "Cache-Control: no-cache",
        "Pragma: no-cache",
        "Authorization: bearer {Access Token}");
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
</code>```

get the uploadURL from the result,

```<code>    $graph_url = $result['uploadUrl'];
    $fragSize = 320 * 1024;
    $file = file_get_contents($filename_location);
    $fileSize = strlen($file);
    $numFragments = ceil($fileSize / $fragSize);
    $bytesRemaining = $fileSize;
    $i = 0;
    $ch = curl_init($graph_url);
    while ($i < $numFragments) {
        $chunkSize = $numBytes = $fragSize;
        $start = $i * $fragSize;
        $end = $i * $fragSize + $chunkSize - 1;
        $offset = $i * $fragSize;
        if ($bytesRemaining < $chunkSize) {
            $chunkSize = $numBytes = $bytesRemaining;
            $end = $fileSize - 1;
        }
        if ($stream = fopen($filename_location, 'r')) {
            // get contents using offset
            $data = stream_get_contents($stream, $chunkSize, $offset);
            fclose($stream);
        }

        $content_range = " bytes " . $start . "-" . $end . "/" . $fileSize;
        $headers = array(
            "Content-Length: $numBytes",
            "Content-Range:$content_range"
        );
        curl_setopt($ch, CURLOPT_URL, $graph_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, constant('CURL_SSL_VERIFYPEER_STATUS'));
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $server_output = curl_exec($ch);
        $info = curl_getinfo($ch);

        $bytesRemaining = $bytesRemaining - $chunkSize;
        $i++;
    }
</code>```

And when you passing the last set of data it should be the correct data bytes. Otherwise it will fail the upload session.

Body:
$url='https://graph.microsoft.com/v1.0/me/drive/root:/filename:/createUploadSession';

    $data= '{}';
    $header = array('Content-Type: json',
        "Cache-Control: no-cache",
        "Pragma: no-cache",
        "Authorization: bearer {Access Token}");
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

get the uploadURL from the result,

    $graph_url = $result['uploadUrl'];
    $fragSize = 320 * 1024;
    $file = file_get_contents($filename_location);
    $fileSize = strlen($file);
    $numFragments = ceil($fileSize / $fragSize);
    $bytesRemaining = $fileSize;
    $i = 0;
    $ch = curl_init($graph_url);
    while ($i < $numFragments) {
        $chunkSize = $numBytes = $fragSize;
        $start = $i * $fragSize;
        $end = $i * $fragSize + $chunkSize - 1;
        $offset = $i * $fragSize;
        if ($bytesRemaining < $chunkSize) {
            $chunkSize = $numBytes = $bytesRemaining;
            $end = $fileSize - 1;
        }
        if ($stream = fopen($filename_location, 'r')) {
            // get contents using offset
            $data = stream_get_contents($stream, $chunkSize, $offset);
            fclose($stream);
        }

        $content_range = " bytes " . $start . "-" . $end . "/" . $fileSize;
        $headers = array(
            "Content-Length: $numBytes",
            "Content-Range:$content_range"
        );
        curl_setopt($ch, CURLOPT_URL, $graph_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, constant('CURL_SSL_VERIFYPEER_STATUS'));
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $server_output = curl_exec($ch);
        $info = curl_getinfo($ch);

        $bytesRemaining = $bytesRemaining - $chunkSize;
        $i++;
    }

And when you passing the last set of data it should be the correct data bytes. Otherwise it will fail the upload session.


问:
Finding all subsets of a list in python
I need to create a function that will be passed a list and will create a new list with all the subsets of the the original list. I have to write it all from scratch, so no importing from itertools.

For Example:

the list given be like [1,2,3] and I want an output like

```<code>[[1],[2],[3],[1,2],[2,3],[1,3],[1,2,3],[]]
</code>```

答:
```<code>from itertools import combinations
s = set([1,2,3])
sum(map(lambda r: list(combinations(s, r)), range(1, len(s)+1)), [])
</code>```

Producing tuples value but it close enough for you.

Title: Finding all subsets of a list in python

Body:
I need to create a function that will be passed a list and will create a new list with all the subsets of the the original list. I have to write it all from scratch, so no importing from itertools.

For Example:

the list given be like [1,2,3] and I want an output like

[[1],[2],[3],[1,2],[2,3],[1,3],[1,2,3],[]]

Body:
from itertools import combinations
s = set([1,2,3])
sum(map(lambda r: list(combinations(s, r)), range(1, len(s)+1)), [])

Producing tuples value but it close enough for you.


问:
change type of input field with jQuery
<pre class="lang-js prettyprint-override"><code>$(document).ready(function() {
    // #login-box password field
    $('#password').attr('type', 'text');
    $('#password').val('Password');
});
</code>```

<p>This is supposed to change the <code>#password</code> input field (with <code>id="password"</code>) that is of <code>type</code> <code>password</code> to a normal text field, and then fill in the text “Password”.</p>

<p>It doesn’t work, though. Why?</p>

<p>Here is the form:</p>

<pre class="lang-html prettyprint-override"><code><form enctype="application/x-www-form-urlencoded" method="post" action="/auth/sign-in">
  <ol>
    <li>
      <div class="element">
        <input type="text" name="username" id="username" value="Prihlasovacie meno" class="input-text" />
      </div>
    </li>
    <li>
      <div class="element">
        <input type="password" name="password" id="password" value="" class="input-text" />
      </div>
    </li>
    <li class="button">
      <div class="button">
        <input type="submit" name="sign_in" id="sign_in" value="Prihlásiť" class="input-submit" />
      </div>
    </li>
  </ol>
</form>
</code>```

答:
This Worked for me.</p>

```<code>$('#newpassword_field').attr("type", 'text');
</code>```

Title: change type of input field with jQuery

Body:
$(document).ready(function() {
    // #login-box password field
    $('#password').attr('type', 'text');
    $('#password').val('Password');
});

This is supposed to change the #password input field (with id="password") that is of type password to a normal text field, and then fill in the text “Password”.

It doesn’t work, though. Why?

Here is the form:

<form enctype="application/x-www-form-urlencoded" method="post" action="/auth/sign-in">

        <input type="text" name="username" id="username" value="Prihlasovacie meno" class="input-text" />

        <input type="password" name="password" id="password" value="" class="input-text" />

        <input type="submit" name="sign_in" id="sign_in" value="Prihlásiť" class="input-submit" />

</form>

Body:
This Worked for me.

$('#newpassword_field').attr("type", 'text');


问:
Using C# to add columns to SQL server database not working
Whenever I call this function to run this query....

```<code>  public static void AddUsernameAndPassword()
    {

        SqlConnection connection = MedicalDB.EstConnection();
        connection.Open();

        string alterStatement = "ALTER TABLE PATIENT_TBL ADD USER_NAME VARCHAR(50) NULL," +
                                " PASSWORD VARCHAR(50) NULL";

        SqlCommand alterCommand =
            new SqlCommand(alterStatement, connection);
        alterCommand.ExecuteNonQuery();
        connection.Close();
    }
</code>```

through here

```<code> private void loginButton_Click(object sender, EventArgs e)
    {
        PatientDB.AddUsernameAndPassword();
        //getPatient(1);

        passTextBox.Text = patient.userName;

    }
</code>```

It tells me

Invalid column name 'USER_NAME'.

The properties are set accordingly. Please advise.

答:
USER_NAME is a function in SQL Server. So if you want to use it as a column name add square brackets to it.

Something like this, [USER_NAME]

Code

```<code>string alterStatement = "ALTER TABLE PATIENT_TBL ADD [USER_NAME] VARCHAR(50) NULL," +
                            " [PASSWORD] VARCHAR(50) NULL";
</code>```

And one more thing, never save password as plain text. Use proper encryptions.

Body:
Whenever I call this function to run this query....

  public static void AddUsernameAndPassword()
    {

        SqlConnection connection = MedicalDB.EstConnection();
        connection.Open();

        string alterStatement = "ALTER TABLE PATIENT_TBL ADD USER_NAME VARCHAR(50) NULL," +
                                " PASSWORD VARCHAR(50) NULL";

        SqlCommand alterCommand =
            new SqlCommand(alterStatement, connection);
        alterCommand.ExecuteNonQuery();
        connection.Close();
    }

through here

 private void loginButton_Click(object sender, EventArgs e)
    {
        PatientDB.AddUsernameAndPassword();
        //getPatient(1);

        passTextBox.Text = patient.userName;

    }

It tells me

Invalid column name 'USER_NAME'.

The properties are set accordingly. Please advise.

Body:
USER_NAME is a function in SQL Server. So if you want to use it as a column name add square brackets to it.

Something like this, [USER_NAME]

Code

string alterStatement = "ALTER TABLE PATIENT_TBL ADD [USER_NAME] VARCHAR(50) NULL," +
                            " [PASSWORD] VARCHAR(50) NULL";

And one more thing, never save password as plain text. Use proper encryptions.


问:
Why does my viewmodel name have to be 'model'?
I've been working with MVC for quite a while. I made a form to submit my data using an entity model and as per requirement had to add tags too so I updated the view and the actionmethod to use a viewmodel instead. Like this:

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PostwTagsVM post)
{
}
</code>```

Surprisingly, the model was null.I couldn't find out why but then decided to rename the object as below:

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PostwTagsVM model)
{
}
</code>```

Surprisingly, I get the data in the model now.
I know I can work like this but if i really needed to name by model object something else other than 'model'. Whats happening here?

答:
It does not have to be named model.

If in the first case, your model is null, its because your PostwTagsVM model contains a property named post.

The parameter can be named whatever you want, except that it cannot be the same name as one of the properties in your model.

The reason is that your form would be sending back a name/value pair that is (say) post=someValue. The DefaultModelBinder looks for a matching name, sets the value of the property named Post to someValue, but then also finds a parameter named post and tries to set that to someValue, which fails (because you cannot do PostwTagsVM post = "someValue";), and the model becomes null.

Body:
I've been working with MVC for quite a while. I made a form to submit my data using an entity model and as per requirement had to add tags too so I updated the view and the actionmethod to use a viewmodel instead. Like this:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PostwTagsVM post)
{
}

Surprisingly, the model was null.I couldn't find out why but then decided to rename the object as below:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PostwTagsVM model)
{
}

Surprisingly, I get the data in the model now.
I know I can work like this but if i really needed to name by model object something else other than 'model'. Whats happening here?


问:
Merge two Git repositories without breaking file history or releases
So I read this and it worked fine. But I also want to keep the releases from both repositories. Is it possible to do this?

Basically I have 2 repos, where repo 1 is an older version of repo 2. I want to clean up my GitHub to only have one.

答:
If by releases, you are refering to GitHub releases, those are based on a tag.

If you have merged the history of the two repos, following your link, the tags of the second repo have been preserved.

You can then fetch from that second original repo the release by its tag, and create a new one, for that same tag, this time in the new merged repo.

This has to be scripted, in order to repeat the process for all the tags/releases of the merged repo.


问:
Recursively cycle every path of an array
I have the following(json) object:

```<code>$obj = json_decode('{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}', true);
</code>```

I'm trying to figure out how to recursively travel through it so I can see all the different paths that is in the array.

It could be 4 separate echo's or a 4 line string. The > could be replaced with anything or nothing at all. If each line was echo'd separately or pushed to an array that would probably give the most flexibility.

```<code>Group1 - Blue - Round - (Harold, Arthur, Tom)
Group1 - Green - Round - (Harold)
Group1 - Green - Circle - (Todd, Mike)
Group2 - Blue - Round - (Peter)
</code>```

I can't wrap my head around it so any help would be appreciated.

I'm thinking I can somehow cycle through each like:

```<code>foreach($obj as $index => $value)
{
   // and then somehow do this until you reach an array?
}
</code>```

答:
Tested only on the given sample. But this should work if array levels are increased. I mainly use RecursiveIteratorIterator class functions

```<code>// Initialize RecursiveIteratorIterator
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($obj), RecursiveIteratorIterator::SELF_FIRST);
$paths = array(); // Paths storage
foreach ($iterator as $k => $v) { // Loop thru each iterator

    if (!$iterator->hasChildren()) { // Check if iterator hasChildren is false
        $innermost = $iterator->getSubIterator($iterator->getDepth()); // Get innermost child which is the array
        for ($p = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) { // Loop and push each path to the innermost array
            $p[] = $iterator->getSubIterator($i)->key();
        }
        array_pop($p); // Remove key
        $innermost = (array)$innermost; // Cast innermost to array
        $p[] = '(' . implode(', ', $innermost) . ')'; // push formatted innermost array to path
        $path = implode(' - ', $p); // implode the path
        $paths[] = $path; // store to list of paths array
    }

}

$paths = array_unique($paths); // remove exactly same paths

foreach ($paths as $value) {  // Loop and echo each path
    echo $value.'<br>';
}
</code>```

Output:- https://eval.in/915070

Body:
I have the following(json) object:

$obj = json_decode('{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}', true);

I'm trying to figure out how to recursively travel through it so I can see all the different paths that is in the array.

It could be 4 separate echo's or a 4 line string. The > could be replaced with anything or nothing at all. If each line was echo'd separately or pushed to an array that would probably give the most flexibility.

Group1 - Blue - Round - (Harold, Arthur, Tom)
Group1 - Green - Round - (Harold)
Group1 - Green - Circle - (Todd, Mike)
Group2 - Blue - Round - (Peter)

I can't wrap my head around it so any help would be appreciated.

I'm thinking I can somehow cycle through each like:

foreach($obj as $index => $value)
{
   // and then somehow do this until you reach an array?
}

Body:
Tested only on the given sample. But this should work if array levels are increased. I mainly use RecursiveIteratorIterator class functions

// Initialize RecursiveIteratorIterator
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($obj), RecursiveIteratorIterator::SELF_FIRST);
$paths = array(); // Paths storage
foreach ($iterator as $k => $v) { // Loop thru each iterator

    if (!$iterator->hasChildren()) { // Check if iterator hasChildren is false
        $innermost = $iterator->getSubIterator($iterator->getDepth()); // Get innermost child which is the array
        for ($p = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) { // Loop and push each path to the innermost array
            $p[] = $iterator->getSubIterator($i)->key();
        }
        array_pop($p); // Remove key
        $innermost = (array)$innermost; // Cast innermost to array
        $p[] = '(' . implode(', ', $innermost) . ')'; // push formatted innermost array to path
        $path = implode(' - ', $p); // implode the path
        $paths[] = $path; // store to list of paths array
    }

}

$paths = array_unique($paths); // remove exactly same paths

foreach ($paths as $value) {  // Loop and echo each path
    echo $value.'<br>';
}

Output:- https://eval.in/915070


问:
find by id in spring data jpa Base Repository
I'm trying to implement a generic findByIdsIn method in the BaseRepository of my Spring Data JPA class so that the functionality can be used by all the classes that implement that interface.
I'm pretty new to Spring Data JPA so I'm not sure if that is possible and how to implement it.

Here's the code I have so far. The findByIdsIn is the functionality I'd like to implement.

```<code>import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;

@NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends Repository<T, ID> {
    List<T> findAll( );
    Optional<T> findById(ID id);
    List<T> findByIdsIn(List<ID> ids); // This is the functionality I'd like to implement.
}
</code>```

Do you guys have any suggestions?
Many thanks!

答:
By default, SimpleJpaRepository is the implementations for basic repository operations. You should implement and write a class extending SimpleJpaRepository. As generic types to this implementation pass two types of parameter as passed in the interface SimpleJpaRepository. Below is a sample implementation of your requirement:

```<code>import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.io.Serializable;
import java.util.Optional;

public class BaseRepositoryImpl <T, ID extends Serializable>
        extends SimpleJpaRepository<T, ID>  implements BaseRepository<T, ID> {

    private final EntityManager entityManager;

    public BaseRepositoryImpl(Class<T> domainClass, EntityManager entityManager) {
        super(domainClass, entityManager);
        this.entityManager = entityManager;
    }

    @Override
   public  List<T> findByIdsIn(List<ID> ids) {
        List<T> entities = entityManager.createQuery(
        "FROM"+this.getDomainClass()+" WHERE id IN ("+CommonUtils.concat(ids,',')+")").getResultList(); // concatenation code is not tested hence u need to fix it
        return entities;
    }
}
</code>```

Also, you will need to override default implementation i.e.
 SimpleJpaRepository with your implementation i.e. BaseRepositoryImpl

```<code>import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import javax.persistence.EntityManager;
import java.io.Serializable;

public class BaseRepositoryFactoryBean<R extends JpaRepository<T, I>, T,
        I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I> {

    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
        return new BaseRepositoryFactory(entityManager);
    }

    private static class BaseRepositoryFactory<T, I extends Serializable>
            extends JpaRepositoryFactory {

        private final EntityManager entityManager;

        public BaseRepositoryFactory(EntityManager entityManager) {
            super(entityManager);
            this.entityManager = entityManager;
        }

        @Override
        protected Object getTargetRepository(RepositoryMetadata metadata) {
            return new BaseRepositoryImpl<T, I>((Class<T>) metadata.getDomainType(), entityManager);
        }

        @Override
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return BaseRepositoryImpl.class;
        }
    }
}
</code>```

Finally, configure your BaseRepositoryFactoryBean in Spring configuration by using @EnableJpaRepositories annotation and specifying your class as below. This will tell JPA which RepositoryFactoryBean to call and which in turn tell which JPA repository to use throughout and initialize it with its implementation using its Impl class.

```<code>@EnableJpaRepositories(basePackages = {"com.test.jpa.custom.repository"},
        repositoryFactoryBeanClass = BaseRepositoryFactoryBean.class)
class Configuration{}
</code>```

Now you could use BaseRepository and findByIdsIn will be available for usage throughout your application.

Body:
I'm trying to implement a generic findByIdsIn method in the BaseRepository of my Spring Data JPA class so that the functionality can be used by all the classes that implement that interface.
I'm pretty new to Spring Data JPA so I'm not sure if that is possible and how to implement it.

Here's the code I have so far. The findByIdsIn is the functionality I'd like to implement.

import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;

@NoRepositoryBean
public interface BaseRepository<T, ID extends Serializable> extends Repository<T, ID> {
    List<T> findAll( );
    Optional<T> findById(ID id);
    List<T> findByIdsIn(List<ID> ids); // This is the functionality I'd like to implement.
}

Do you guys have any suggestions?
Many thanks!

Body:
By default, SimpleJpaRepository is the implementations for basic repository operations. You should implement and write a class extending SimpleJpaRepository. As generic types to this implementation pass two types of parameter as passed in the interface SimpleJpaRepository. Below is a sample implementation of your requirement:

import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.io.Serializable;
import java.util.Optional;

public class BaseRepositoryImpl <T, ID extends Serializable>
        extends SimpleJpaRepository<T, ID>  implements BaseRepository<T, ID> {

    private final EntityManager entityManager;

    public BaseRepositoryImpl(Class<T> domainClass, EntityManager entityManager) {
        super(domainClass, entityManager);
        this.entityManager = entityManager;
    }

    @Override
   public  List<T> findByIdsIn(List<ID> ids) {
        List<T> entities = entityManager.createQuery(
        "FROM"+this.getDomainClass()+" WHERE id IN ("+CommonUtils.concat(ids,',')+")").getResultList(); // concatenation code is not tested hence u need to fix it
        return entities;
    }
}

Also, you will need to override default implementation i.e.
 SimpleJpaRepository with your implementation i.e. BaseRepositoryImpl

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import javax.persistence.EntityManager;
import java.io.Serializable;

public class BaseRepositoryFactoryBean<R extends JpaRepository<T, I>, T,
        I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I> {

    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
        return new BaseRepositoryFactory(entityManager);
    }

    private static class BaseRepositoryFactory<T, I extends Serializable>
            extends JpaRepositoryFactory {

        private final EntityManager entityManager;

        public BaseRepositoryFactory(EntityManager entityManager) {
            super(entityManager);
            this.entityManager = entityManager;
        }

        @Override
        protected Object getTargetRepository(RepositoryMetadata metadata) {
            return new BaseRepositoryImpl<T, I>((Class<T>) metadata.getDomainType(), entityManager);
        }

        @Override
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return BaseRepositoryImpl.class;
        }
    }
}

Finally, configure your BaseRepositoryFactoryBean in Spring configuration by using @EnableJpaRepositories annotation and specifying your class as below. This will tell JPA which RepositoryFactoryBean to call and which in turn tell which JPA repository to use throughout and initialize it with its implementation using its Impl class.

@EnableJpaRepositories(basePackages = {"com.test.jpa.custom.repository"},
        repositoryFactoryBeanClass = BaseRepositoryFactoryBean.class)
class Configuration{}

Now you could use BaseRepository and findByIdsIn will be available for usage throughout your application.


问:
Package requires NuGet client version '2.12'
I am trying to install 'WindowsAzure.Storage 8.0.1' in visual studio 2012, but getting the error

package requires NuGet client version '2.12' or above, but the current NuGet version is '2.8.60318.667'.

on running command "Install-Package NuGet.Client"

```<code>Attempting to resolve dependency 'NuGet.Versioning (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Packaging (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Common (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Packaging.Core (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Packaging.Core.Types (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Frameworks (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Repositories (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.RuntimeModel (≥ 3.5.0)'.
Attempting to resolve dependency 'Newtonsoft.Json (≥ 6.0.4)'.
Attempting to resolve dependency 'NuGet.ContentModel (≥ 3.5.0)'.
'NuGet.Client 3.5.0' already installed.
</code>```

But still I am getting the error.

The 'WindowsAzure.Storage 8.0.1' package requires NuGet client version '2.12' or above, but the current NuGet version is '2.8.60318.667'.

答:
I struggled with this issue in Visual Studio 2010 when I was trying to add NewtonSoft.Json nuget package into my project. When I try to run the latest version of the nuget package from nuget package manager console:

```<code>PM> Install-Package Newtonsoft.Json
</code>```

It results in the same error as mentioned by OP:

package requires NuGet client version '2.12' or above, but the current
  NuGet version is '2.8.60318.667'.

So I thought I would update the NuGet extension in Visual Studio first to latest version. But when I went into Tools -> Extensions and Updates window the Updates tab wasn't showing any update for Nuget extension. So it seems NuGet client version 2.12 isn't available/supported in Visual Studio 2010 at all. I was running out of options now.

So finally, I tried to install a specific lower version (6.0.3) of Newtonsoft.Json package deliberately this way:

```<code>PM> Install-Package Newtonsoft.Json {Your Project Name} 6.0.3
</code>```

This worked successfully.
Latest version of this package at the time of writing this post is 10.0.3 instead.

So, it might be the case that newer version of a nuget package is compatible with only latest version of nuget package manager. So sometimes explicitly installing a lower version of the package might help you. Older version of a nuget package will of course be compatible with older nuget extension in Visual Studio if it is not up-to-date.

The only caveat in this solution is that the functionalities present in lower version of the nuget package you target should suffice your current project needs. Good luck!

Note: Although I've elaborated this solution w.r.t. Visual Studio 2010 but you can try this work around for any Visual Studio version for that matter.

Body:
I am trying to install 'WindowsAzure.Storage 8.0.1' in visual studio 2012, but getting the error

package requires NuGet client version '2.12' or above, but the current NuGet version is '2.8.60318.667'.

on running command "Install-Package NuGet.Client"

Attempting to resolve dependency 'NuGet.Versioning (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Packaging (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Common (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Packaging.Core (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Packaging.Core.Types (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Frameworks (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.Repositories (≥ 3.5.0)'.
Attempting to resolve dependency 'NuGet.RuntimeModel (≥ 3.5.0)'.
Attempting to resolve dependency 'Newtonsoft.Json (≥ 6.0.4)'.
Attempting to resolve dependency 'NuGet.ContentModel (≥ 3.5.0)'.
'NuGet.Client 3.5.0' already installed.

But still I am getting the error.

The 'WindowsAzure.Storage 8.0.1' package requires NuGet client version '2.12' or above, but the current NuGet version is '2.8.60318.667'.

Body:
I struggled with this issue in Visual Studio 2010 when I was trying to add NewtonSoft.Json nuget package into my project. When I try to run the latest version of the nuget package from nuget package manager console:

PM> Install-Package Newtonsoft.Json

It results in the same error as mentioned by OP:

package requires NuGet client version '2.12' or above, but the current
  NuGet version is '2.8.60318.667'.

So I thought I would update the NuGet extension in Visual Studio first to latest version. But when I went into Tools -> Extensions and Updates window the Updates tab wasn't showing any update for Nuget extension. So it seems NuGet client version 2.12 isn't available/supported in Visual Studio 2010 at all. I was running out of options now.

So finally, I tried to install a specific lower version (6.0.3) of Newtonsoft.Json package deliberately this way:

PM> Install-Package Newtonsoft.Json {Your Project Name} 6.0.3

This worked successfully.
Latest version of this package at the time of writing this post is 10.0.3 instead.

So, it might be the case that newer version of a nuget package is compatible with only latest version of nuget package manager. So sometimes explicitly installing a lower version of the package might help you. Older version of a nuget package will of course be compatible with older nuget extension in Visual Studio if it is not up-to-date.

The only caveat in this solution is that the functionalities present in lower version of the nuget package you target should suffice your current project needs. Good luck!

Note: Although I've elaborated this solution w.r.t. Visual Studio 2010 but you can try this work around for any Visual Studio version for that matter.


问:
How to convert string array to JSON array in Javascript?
I have string array like this:

```<code>"[totRev=248634.29858677526, totEBITDA=34904.9893085068, EBITDA_Operating_Cash_Flow_Margin=0.140386863387, debt_Service_Coverage_Ratio=16.7793849967, gross_Debt_to_EBITDA=0.3626422278, gross_Debt=50632.09233331651, cash_Available_for_Debt=102746.09168349924, debt_Servicing_Amount=6123.352655871018]"
</code>```

How do I convert this either into a JSON Array or a JSON object like

```<code>{totRev:'248634.29858677526',....etc}
</code>```

答:
Use substring, split and reduce

```<code>str.substring( 1,str.length - 1 ) //remove [ and ] from the string
    .split(",") //split by ,
    .reduce( (a,b) => (i = b.split("="), a[i[0]] = i[1], a ) , {} );
</code>```

Reduce explanation

Split b (element in the array such as totRev=248634.29858677526) by =

Assign the first item in the array as key to a (accumulator initialized as {}) and value as second item of the array

Return a

Demo

var str = "[totRev=248634.29858677526, totEBITDA=34904.9893085068, EBITDA_Operating_Cash_Flow_Margin=0.140386863387, debt_Service_Coverage_Ratio=16.7793849967, gross_Debt_to_EBITDA=0.3626422278, gross_Debt=50632.09233331651, cash_Available_for_Debt=102746.09168349924, debt_Servicing_Amount=6123.352655871018]";
var output = str.substring(1,str.length-1).split(",").reduce( (a,b) => (i = b.split("="), a[i[0].trim()] = i[1], a ) , {} );
console.log(output);```

Body:
I have string array like this:

"[totRev=248634.29858677526, totEBITDA=34904.9893085068, EBITDA_Operating_Cash_Flow_Margin=0.140386863387, debt_Service_Coverage_Ratio=16.7793849967, gross_Debt_to_EBITDA=0.3626422278, gross_Debt=50632.09233331651, cash_Available_for_Debt=102746.09168349924, debt_Servicing_Amount=6123.352655871018]"

How do I convert this either into a JSON Array or a JSON object like

{totRev:'248634.29858677526',....etc}

Body:
Use substring, split and reduce

str.substring( 1,str.length - 1 ) //remove [ and ] from the string
    .split(",") //split by ,
    .reduce( (a,b) => (i = b.split("="), a[i[0]] = i[1], a ) , {} );

Reduce explanation

Split b (element in the array such as totRev=248634.29858677526) by =

Assign the first item in the array as key to a (accumulator initialized as {}) and value as second item of the array

Return a

Demo

var str = "[totRev=248634.29858677526, totEBITDA=34904.9893085068, EBITDA_Operating_Cash_Flow_Margin=0.140386863387, debt_Service_Coverage_Ratio=16.7793849967, gross_Debt_to_EBITDA=0.3626422278, gross_Debt=50632.09233331651, cash_Available_for_Debt=102746.09168349924, debt_Servicing_Amount=6123.352655871018]";
var output = str.substring(1,str.length-1).split(",").reduce( (a,b) => (i = b.split("="), a[i[0].trim()] = i[1], a ) , {} );
console.log(output);


问:
XML PATH output one by one using SQL Server
I'm trying to group column values by a specific column using FOR XML PATH('') in SQL Server.

For example when I pass the ModuleID value 1 then output RoleName : Admin Administrator Super Admin  which is present is same line.

```<code>ALTER PROCEDURE [dbo].[MEDEIL_SiteRoleModules_SelectOne]
    @ModuleID int
AS
    SELECT
        t1.ModuleID,
        RoleName = (SELECT s1.RoleName AS [data()]
                    FROM SiteRoleModules t2
                    INNER JOIN SiteRoles s1 ON t2.RoleID = s1.RoleID
                    WHERE t2.ModuleID = t1.ModuleID
                    GROUP BY s1.RoleName
                    FOR XML PATH(''))
    FROM
        SiteRoleModules t1
    WHERE
        ModuleId = @ModuleID
    GROUP BY
        ModuleID
</code>```

I need to display one by one

答:
You could try xquery.. .node method

```<code>select
           case when row_number() over (partition by a.ModuleID order by a.ModuleID) > 1 then '' else cast(a.ModuleID as varchar) end [ModuleID],
           id.value('.', 'varchar(50)') [RoleName] from
     (
        select ModuleID ,  cast('<m>'+replace(RoleName, space(1), '</m><m>')+'</m>' as xml) RoleName  from <table>
     ) a cross apply RoleName.nodes ('/m') as RoleName(id)
</code>```

Result :

```<code>ModuleID    RoleName
1           Admin
            Administrator
            Super
            Admin
</code>```

Body:
I'm trying to group column values by a specific column using FOR XML PATH('') in SQL Server.

For example when I pass the ModuleID value 1 then output RoleName : Admin Administrator Super Admin  which is present is same line.

ALTER PROCEDURE [dbo].[MEDEIL_SiteRoleModules_SelectOne]
    @ModuleID int
AS
    SELECT
        t1.ModuleID,
        RoleName = (SELECT s1.RoleName AS [data()]
                    FROM SiteRoleModules t2
                    INNER JOIN SiteRoles s1 ON t2.RoleID = s1.RoleID
                    WHERE t2.ModuleID = t1.ModuleID
                    GROUP BY s1.RoleName
                    FOR XML PATH(''))
    FROM
        SiteRoleModules t1
    WHERE
        ModuleId = @ModuleID
    GROUP BY
        ModuleID

I need to display one by one

Body:
You could try xquery.. .node method

select
           case when row_number() over (partition by a.ModuleID order by a.ModuleID) > 1 then '' else cast(a.ModuleID as varchar) end [ModuleID],
           id.value('.', 'varchar(50)') [RoleName] from
     (
        select ModuleID ,  cast('<m>'+replace(RoleName, space(1), '</m><m>')+'</m>' as xml) RoleName  from <table>
     ) a cross apply RoleName.nodes ('/m') as RoleName(id)

Result :

ModuleID    RoleName
1           Admin
            Administrator
            Super
            Admin


问:
How to print all jar results into a file using bash script
I've been trying to do this simple script that I wrote where it runs an executable jar file that I made. The command of the script are as follows:

```<code>#!/bin/bash
msisdn=$1

java -cp /home/support/phuzca/Migration/PostpaidXMigration_lib/ -jar /home/support/phuzca/Migration/PostpaidXMigration.jar $msisdn /home/support/phuzca/Migration/config.properties /opt/tomcat9/webapps/axis2/WEB-INF/classes/META-INF/PlanID.xml
</code>```

The jar file works as expected and I receive the expected results:

The idea that I've been trying to figure out is how to prevent those texts from appearing when I run my script, and instead, print them in a file so it can be reviewed later. I hope you could open up some ideas for me. Thank you very much.

答:
Redirect both stdout and stderr to the output file.

```<code>migrateToPstopaidX.sh > output.log 2>&1
</code>```

You can use >> to append instead of overwriting your file.

Bash executes the redirects from left to right as follows:

>: Open output.log in overwrite mode and redirect stdout there.

2>&1: Redirect stderr to "where stdout is currently going". In this case, that is a file opened in append mode. In other words, the &1 reuses the file descriptor which stdout currently uses.

Body:
I've been trying to do this simple script that I wrote where it runs an executable jar file that I made. The command of the script are as follows:

#!/bin/bash
msisdn=$1

java -cp /home/support/phuzca/Migration/PostpaidXMigration_lib/ -jar /home/support/phuzca/Migration/PostpaidXMigration.jar $msisdn /home/support/phuzca/Migration/config.properties /opt/tomcat9/webapps/axis2/WEB-INF/classes/META-INF/PlanID.xml

The jar file works as expected and I receive the expected results:

The idea that I've been trying to figure out is how to prevent those texts from appearing when I run my script, and instead, print them in a file so it can be reviewed later. I hope you could open up some ideas for me. Thank you very much.

Body:
Redirect both stdout and stderr to the output file.

migrateToPstopaidX.sh > output.log 2>&1

You can use >> to append instead of overwriting your file.

Bash executes the redirects from left to right as follows:

>: Open output.log in overwrite mode and redirect stdout there.

2>&1: Redirect stderr to "where stdout is currently going". In this case, that is a file opened in append mode. In other words, the &1 reuses the file descriptor which stdout currently uses.


问:
Web Site Designing for Mobile
I just added printing capability to a web site using a style sheet (ie. @media print, etc.) and was wondering if I could use a similar method for adding support for mobile devices.

If not, how do I detect a mobile device?  My pages are C# (.aspx) and I'd like to scale back the pages for ease of use on a mobile device.

Any advice for me?

EDIT: My wife has a BlackBerry, so at a miminum I'd like to enable our company's web site for that.

答:
The best way of doing all of this is to do it at a server level.

Use a web service to check whether the visitor is a mobile and deliver your output based on this. Use the same URL and perform the same business logic on your application - just change the view layer of your app.

A great option is Wapple Architect (http://wapple.net) - it allows you to do these checks at a server level with some web services and then perform logic and add code if it's a mobile device.

Definitely worth a look.

OwnerDisplayName: BoltBait

Title: Web Site Designing for Mobile

LastEditorDisplayName: BoltBait