问:
Xamarin Android DropBox OAuth2Authentication Error
I'm trying to upload a text file to Dropbox using my android application. Which is developed by Xamarin & Visual Studio 2017.

When I try to run the application it gives this exception

Java.Lang.IllegalStateException: URI scheme in your app's manifest is not set up correctly. You should have a com.dropbox.client2.android.AuthActivity with the scheme: db-zeg38m9cvkcr55y

My AndroidManifest.xml

```<code> <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
         package="DemoDropbox.DemoDropbox"
         android:versionCode="1"
         android:versionName="1.0"
         android:installLocation="auto">
 <uses-sdk android:minSdkVersion="16" />
 <uses-permission android:name="android.permission.INTERNET" />
 <application android:label="DemoDropbox"></application>
 <activity android:name="com.dropbox.client2.android.AuthActivity"
           android:configChanges="orientation|keyboard"
           android:launchMode="singleTask">
   <intent-filter>
     <!-- Change this to be db- followed by your app key -->
     <data android:scheme="db-zeg38m9cvkcr55y" />
     <action android:name="android.intent.action.VIEW" />
     <category android:name="android.intent.category.BROWSABLE" />
     <category android:name="android.intent.category.DEFAULT" />
   </intent-filter>
 </activity>
</code>```

答:
I was able to find the solution after some research.

"activity" block should be inside the "application" block.
AndroidManifest.xml file should be as follows.

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="DemoFileSync.DemoFileSync"
          android:versionCode="1"
          android:versionName="1.0"
          android:installLocation="auto">
  <uses-sdk android:minSdkVersion="16" />
  <uses-permission android:name="android.permission.INTERNET" />
  <application android:label="DemoFileSync">
    <activity android:name="com.dropbox.client2.android.AuthActivity"
              android:configChanges="orientation|keyboard"
              android:launchMode="singleTask">
      <intent-filter>
        <!-- Change this to be db- followed by your app key -->
        <data android:scheme="db-zeg38m9cvkcr55y" />
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.BROWSABLE" />
        <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
    </activity>
  </application>
</manifest>
</code>```

Body:
I'm trying to upload a text file to Dropbox using my android application. Which is developed by Xamarin & Visual Studio 2017.

When I try to run the application it gives this exception

Java.Lang.IllegalStateException: URI scheme in your app's manifest is not set up correctly. You should have a com.dropbox.client2.android.AuthActivity with the scheme: db-zeg38m9cvkcr55y

My AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
         package="DemoDropbox.DemoDropbox"
         android:versionCode="1"
         android:versionName="1.0"
         android:installLocation="auto">
 <uses-sdk android:minSdkVersion="16" />
 <uses-permission android:name="android.permission.INTERNET" />
 <application android:label="DemoDropbox"></application>
 <activity android:name="com.dropbox.client2.android.AuthActivity"
           android:configChanges="orientation|keyboard"
           android:launchMode="singleTask">
   <intent-filter>

     <data android:scheme="db-zeg38m9cvkcr55y" />
     <action android:name="android.intent.action.VIEW" />
     <category android:name="android.intent.category.BROWSABLE" />
     <category android:name="android.intent.category.DEFAULT" />
   </intent-filter>
 </activity>

Body:
I was able to find the solution after some research.

"activity" block should be inside the "application" block.
AndroidManifest.xml file should be as follows.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="DemoFileSync.DemoFileSync"
          android:versionCode="1"
          android:versionName="1.0"
          android:installLocation="auto">
  <uses-sdk android:minSdkVersion="16" />
  <uses-permission android:name="android.permission.INTERNET" />
  <application android:label="DemoFileSync">
    <activity android:name="com.dropbox.client2.android.AuthActivity"
              android:configChanges="orientation|keyboard"
              android:launchMode="singleTask">
      <intent-filter>
        <!-- Change this to be db- followed by your app key -->
        <data android:scheme="db-zeg38m9cvkcr55y" />
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.BROWSABLE" />
        <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
    </activity>
  </application>
</manifest>


来源: stackexchange

问:
How to read text on a web page in swift for ios
I have a web page that only shows simple text information but I am unsure how to get the text using swift. I am open to using any method as I think this is an easy problem, I am just unsure what to search for to find an answer.

Here is the webpage in question where the last part, "player=bob" can be modified depending on the user. Thanks

http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player=bob

答:
You can use URLSession dataTask(with url:) to download your string data asynchronously:</p>

```<code>import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

let scheme = "http"
let host = "services.runescape.com"
let path = "/m=hiscore_oldschool/index_lite.ws"
let player = "bob"
let queryItem = URLQueryItem(name: "player", value: player)

var urlComponents = URLComponents()
urlComponents.scheme = scheme
urlComponents.host = host
urlComponents.path = path
urlComponents.queryItems = [queryItem]
if let url = urlComponents.url {
    print(url) // "http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player=bob\n"

    URLSession.shared.dataTask(with: url) { data, response, error in
        guard let data = data, error ==  nil, let string = String(data:data, encoding: .utf8) else { return }
        print(string)  // 58009,1806,205602075\n348,99,59484076\n14451,99,16670682\n22760,99,16641294\n4372,99,35456433\n64147,99,13034611\n14021,99,13034458\n269415,79,1897071\n57799,99,13034505\n42650,87,4136181\n262455,70,742935\n12795,99,13034536\n254495,60,275820\n89361,75,1213576\n190818,62,341931\n272854,60,284103\n111969,66,507089\n66399,74,1177748\n64643,72,915704\n10231,99,13059448\n187538,52,132708\n162920,50,106555\n175923,62,351621\n295606,46,68990\n327642,1\n179487,5\n72965,106\n-1,-1\n-1,-1\n48877,85\n-1,-1\n24712,15\n-1,-1\n\n"
    }.resume()
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use URLSession dataTask(with url:) to download your string data asynchronously:

import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

let scheme = "http"
let host = "services.runescape.com"
let path = "/m=hiscore_oldschool/index_lite.ws"
let player = "bob"
let queryItem = URLQueryItem(name: "player", value: player)

var urlComponents = URLComponents()
urlComponents.scheme = scheme
urlComponents.host = host
urlComponents.path = path
urlComponents.queryItems = [queryItem]
if let url = urlComponents.url {
    print(url) // "http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player=bob\n"

    URLSession.shared.dataTask(with: url) { data, response, error in
        guard let data = data, error ==  nil, let string = String(data:data, encoding: .utf8) else { return }
        print(string)  // 58009,1806,205602075\n348,99,59484076\n14451,99,16670682\n22760,99,16641294\n4372,99,35456433\n64147,99,13034611\n14021,99,13034458\n269415,79,1897071\n57799,99,13034505\n42650,87,4136181\n262455,70,742935\n12795,99,13034536\n254495,60,275820\n89361,75,1213576\n190818,62,341931\n272854,60,284103\n111969,66,507089\n66399,74,1177748\n64643,72,915704\n10231,99,13059448\n187538,52,132708\n162920,50,106555\n175923,62,351621\n295606,46,68990\n327642,1\n179487,5\n72965,106\n-1,-1\n-1,-1\n48877,85\n-1,-1\n24712,15\n-1,-1\n\n"
    }.resume()
}


问:
OracleDataAdapter, Fill method hangs, how do I handle connection terminations/drop offs/cut outs?
I have a C# program that connects to a remote server to query data. The data is quite big so the query takes about 2 mins to finish. During this 2 min window, the internet went down. This resulted in the job being unable to finish with the program stuck in the getting data routine.

It established connection but during the select query it was cut off. Setting the command timeout to 30 seconds did not work. I need the query to fail when encountering this error because the program can handle failure but it cannot handle being stuck. Thanks!

UPDATE: included code

```<code>OracleConnection connection = new OracleConnection(connectionstring);
OracleDataAdapter oracleDataAdapter = new OracleDataAdapter(new OracleCommand(query, connection));
oracleDataAdapter.SelectCommand.CommandTimeout = 30;

  DataSet dataSet = new DataSet();
  try
  {
    oracleDataAdapter.Fill(dataSet, table); //Hangs on this line when connection is lost
    return dataSet;
  }
  catch
  {
    throw;
  }
  finally
  {
    dataSet.Dispose();
    oracleDataAdapter.Dispose();
  }
</code>```

UPDATE AGAIN:

What I need to do is handle this situation because I don't want a dangling process.

Simplest would be once the connection is lost is that the program will throw an error. That is what I don't know how to do. I assumed that the commandtimeout will fix it but it did not.

答:
I see a couple issues with your statement, assuming it's using ODP.Net. Try the following:

```<code>DataSet dataSet = new DataSet();
using (OracleConnection connection = new OracleConnection(connectionstring))
{
  using (OracleDataAdapter oracleDataAdapter = new OracleDataAdapter(new OracleCommand(query, connection)))
  {
    oracleDataAdapter.Fill(dataSet, table);
  }
}
return dataSet;
</code>```

The using blocks will handle disposing of the connection and data adapter. In your example the connection did not get disposed which may have been part of your issue. Additionally I don't think you want to dispose the dataset if you intend to return it.

Since you were bubbling up the exception with a Throw I removed the exception handling. Keep in mind that this will bubble the exception so somewhere in your calling code chain you will need to catch the exception and handle it. If the app is just sitting there then be wary of any empty "catch" blocks eating exceptions.

Body:
I have a C# program that connects to a remote server to query data. The data is quite big so the query takes about 2 mins to finish. During this 2 min window, the internet went down. This resulted in the job being unable to finish with the program stuck in the getting data routine.

It established connection but during the select query it was cut off. Setting the command timeout to 30 seconds did not work. I need the query to fail when encountering this error because the program can handle failure but it cannot handle being stuck. Thanks!

UPDATE: included code

OracleConnection connection = new OracleConnection(connectionstring);
OracleDataAdapter oracleDataAdapter = new OracleDataAdapter(new OracleCommand(query, connection));
oracleDataAdapter.SelectCommand.CommandTimeout = 30;

  DataSet dataSet = new DataSet();
  try
  {
    oracleDataAdapter.Fill(dataSet, table); //Hangs on this line when connection is lost
    return dataSet;
  }
  catch
  {
    throw;
  }
  finally
  {
    dataSet.Dispose();
    oracleDataAdapter.Dispose();
  }

UPDATE AGAIN:

What I need to do is handle this situation because I don't want a dangling process.

Simplest would be once the connection is lost is that the program will throw an error. That is what I don't know how to do. I assumed that the commandtimeout will fix it but it did not.

Body:
I see a couple issues with your statement, assuming it's using ODP.Net. Try the following:

DataSet dataSet = new DataSet();
using (OracleConnection connection = new OracleConnection(connectionstring))
{
  using (OracleDataAdapter oracleDataAdapter = new OracleDataAdapter(new OracleCommand(query, connection)))
  {
    oracleDataAdapter.Fill(dataSet, table);
  }
}
return dataSet;

The using blocks will handle disposing of the connection and data adapter. In your example the connection did not get disposed which may have been part of your issue. Additionally I don't think you want to dispose the dataset if you intend to return it.

Since you were bubbling up the exception with a Throw I removed the exception handling. Keep in mind that this will bubble the exception so somewhere in your calling code chain you will need to catch the exception and handle it. If the app is just sitting there then be wary of any empty "catch" blocks eating exceptions.


问:
UIWebView pagination
I have a large html content to render in a UIWebView, I want to display the content in pages just like a book and the user uses buttons to navigate the pages. Is there any way to calculate the height of html content that fits in the webview without scrolling?</p>

答:
```<code>for (id subview in self.webView.subviews)
{
    if ([[subview class] isSubclassOfClass:[UIScrollView class]])
    {
        ((UIScrollView *)subview).pagingEnabled = YES;
        break;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: UIWebView pagination


问:
Accessing the list within a dictionary in Python
I have created a dictionary

```<code>store = {'assetType': "['props','char','env','sets']", 'Height': '871', 'Project': 'AnimationProject1', 'Width': '2048', 'FPS': '24', 'Type': 'Animation', 'Unit': 'cm'}
</code>```

This is within an xml file, so I use xml.etree.ElementTree to parse the file and find, findall and iter to access the xml files and the above line is what I got at the end. I use a for loop to access the xml file

```<code>import xml.etree.ElementTree as xml

read = xml.parse(xmlFile)
#xmlFile is the xmlFile directory

findBase = read.findall('base')
#'base' and 'type' are the xml.SubElement used in the xml file.

for child in findBase:
    findType = child.iter('type')
    store = child.attrib
    for types in findType:
        store[types.attrib.keys()[0]] = types.attrib.values()[0]
    print store
    print store.items()[0][1][3]
</code>```

However, now I would like access 'props' from 'assetType' from the dictionary above. I tried using store.items()[0][1] and I'm able to get "['props','char','env','sets']" but when I do store.items()[0][1][3], instead of getting the word sets, I get r instead. I understand the reason behind it, it's because it has registered that whole line as a string instead of a list of characters. I have also tried something like store.get("assetType") The problem is the same.

My question is, how can I get the word props, char, env or sets as a whole from the dictionary above instead of individual letters?

Thanks

答:
The assetType value is a string as you mentioned that needs to be parsed into a list. A couple ways to do it as mentioned in the comments. Here's a simple JSON way that's unfortunately fairly specific to your case. The single quotes have are not valid JSON so they have to be swapped for doubles.

```<code>>>> import json
>>> store = {'assetType': "['props','char','env','sets']",
 'Height': '871', 'Project': 'AnimationProject1',
 'Width': '2048', 'FPS': '24', 'Type': 'Animation',
 'Unit': 'cm'}
>>> json.loads(store['assetType'].replace("'",'"'))[3]
u'sets'
</code>```

Body:
I have created a dictionary

store = {'assetType': "['props','char','env','sets']", 'Height': '871', 'Project': 'AnimationProject1', 'Width': '2048', 'FPS': '24', 'Type': 'Animation', 'Unit': 'cm'}

This is within an xml file, so I use xml.etree.ElementTree to parse the file and find, findall and iter to access the xml files and the above line is what I got at the end. I use a for loop to access the xml file

import xml.etree.ElementTree as xml

read = xml.parse(xmlFile)
#xmlFile is the xmlFile directory

findBase = read.findall('base')
#'base' and 'type' are the xml.SubElement used in the xml file.

for child in findBase:
    findType = child.iter('type')
    store = child.attrib
    for types in findType:
        store[types.attrib.keys()[0]] = types.attrib.values()[0]
    print store
    print store.items()[0][1][3]

However, now I would like access 'props' from 'assetType' from the dictionary above. I tried using store.items()[0][1] and I'm able to get "['props','char','env','sets']" but when I do store.items()[0][1][3], instead of getting the word sets, I get r instead. I understand the reason behind it, it's because it has registered that whole line as a string instead of a list of characters. I have also tried something like store.get("assetType") The problem is the same.

My question is, how can I get the word props, char, env or sets as a whole from the dictionary above instead of individual letters?

Thanks

Body:
The assetType value is a string as you mentioned that needs to be parsed into a list. A couple ways to do it as mentioned in the comments. Here's a simple JSON way that's unfortunately fairly specific to your case. The single quotes have are not valid JSON so they have to be swapped for doubles.

>>> import json
>>> store = {'assetType': "['props','char','env','sets']",
 'Height': '871', 'Project': 'AnimationProject1',
 'Width': '2048', 'FPS': '24', 'Type': 'Animation',
 'Unit': 'cm'}
>>> json.loads(store['assetType'].replace("'",'"'))[3]
u'sets'


问:
Iterate DICOM files
Im using pydicom to read dicom files (the patient name), but all my dicom files are name as i34, i67 and so on (no specific order or sequence for these names).
My problem: i have a list of patients names in a txt file and i want search every patient name in this txt file with all the dicom files, looking to their PatientName in the dicom file (for those who are not familiar, every dicom file has a number of informations of a patient, one of them being the PatientName)

Exemple:

txt file:
John
George
Ringo
Paul

Dicom files:
i54
i98
i64
i12

What I want:
Take John and search i54, i98, i64, i12 for the PatientName match. And do it for every name in the txt file. Hope I made my self clear. Thks in advance!

EDIT

i try this code but didnt work

```<code>import dicom
import os

dir = "/path/to/dir_where_dicom_file_are"
txt = open('/path/to/txt_with_patientsnames.txt','r')
for line in txt:
    for sub, dirs, files in os.walk(dir):
        names = line.strip()
        for dcm in files:
           ds = dicom.read_file(dir+dcm) #necessary for read dicom files
           patient = ds.PatientName
           if names in patient:
           #do something
</code>```

I took a sample of 20 dicom images and a sample of 20 names. I knew that only one dicom file of this sample belong to one patient name so my ouput should be only one match righ? but im getting 20 match results out of this. Whats wrong?

答:
The problem was logic (more specifically the lack of it)

```<code>dir = "/path/where/dcm/files/are"
arq = open('path/where/file with pacient names are/patient.txt','r')
for linha in arq:
     c = linha.strip()
     for sub,p,a in os.walk(dir):
        for dcm in a:
          ds = dicom.read_file(dir+dcm)
          pctname = ds.PatientName
          if c in pctname:
          #do something
</code>```

To be honest i dont know what was wrong in the first place.

ContentLicense: CC BY-SA 4.0

Title: Iterate DICOM files

Body:
Im using pydicom to read dicom files (the patient name), but all my dicom files are name as i34, i67 and so on (no specific order or sequence for these names).
My problem: i have a list of patients names in a txt file and i want search every patient name in this txt file with all the dicom files, looking to their PatientName in the dicom file (for those who are not familiar, every dicom file has a number of informations of a patient, one of them being the PatientName)

Exemple:

txt file:
John
George
Ringo
Paul

Dicom files:
i54
i98
i64
i12

What I want:
Take John and search i54, i98, i64, i12 for the PatientName match. And do it for every name in the txt file. Hope I made my self clear. Thks in advance!

EDIT

i try this code but didnt work

import dicom
import os

dir = "/path/to/dir_where_dicom_file_are"
txt = open('/path/to/txt_with_patientsnames.txt','r')
for line in txt:
    for sub, dirs, files in os.walk(dir):
        names = line.strip()
        for dcm in files:
           ds = dicom.read_file(dir+dcm) #necessary for read dicom files
           patient = ds.PatientName
           if names in patient:
           #do something

I took a sample of 20 dicom images and a sample of 20 names. I knew that only one dicom file of this sample belong to one patient name so my ouput should be only one match righ? but im getting 20 match results out of this. Whats wrong?

Body:
The problem was logic (more specifically the lack of it)

dir = "/path/where/dcm/files/are"
arq = open('path/where/file with pacient names are/patient.txt','r')
for linha in arq:
     c = linha.strip()
     for sub,p,a in os.walk(dir):
        for dcm in a:
          ds = dicom.read_file(dir+dcm)
          pctname = ds.PatientName
          if c in pctname:
          #do something

To be honest i dont know what was wrong in the first place.


答:
If you can trust the input you can do an eval on the string representation of your list to convert it into a proper Python list

```<code>store = {'assetType': "['props','char','env','sets']", 'Height': '871', 'Project': 'AnimationProject1', 'Width': '2048', 'FPS': '24', 'Type': 'Animation', 'Unit': 'cm'}
asset_types = eval(store['assetType'])
# Then access the entries in the list
print asset_types[0]  # etc.
</code>```

Title: Accessing the list within a dictionary in Python

Body:
If you can trust the input you can do an eval on the string representation of your list to convert it into a proper Python list

store = {'assetType': "['props','char','env','sets']", 'Height': '871', 'Project': 'AnimationProject1', 'Width': '2048', 'FPS': '24', 'Type': 'Animation', 'Unit': 'cm'}
asset_types = eval(store['assetType'])
# Then access the entries in the list
print asset_types[0]  # etc.


问:
Unexpected token }
I have a script to open a model window.. Chrome gives me "Uncaught SyntaxError: Unexpected token }" on a line that doesn't even have a closing curly brace.

Here is the portion of the script that has the error:

```<code>function showm(id1){
  window.onscroll=function(){document.getElementById(id1).style.top=document.body.scrollTop;};
  document.getElementById(id1).style.display="block";
  document.getElementById(id1).style.top=document.body.scrollTop;
}
</code>```

Does anybody have any ideas on this? Any help is appreciated.

答:
Try running the entire script through jslint. This may help point you at the cause of the error.

Edit Ok, it's not quite the syntax of the script that's the problem. At least not in a way that jslint can detect.

Having played with your live code at http://ft2.hostei.com/ft.v1/, it looks like there are syntax errors in the generated code that your script puts into an onclick attribute in the DOM. Most browsers don't do a very good job of reporting errors in JavaScript run via such things (what is the file and line number of a piece of script in the onclick attribute of a dynamically inserted element?). This is probably why you get a confusing error message in Chrome. The FireFox error message is different, and also doesn't have a useful line number, although FireBug does show the code which causes the problem.

This snippet of code is taken from your edit function which is in the inline script block of your HTML:

```<code>var sub = document.getElementById('submit');
...
sub.setAttribute("onclick", "save(\""+file+"\", document.getElementById('name').value, document.getElementById('text').value");
</code>```

Note that this sets the onclick attribute of an element to invalid JavaScript code:

```<code><input type="submit" id="submit" onclick="save("data/wasup.htm", document.getElementById('name').value, document.getElementById('text').value">
</code>```

The JS is:

```<code>save("data/wasup.htm", document.getElementById('name').value, document.getElementById('text').value
</code>```

Note the missing close paren to finish the call to save.

As an aside, inserting onclick attributes is not a very modern or clean way of adding event handlers in JavaScript. Why are you not using the DOM's addEventListener to simply hook up a function to the element? If you were using something like jQuery, this would be simpler still.

Title: Unexpected token }

Body:
I have a script to open a model window.. Chrome gives me "Uncaught SyntaxError: Unexpected token }" on a line that doesn't even have a closing curly brace.

Here is the portion of the script that has the error:

function showm(id1){
  window.onscroll=function(){document.getElementById(id1).style.top=document.body.scrollTop;};
  document.getElementById(id1).style.display="block";
  document.getElementById(id1).style.top=document.body.scrollTop;
}

Does anybody have any ideas on this? Any help is appreciated.

Body:
Try running the entire script through jslint. This may help point you at the cause of the error.

Edit Ok, it's not quite the syntax of the script that's the problem. At least not in a way that jslint can detect.

Having played with your live code at http://ft2.hostei.com/ft.v1/, it looks like there are syntax errors in the generated code that your script puts into an onclick attribute in the DOM. Most browsers don't do a very good job of reporting errors in JavaScript run via such things (what is the file and line number of a piece of script in the onclick attribute of a dynamically inserted element?). This is probably why you get a confusing error message in Chrome. The FireFox error message is different, and also doesn't have a useful line number, although FireBug does show the code which causes the problem.

This snippet of code is taken from your edit function which is in the inline script block of your HTML:

var sub = document.getElementById('submit');
...
sub.setAttribute("onclick", "save(\""+file+"\", document.getElementById('name').value, document.getElementById('text').value");

Note that this sets the onclick attribute of an element to invalid JavaScript code:

<input type="submit" id="submit" onclick="save("data/wasup.htm", document.getElementById('name').value, document.getElementById('text').value">

The JS is:

save("data/wasup.htm", document.getElementById('name').value, document.getElementById('text').value

Note the missing close paren to finish the call to save.

As an aside, inserting onclick attributes is not a very modern or clean way of adding event handlers in JavaScript. Why are you not using the DOM's addEventListener to simply hook up a function to the element? If you were using something like jQuery, this would be simpler still.


问:
Xamarin Audio Player Progress bar inconsistency
I am having an issue with progress bar in Xamarin Android. I am using the below code for playing a specific audio file.

```<code>await CrossMediaManager.Current.Play(await DependencyService.Get<IMedia>().GetPath(answer.ResourceURL));
</code>```

and the progress bar code is like this :

```<code>CrossMediaManager.Current.PlayingChanged += (sender, ev) =>
                            {
                                progressBar.Progress = ev.Position.TotalSeconds / ev.Duration.TotalSeconds;
                                elapseTime.Text = Math.Abs(ev.Position.TotalMinutes).ToString("0.00");
                                totalTime.Text = Math.Abs((ev.Duration.TotalMinutes) - ev.Position.TotalMinutes).ToString("0.00");
                            };
</code>```

I have placed this progress bar code after the play.
So now my issue is like, in my screen there are some audio files for example 5 with 5 play buttons.
If I click on 2nd file, the audio is playing perfect. But the progress bar for the 5th file is also being moved but the audio is not played. Only the progress bar is moved.
Please find the attached image.Screenshot for progress bar

if I place the progress bar code in my constructor, all the progress bars of all the files are being moved but only one file is being played.

Some one please help me out fix this issue.

答:
I am using card component, which will be iterated based on the number of files from the DB in my ViewModel. the count of the files is dynamic.

I'm not sure which control are you using, but based on your description, it's possible that you're using ListView or RecyclerView or something like it, whose items can be automatically inserted to the list using an Adapter.

Then, for the controls like this, it is not recommended to use its name for retrieving the instance of the control in the item, cause each item has a control with the same name, especially that you're using Xamarin.Forms for development, if you're using the ListView in PCL and DataTemplate for the ItemTemplate, it's like a structure for each item.

Assume that you're using the ListView in PCL, not in Android platform, then you can for example code like this.

Firstly create a subclass of Image so we can give an ID to each item, for example:

```<code>public class MyImage : Image
{
    public int ItemID
    {
        get { return (int)GetValue(ItemIDProperty); }
        set { SetValue(ItemIDProperty, value); }
    }

    public static readonly BindableProperty ItemIDProperty = BindableProperty.Create<MyImage, int>(p => p.ItemID, default(int));
}
</code>```

Then use is in XAML for example:

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:YOURNAMESPACE"
             x:Class="YOURNAMESPACE.MainPage">
    <ContentPage.Content>

            <ListView x:Name="lv">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <StackLayout Orientation="Horizontal" HorizontalOptions="Fill">
                                <local:MyImage x:Name="xplay" Source="play_circle.png" ItemID="{Binding id}">
                                    <Image.GestureRecognizers>
                                        <TapGestureRecognizer Tapped="TrackEntity3" NumberOfTapsRequired="1" />
                                    </Image.GestureRecognizers>
                                </local:MyImage>
                                <StackLayout HorizontalOptions="FillAndExpand" Orientation="Vertical">
                                    <StackLayout Orientation="Horizontal">
                                        <Label x:Name="elapseTime" HorizontalOptions="Start" HorizontalTextAlignment="Start" Text="{Binding elapsetime,Mode=OneWay}"></Label>
                                        <Label x:Name="totalTime" HorizontalOptions="EndAndExpand" HorizontalTextAlignment="End" Text="{Binding totaltime,Mode=OneWay}"></Label>
                                    </StackLayout>
                                    <ProgressBar x:Name="progressBar" WidthRequest="300"  Progress="{Binding progress,Mode=OneWay}" />
                                </StackLayout>
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

    </ContentPage.Content>
</ContentPage>
</code>```

Create a data model:

```<code>public class MyMedia : INotifyPropertyChanged
{
    public int id { get; set; }

    private string _elapsetime;

    public string elapsetime
    {
        get { return _elapsetime; }
        set
        {
            if (value != _elapsetime)
            {
                _elapsetime = value;
                OnPropertyChanged();
            }
        }
    }

    private string _totaltime;

    public string totaltime
    {
        get { return _totaltime; }
        set
        {
            if (value != _totaltime)
            {
                _totaltime = value;
                OnPropertyChanged();
            }
        }
    }

    private double _progress;

    public double progress
    {
        get { return _progress; }
        set
        {
            if (value != _progress)
            {
                _progress = value;
                OnPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        if (this.PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
</code>```

In the TrackEntity3 event:

```<code>private MyMedia currentItem;

private void TrackEntity3(object sender, EventArgs e)
{
    var image = sender as MyImage;
    var id = image.ItemID;
    foreach (var source in lv.ItemsSource)
    {
        var item = source as MyMedia;
        if (item.id == id)
        {
            //play music here
            //find labels and progressbar
            if (currentItem != null)
            {
                currentItem.progress = 0;
                currentItem.totaltime = "";
                currentItem.elapsetime = "";
            }
            currentItem = item;
        }
    }
}
</code>```

In the CrossMediaManager.Current.PlayingChanged event directly change the item like this:

```<code>CrossMediaManager.Current.PlayingChanged += (sender, ev) =>
                            {
                                currentItem.progress = ...;
                                currentItem.elapsetime = ...;
                                currentItem.totaltime = ...;

                            };
</code>```

Since it's a ListView, you can add items use ObservableCollection:

```<code>private ObservableCollection<MyMedia> collection = new ObservableCollection<MyMedia>();

public MainPage()
{
    InitializeComponent();
    for (int i = 0; i < 5; i++)
    {
        collection.Add(new MyMedia { id = i });
    }
    lv.ItemsSource = collection;
}
</code>```

And sounds like you're using MVVM pattern, you can move the code in behind to your viewmodel. And if you're using other control for dynamically adding items, you can leave a comment.

Body:
I am having an issue with progress bar in Xamarin Android. I am using the below code for playing a specific audio file.

await CrossMediaManager.Current.Play(await DependencyService.Get<IMedia>().GetPath(answer.ResourceURL));

and the progress bar code is like this :

CrossMediaManager.Current.PlayingChanged += (sender, ev) =>
                            {
                                progressBar.Progress = ev.Position.TotalSeconds / ev.Duration.TotalSeconds;
                                elapseTime.Text = Math.Abs(ev.Position.TotalMinutes).ToString("0.00");
                                totalTime.Text = Math.Abs((ev.Duration.TotalMinutes) - ev.Position.TotalMinutes).ToString("0.00");
                            };

I have placed this progress bar code after the play.
So now my issue is like, in my screen there are some audio files for example 5 with 5 play buttons.
If I click on 2nd file, the audio is playing perfect. But the progress bar for the 5th file is also being moved but the audio is not played. Only the progress bar is moved.
Please find the attached image.Screenshot for progress bar

if I place the progress bar code in my constructor, all the progress bars of all the files are being moved but only one file is being played.

Some one please help me out fix this issue.

Body:
I am using card component, which will be iterated based on the number of files from the DB in my ViewModel. the count of the files is dynamic.

I'm not sure which control are you using, but based on your description, it's possible that you're using ListView or RecyclerView or something like it, whose items can be automatically inserted to the list using an Adapter.

Then, for the controls like this, it is not recommended to use its name for retrieving the instance of the control in the item, cause each item has a control with the same name, especially that you're using Xamarin.Forms for development, if you're using the ListView in PCL and DataTemplate for the ItemTemplate, it's like a structure for each item.

Assume that you're using the ListView in PCL, not in Android platform, then you can for example code like this.

Firstly create a subclass of Image so we can give an ID to each item, for example:

public class MyImage : Image
{
    public int ItemID
    {
        get { return (int)GetValue(ItemIDProperty); }
        set { SetValue(ItemIDProperty, value); }
    }

    public static readonly BindableProperty ItemIDProperty = BindableProperty.Create<MyImage, int>(p => p.ItemID, default(int));
}

Then use is in XAML for example:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:YOURNAMESPACE"
             x:Class="YOURNAMESPACE.MainPage">
    <ContentPage.Content>

            <ListView x:Name="lv">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <StackLayout Orientation="Horizontal" HorizontalOptions="Fill">
                                <local:MyImage x:Name="xplay" Source="play_circle.png" ItemID="{Binding id}">
                                    <Image.GestureRecognizers>
                                        <TapGestureRecognizer Tapped="TrackEntity3" NumberOfTapsRequired="1" />
                                    </Image.GestureRecognizers>
                                </local:MyImage>
                                <StackLayout HorizontalOptions="FillAndExpand" Orientation="Vertical">
                                    <StackLayout Orientation="Horizontal">
                                        <Label x:Name="elapseTime" HorizontalOptions="Start" HorizontalTextAlignment="Start" Text="{Binding elapsetime,Mode=OneWay}"></Label>
                                        <Label x:Name="totalTime" HorizontalOptions="EndAndExpand" HorizontalTextAlignment="End" Text="{Binding totaltime,Mode=OneWay}"></Label>
                                    </StackLayout>
                                    <ProgressBar x:Name="progressBar" WidthRequest="300"  Progress="{Binding progress,Mode=OneWay}" />
                                </StackLayout>
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

    </ContentPage.Content>
</ContentPage>

Create a data model:

public class MyMedia : INotifyPropertyChanged
{
    public int id { get; set; }

    private string _elapsetime;

    public string elapsetime
    {
        get { return _elapsetime; }
        set
        {
            if (value != _elapsetime)
            {
                _elapsetime = value;
                OnPropertyChanged();
            }
        }
    }

    private string _totaltime;

    public string totaltime
    {
        get { return _totaltime; }
        set
        {
            if (value != _totaltime)
            {
                _totaltime = value;
                OnPropertyChanged();
            }
        }
    }

    private double _progress;

    public double progress
    {
        get { return _progress; }
        set
        {
            if (value != _progress)
            {
                _progress = value;
                OnPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        if (this.PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

In the TrackEntity3 event:

private MyMedia currentItem;

private void TrackEntity3(object sender, EventArgs e)
{
    var image = sender as MyImage;
    var id = image.ItemID;
    foreach (var source in lv.ItemsSource)
    {
        var item = source as MyMedia;
        if (item.id == id)
        {
            //play music here
            //find labels and progressbar
            if (currentItem != null)
            {
                currentItem.progress = 0;
                currentItem.totaltime = "";
                currentItem.elapsetime = "";
            }
            currentItem = item;
        }
    }
}

In the CrossMediaManager.Current.PlayingChanged event directly change the item like this:

CrossMediaManager.Current.PlayingChanged += (sender, ev) =>
                            {
                                currentItem.progress = ...;
                                currentItem.elapsetime = ...;
                                currentItem.totaltime = ...;

                            };

Since it's a ListView, you can add items use ObservableCollection:

private ObservableCollection<MyMedia> collection = new ObservableCollection<MyMedia>();

public MainPage()
{
    InitializeComponent();
    for (int i = 0; i < 5; i++)
    {
        collection.Add(new MyMedia { id = i });
    }
    lv.ItemsSource = collection;
}

And sounds like you're using MVVM pattern, you can move the code in behind to your viewmodel. And if you're using other control for dynamically adding items, you can leave a comment.


问:
Combinatorics Algorithm
I've come across an interesting programming problem that I can't seem to formulate a solution to. Suppose you have K balls of N different colors. You must partition all of the balls into as many groups as possible such that no two groups are the same. (Two groups are considered the same if they have the same number of balls of each color.) What is the maximum number of groups you can make?

constraints:
1<=K<=50,
1<=N<=14

To clarify: We would like an algorithm that takes in an array of integers >= 1. The size of the array is N and the sum of the values it contains is K. The algorithm should return the maximum number of groups.

Any ideas on an algorithmic approach to this problem?

答:
After speaking with my professor again, I learned that this was an adaptation of an open.kattis.com problem.

The two are nearly identical, as any instance of the original problem can be solved by taking the prime factorization of N and treating each prime factor as a ball. For instance, 900 = 2^2*3^2*5*2, so the equivalent balls problem would be 2 2 2.

The given bounds were found using the max bound of 10^15. 2^50 > 10^15, so there can never be more than 50 factors, and multiplying the first 15 primes by each other also exceed 10^15, meaning there can be at most 14 groups.

The tradeoff between number of balls and number of groups was overlooked however, and that in my opinion makes the problem much easier to solve. For instance, if there are 14 groups, there will only be 1 ball in each group, while if there are 50 balls then they will all belong to the same group (this is due to the 10^15 constraints of the original problem)

With this new information I was able to solve the problem. I factorized N into a list of Primes as well as a list of all factors, and then used a multiple dimensional knapsack algorithm(if N has X unique prime factors, then the knapsack DP will be X+1 dimensional, where the first dimension is which item you are considering and each other dimension represents your remaining supply of a certain prime factor). Each factor of N would represent a potential item to take in the knapsack, with it's prime factorization being it's cost vector.

After doing this, the problem was still too slow on maximum cases, and one additional optimization was required. I found that an optimal solution always exists that uses as many single ball groups as possible. By creating as many 1 ball groups as possible in the beginning and solving the remaining subproblem, I was able to complete the problem in Kattis's time constraints.

My algorithm depends on two assumptions that I have proven:

If you can make X groups without using all of the balls, you can also make X groups using all of the balls. This makes knapsack solutions where you don't use 100% of the capacity valid. This assumption can be proven by taking all unused balls and adding them all to the largest group. This will create a group larger than any other, and hence it must be unique. This leaves you with the same number of groups, but all balls utilized.

there always exists an optimal solution using as many 1-ball groups as possible. This makes it possible to reduce the original problem into a subproblem solvable in the time constraint. This can be proven as well. Take any optimal solution. For any 1 ball grouping that does not exist, take a group containing that 1 ball, and move every other ball in that group to the largest group. This creates a solution with the same (optimal) number of groups, that also has as many 1 ball groups as possible.

My solution has a runtime of O(F(N)^2), where F(N) is the total number of factors of N.

Title: Combinatorics Algorithm


问:
WordPress - Contact Form 7 fields save to a different database
I know that there will be a database to be created at the initial configuration of CF7. I am wondering whether or not I can use a different database of my own (not the wordpress' database) in PHPMyAdmin, and is there an existing tutorial to do so?

Thank you.

答:
That could have some serious unintended consequences. You'd be better off putting a hook in your submission to ALSO add the data to some other database.

The reason is that plugins are quite integrated and there are many things that it tracks at once including things related to the user who submits the form. If you orphan some of those records, it might be difficult to reconstruct things, build reports, and do other sorts of maintenance later.


问:
Place Picker close after launch
I am using Google places API on Android Studio to display places of interest based on location. I am using the PlacePicker Inentbuilder to accomplish this.

When the app is run, the place picker launches and then closes immediately (about 1-2 seconds).

I already generated the public API key for android applications and am including this in the meta-data tag in the app manifest.

I have enabled the "Google Places API for android" API on the developers console.

I have included the latest play services version in dependencies in build.gradle.

I have included my code and the Logcat below. Do let me know if I need to include anything else.

Manifest.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".CoresActivity"
        android:label="@string/title_activity_cores" >
    </activity>
    <activity
        android:name=".MicrofoneActivity"
        android:label="@string/title_activity_microfone" >
    </activity>
    <activity
        android:name=".ConfirmaCoresActivity"
        android:label="@string/title_activity_confirma_cores" >
    </activity>
    <activity
        android:name=".BolaLocaActivity"
        android:label="@string/title_activity_bola_loca" >
    </activity>
    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps" >
    </activity>
    <activity
        android:name=".PlacesAPIActivity"
        android:label="@string/title_activity_place_api" >
    </activity>
</application>
</code>```

PlacesAPIActivity - Activity that is using google places API:

```<code>package com.fastcoding.appbebado;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;

public class PlacesAPIActivity extends AppCompatActivity {
    TextView getLocation;
    int PLACE_PICKER_REQUEST = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_places_api);
        getLocation = (TextView)findViewById(R.id.getLocTV);
        getLocation.setClickable(true);
        getLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
                Intent intent;
                try {
                    intent = builder.build(getApplicationContext());
                    startActivityForResult(intent, PLACE_PICKER_REQUEST);
                    Toast.makeText(PlacesAPIActivity.this,"start activity for result",Toast.LENGTH_LONG).show();
                } catch (GooglePlayServicesRepairableException e) {
                    e.printStackTrace();
                } catch (GooglePlayServicesNotAvailableException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_place_api, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        System.out.println("onActivityResult");
        if (requestCode == PLACE_PICKER_REQUEST) {
            if (resultCode == RESULT_OK) {
                Place place = PlacePicker.getPlace(data, this);
                String toastMsg = String.format("Place: %s", place.getName());
                Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
            }
        }
    }
}
</code>```

Build.gradle (app module - This is the only module)

```<code>    apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion '22.0.1'

    defaultConfig {
        applicationId "com.fastcoding.appbebado"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:22.2.1'
    compile 'com.google.android.gms:play-services:7.5.0'
}
</code>```

答: Enable your Google Places API for Android in the https://console.developers.google.com/apis/dashboard

Title: Place Picker close after launch

Body:
I am using Google places API on Android Studio to display places of interest based on location. I am using the PlacePicker Inentbuilder to accomplish this.

When the app is run, the place picker launches and then closes immediately (about 1-2 seconds).

I already generated the public API key for android applications and am including this in the meta-data tag in the app manifest.

I have enabled the "Google Places API for android" API on the developers console.

I have included the latest play services version in dependencies in build.gradle.

I have included my code and the Logcat below. Do let me know if I need to include anything else.

Manifest.xml:

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".CoresActivity"
        android:label="@string/title_activity_cores" >
    </activity>
    <activity
        android:name=".MicrofoneActivity"
        android:label="@string/title_activity_microfone" >
    </activity>
    <activity
        android:name=".ConfirmaCoresActivity"
        android:label="@string/title_activity_confirma_cores" >
    </activity>
    <activity
        android:name=".BolaLocaActivity"
        android:label="@string/title_activity_bola_loca" >
    </activity>
    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps" >
    </activity>
    <activity
        android:name=".PlacesAPIActivity"
        android:label="@string/title_activity_place_api" >
    </activity>
</application>

PlacesAPIActivity - Activity that is using google places API:

package com.fastcoding.appbebado;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;

public class PlacesAPIActivity extends AppCompatActivity {
    TextView getLocation;
    int PLACE_PICKER_REQUEST = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_places_api);
        getLocation = (TextView)findViewById(R.id.getLocTV);
        getLocation.setClickable(true);
        getLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
                Intent intent;
                try {
                    intent = builder.build(getApplicationContext());
                    startActivityForResult(intent, PLACE_PICKER_REQUEST);
                    Toast.makeText(PlacesAPIActivity.this,"start activity for result",Toast.LENGTH_LONG).show();
                } catch (GooglePlayServicesRepairableException e) {
                    e.printStackTrace();
                } catch (GooglePlayServicesNotAvailableException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_place_api, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        System.out.println("onActivityResult");
        if (requestCode == PLACE_PICKER_REQUEST) {
            if (resultCode == RESULT_OK) {
                Place place = PlacePicker.getPlace(data, this);
                String toastMsg = String.format("Place: %s", place.getName());
                Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
            }
        }
    }
}

Build.gradle (app module - This is the only module)

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion '22.0.1'

    defaultConfig {
        applicationId "com.fastcoding.appbebado"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:22.2.1'
    compile 'com.google.android.gms:play-services:7.5.0'
}


问:
Batch call to array of functions in Python
I am using scipy.interpolate.Rbf, which returns a function, to fit a large number RBF to different sets of points, and storing the output of this in a vector of functions, as follows

```<code>import scipy.interpolate as interp

for i in range(0,n):
    # Gets data points for this particular iteration
    data = get_data(i)

    # Fits RBF to data points
    zfun_smooth_rbf = interp.Rbf(data[:, 0], data[:, 1], data[:, 2], function='linear', smooth=0)

    # Appends RBF function
    rbf_fit.append(zfun_smooth_rbf)
</code>```

And then I am interested in running all the functions to regress a value for each computed RBF. Currently I use a foor loop strategy, similar to what was answered in this question, but this is far from ideal, because it basically runs this sequentially

```<code>c = [float(f(x,y) for f in self.rbf_fit]
</code>```

Is there anyway to run this call with a single call? In other words, I need to call all the functions stored in an array, at the same time. Something like  c = self.rbf_fit[:](x,y)?

Body:
I am using scipy.interpolate.Rbf, which returns a function, to fit a large number RBF to different sets of points, and storing the output of this in a vector of functions, as follows

import scipy.interpolate as interp

for i in range(0,n):
    # Gets data points for this particular iteration
    data = get_data(i)

    # Fits RBF to data points
    zfun_smooth_rbf = interp.Rbf(data[:, 0], data[:, 1], data[:, 2], function='linear', smooth=0)

    # Appends RBF function
    rbf_fit.append(zfun_smooth_rbf)

And then I am interested in running all the functions to regress a value for each computed RBF. Currently I use a foor loop strategy, similar to what was answered in this question, but this is far from ideal, because it basically runs this sequentially

c = [float(f(x,y) for f in self.rbf_fit]

Is there anyway to run this call with a single call? In other words, I need to call all the functions stored in an array, at the same time. Something like  c = self.rbf_fit[:](x,y)?

Body:
I'm going to try to combine the __call__ of 2 rbfi into one call.

In [80]: from scipy.interpolate import Rbf

Make a sample as illustrated in the docs:

In [81]: x, y, z, d = np.random.rand(4, 50)
In [82]: rbfi0 = Rbf(x, y, z, d)
In [83]:  xi = yi = zi = np.linspace(0, 1, 20)
In [84]: di0 = rbfi0(xi, yi, zi)
In [85]: di0
Out[85]:
array([ 0.26614249,  0.07429816, -0.01512205,  0.05134466,  0.24213774,
        0.41653342,  0.45280185,  0.34763177,  0.17681661,  0.07186139,
        0.16299749,  0.40416788,  0.641642  ,  0.78828711,  0.79709639,
        0.6530432 ,  0.42473033,  0.24155719,  0.17008326,  0.179932  ])

Make a second sample:

In [86]: x, y, z, d = np.random.rand(4, 50)
In [87]: rbfi1 = Rbf(x, y, z, d)
In [88]: di1 = rbfi1(xi, yi, zi)
In [89]: di1
Out[89]:
array([ 0.38975158,  0.39887118,  0.42430634,  0.48554998,  0.59403568,
        0.71745345,  0.77483525,  0.70657269,  0.53545478,  0.34931526,
        0.28960157,  0.45825098,  0.7538652 ,  0.99950089,  1.14749381,
        1.19019632,  1.12736371,  1.00558691,  0.87811695,  0.77231634])

Look at the key attributes of the rbfi:

In [90]: rbfi0.nodes
Out[90]:
array([ -13.02451018,   -3.05675802,    8.54073071,  -81.47163716,
         -5.74247623,  118.70153224,   -1.39117053,   -3.37170396,
         ....
        -10.08326243,    8.9995743 ,    3.83357612,   -4.59815344,
        -25.09981508,   -2.8753806 ,   -0.63932038,   76.59402274,
          0.26222997,  -30.35280108])
In [91]: rbfi0.nodes.shape
Out[91]: (50,)
In [92]: rbfi1.nodes.shape
Out[92]: (50,)
In [93]: rbfi0.xi.shape
Out[93]: (3, 50)
In [94]: rbfi1.xi.shape
Out[94]: (3, 50)

Construct the variables in the __call__:

In [95]: xa = np.asarray([a.flatten() for a in [xi,yi,zi]], dtype=np.float_)
In [96]: xa.shape
Out[96]: (3, 20)
In [97]: r0 = rbfi0._call_norm(xa, rbfi0.xi)
In [98]: r1 = rbfi1._call_norm(xa, rbfi1.xi)
In [99]: r0.shape
Out[99]: (20, 50)
In [100]: r1.shape
Out[100]: (20, 50)

Compute the norm for both rbfi with one call - by concatenating the xi arrays:

In [102]: r01 = rbfi0._call_norm(xa, np.concatenate((rbfi0.xi, rbfi1.xi),axis=1))
In [103]: r01.shape
Out[103]: (20, 100)
In [104]: np.allclose(r0, r01[:,:50])
Out[104]: True
In [105]: np.allclose(r1, r01[:,50:])

Now do the same for the nodes' anddot`:

In [110]: res01 = np.dot(rbfi0._function(r01), np.concatenate((rbfi0.nodes, rbfi1.nodes)))
In [111]: res01.shape
Out[111]: (20,)

Oops.  We want two sets of 20; this fits it against all 100 nodes at once.  I need to do some reshaping.

In [133]: r01.shape
Out[133]: (20, 100)
In [134]: r01 = r01.reshape(20,2,50)
In [135]: nodes01 = np.concatenate((rbfi0.nodes, rbfi1.nodes))
In [136]: nodes01.shape
Out[136]: (100,)
In [137]: nodes01 = nodes01.reshape(2,50) # should have just stacked them

The _function callables for the 2 rbfi differ, so I have use them separately:

In [138]: fr01 = [rbfi0._function(r01[:,0,:]), rbfi1._function(r01[:,1,:])]
In [139]: fr01[0].shape
Out[139]: (20, 50)

With more samples this list would be constructed with a list comprehension.

In [140]: fr01 = np.stack(fr01, axis=1)
In [141]: fr01.shape
Out[141]: (20, 2, 50)

Now I can do the np.dot for the combined rbfi:

In [142]: res01 = np.einsum('ijk,jk->ij', fr01, nodes01)
In [143]: res01.shape
Out[143]: (20, 2)
In [144]: np.allclose(res0, res01[:,0])
Out[144]: True
In [145]: np.allclose(res1, res01[:,1])
Out[145]: True

In [149]: di01 = np.stack([rbfi0(xi, yi, zi), rbfi1(xi, yi, zi)],axis=1)
In [150]: di01.shape
Out[150]: (20, 2)
In [151]: np.allclose(di01, res01)

So I've managed to replace the In [149] iteration with a In [138] one. I don't know if that's a time savings or not.  It may depend on how costly the _function call is compared to the rest the rbfi.__call__.

In my example

In [131]: rbfi0._function
Out[131]: <bound method Rbf._h_multiquadric of <scipy.interpolate.rbf.Rbf object at 0xab002fac>>

I don't know if your parameters, function='linear', smooth=0 make a difference.  If the respective _function attributes are the same, then I could replace iteration with a

rbfi0._function(r01).reshape(20,2,50)

That gives an idea of how you might speed up the iteration of the rbfi, and maybe even replace it with a 'vector' operation.

It looks like, for the default function, the difference is only in the epsilon value:

In [156]: rbfi0._function??
Signature: rbfi0._function(r)
Source:
    def _h_multiquadric(self, r):
        return np.sqrt((1.0/self.epsilon*r)**2 + 1)
File:      /usr/local/lib/python3.5/dist-packages/scipy/interpolate/rbf.py
Type:      method
In [157]: rbfi0.epsilon
Out[157]: 0.25663331561494024
In [158]: rbfi1.epsilon
Out[158]: 0.26163317529091562


问:
button refreshes website even if there is an action
I'm working on a website but it seems that I'm having some problems with a <button> because it refreshes the website even if I have a  with an action that is a file called r2.php.
The <button> is supposed to take me to the file r2.php but apparently it's just refreshing the website here is the code of the page :

```<code><form action="r2.php">
  <div class="row">
    <div class="col-xs-12">
      <div class="form-group">
        <label for="cardnumber" class="card-label">
                        <span id="trans-cardnumber">Card number</span>
                        <span class="card-icons">
                            <span id="provider-icons"><span class="icon-provider visa disabled" data-type="visa"></span><span class="icon-provider mastercard disabled" data-type="mastercard"></span><span class="icon-provider amex disabled" data-type="amex"></span><span class="icon-provider discover disabled" data-type="discover"></span></span>
                            <a id="secure-lock" class="icon-provider lock" data-tooltip="" data-lang="security_explained"></a>
                        </span>
                    </label>
        <span class="safe-field">
                        <input id="cardnumber" autocomplete="cc-number" type="tel" pattern="[0-9]*" placeholder="1111 2222 3333 4444" data-encrypted-name="number" class="form-control">
                    </span>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-xs-12">
      <div class="form-group">
        <label id="trans-expiration_date" for="expiration_date">Expiry date</label>
        <div class="row">
          <div class="col-xs-6">
            <select id="expiry-month" autocomplete="cc-exp-month" data-encrypted-name="expiryMonth" class="form-control">
                                <option id="trans-label_month" value="" default="default" selected="selected">Month</option>
                                <option value="1">01</option>
                                <option value="2">02</option>
                                <option value="3">03</option>
                                <option value="4">04</option>
                                <option value="5">05</option>
                                <option value="6">06</option>
                                <option value="7">07</option>
                                <option value="8">08</option>
                                <option value="9">09</option>
                                <option value="10">10</option>
                                <option value="11">11</option>
                                <option value="12">12</option>
                            </select>
          </div>
          <div class="col-xs-6">
            <select id="expiry-year" autocomplete="cc-exp-year" data-encrypted-name="expiryYear" class="form-control">
                                <option id="trans-label_year" value="" default="" selected="selected">Year</option>
                            <option value="2017">17</option><option value="2018">18</option><option value="2019">19</option><option value="2020">20</option><option value="2021">21</option><option value="2022">22</option><option value="2023">23</option><option value="2024">24</option><option value="2025">25</option><option value="2026">26</option><option value="2027">27</option><option value="2028">28</option><option value="2029">29</option><option value="2030">30</option><option value="2031">31</option><option value="2032">32</option><option value="2033">33</option><option value="2034">34</option><option value="2035">35</option><option value="2036">36</option><option value="2037">37</option><option value="2038">38</option><option value="2039">39</option><option value="2040">40</option><option value="2041">41</option><option value="2042">42</option><option value="2043">43</option><option value="2044">44</option><option value="2045">45</option><option value="2046">46</option></select>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-xs-6">
      <div class="form-group">
        <label id="trans-security_code" for="security-code" class="contain-tooltip" data-tooltip="" data-lang="cvc_info">Security code</label>
        <span class="safe-field">
                        <input id="security-code" autocomplete="off" type="tel" pattern="[0-9]*" placeholder="" data-encrypted-name="cvc" class="form-control">
                    </span>
      </div>
    </div>
    <div class="col-xs-6">
      <div class="form-group">
        <label id="trans-label_postal_code" for="zip-code">Zip code</label>
        <input id="zip-code" name="zip-code" autocomplete="off" type="text" class="form-control">
      </div>
    </div>
  </div>

  <aside class="aside-legal">

    <p>
      You hereby authorise us to charge you automatically every month until you cancel your subscription. Full terms are available <a href="/us/legal/end-user-agreement/" target="_blank">here.</a>
    </p>
  </aside>

  <button type="submit">Complete Verification</button>

</form>
</code>```

答:
I see your code and I think you might miss the method in form tag.

Note: If you did not put method on form tag it takes method='GET'
  automatically by default.

```<code><form action="action="r2.php" method="POST">
 //Try this way might it help.
</form>
</code>```

Body:
I'm working on a website but it seems that I'm having some problems with a <button> because it refreshes the website even if I have a  with an action that is a file called r2.php.
The <button> is supposed to take me to the file r2.php but apparently it's just refreshing the website here is the code of the page :

<form action="r2.php">

                        Card number

                        <input id="cardnumber" autocomplete="cc-number" type="tel" pattern="[0-9]*" placeholder="1111 2222 3333 4444" data-encrypted-name="number" class="form-control">

        Expiry date

            <select id="expiry-month" autocomplete="cc-exp-month" data-encrypted-name="expiryMonth" class="form-control">
                                <option id="trans-label_month" value="" default="default" selected="selected">Month</option>
                                <option value="1">01</option>
                                <option value="2">02</option>
                                <option value="3">03</option>
                                <option value="4">04</option>
                                <option value="5">05</option>
                                <option value="6">06</option>
                                <option value="7">07</option>
                                <option value="8">08</option>
                                <option value="9">09</option>
                                <option value="10">10</option>
                                <option value="11">11</option>
                                <option value="12">12</option>
                            </select>

            <select id="expiry-year" autocomplete="cc-exp-year" data-encrypted-name="expiryYear" class="form-control">
                                <option id="trans-label_year" value="" default="" selected="selected">Year</option>
                            <option value="2017">17</option><option value="2018">18</option><option value="2019">19</option><option value="2020">20</option><option value="2021">21</option><option value="2022">22</option><option value="2023">23</option><option value="2024">24</option><option value="2025">25</option><option value="2026">26</option><option value="2027">27</option><option value="2028">28</option><option value="2029">29</option><option value="2030">30</option><option value="2031">31</option><option value="2032">32</option><option value="2033">33</option><option value="2034">34</option><option value="2035">35</option><option value="2036">36</option><option value="2037">37</option><option value="2038">38</option><option value="2039">39</option><option value="2040">40</option><option value="2041">41</option><option value="2042">42</option><option value="2043">43</option><option value="2044">44</option><option value="2045">45</option><option value="2046">46</option></select>

        Security code

                        <input id="security-code" autocomplete="off" type="tel" pattern="[0-9]*" placeholder="" data-encrypted-name="cvc" class="form-control">

        Zip code
        <input id="zip-code" name="zip-code" autocomplete="off" type="text" class="form-control">

      You hereby authorise us to charge you automatically every month until you cancel your subscription. Full terms are available here.

  <button type="submit">Complete Verification</button>

</form>

Body:
I see your code and I think you might miss the method in form tag.

Note: If you did not put method on form tag it takes method='GET'
  automatically by default.

<form action="action="r2.php" method="POST">
 //Try this way might it help.
</form>


问:
Using PHP to split a URL
I am creating a PHP proxy where it accepts a url and confirms it is on my list of servers.

When importing the url from the application i ran it to an issue where i needed 2 parser tags. i need it to split along a "\?" tag as well as a string, in my case, "export?"

i am using preg for the first tag. Does this accept the strings like my export tag or is there some other method for doing this?

please le me know how this is accomplished or if you have more questions.

答:
As ircmaxell has already stated in the comments, PHP does already have a function to parse a URL: parse_url.

And when you have the URL path (I assume your export? the path suffix plus the query indicator), you can use explode to split the path into its path segments:

```<code>$path = parse_url($url, PHP_URL_PATH);
$segments = explode('/', $path);
</code>```

You can then get the last path segment with one of the following:

```<code>end($segments)
$segments[count($segments)-1]
</code>```

And to cope with trailing slashes, you can use rtrim($path, '/') to remove them.

All together:

```<code>$url = 'http://www.example.com/subfolders/export?';
$path = parse_url($url, PHP_URL_PATH);
$segments = explode('/', rtrim($path, '/'));
echo end($segments);
</code>```

Title: Using PHP to split a URL

Body:
As ircmaxell has already stated in the comments, PHP does already have a function to parse a URL: parse_url.

And when you have the URL path (I assume your export? the path suffix plus the query indicator), you can use explode to split the path into its path segments:

$path = parse_url($url, PHP_URL_PATH);
$segments = explode('/', $path);

You can then get the last path segment with one of the following:

end($segments)
$segments[count($segments)-1]

And to cope with trailing slashes, you can use rtrim($path, '/') to remove them.

All together:

$url = 'http://www.example.com/subfolders/export?';
$path = parse_url($url, PHP_URL_PATH);
$segments = explode('/', rtrim($path, '/'));
echo end($segments);


问:
Static Month Every Year Parameter SSRS
I want to have a parameter that selects the same month (which is September) every year. So this Parameter dynamically changes every year but still selects September. </p>

答:
It was all about changing the month the the static date. Took me a few tweaks but I was able to figure it out. It was actually pretty easy stuff. Feel free to post other methods. Method I used was:

=dateadd("m",-1,dateserial(year(Today()),9,1))

Title: Static Month Every Year Parameter SSRS


问:
How to make browser stop caching GWT nocache.js
I'm developing a web app using GWT and am seeing a crazy problem with caching of the app.nocache.js file in the browser even though the web server sent a new copy of the file!

I am using Eclipse to compile the app, which works in dev mode.  To test production mode, I have a virtual machine (Oracle VirtualBox) with a Ubuntu guest OS running on my host machine (Windows 7).  I'm running lighttpd web server in the VM.  The VM is sharing my project's war directory, and the web server is serving this dir.

I'm using Chrome as the browser, but the same thing happens in Firefox.

Here's the scenario:

The web page for the app is blank. Accorind to Chrome's "Inspect Element" tool, it's because it is trying fetch 6E89D5C912DD8F3F806083C8AA626B83.cache.html, which doesn't exist (404 not found).

I check the war directory, and sure enough, that file doesn't exist.

The app.nocache.js on the browser WAS RELOADED from the web server (200 OK), because the file on the server was newer than the browser cache.  I verified that file size and timestamp for the new file returned by the server were correct.  (This is info Chrome reports about the server's HTTP response)

However, if I open the app.nocache.js on the browser, the javascript is referring to 6E89D5C912DD8F3F806083C8AA626B83.cache.html!!!  That is, even though the web server sent a new app.nocache.js, the browser seems to have ignored that and kept using its cached copy!

Goto Google->GWT Compile in Eclipse. Recompile the whole thing.

Verify in the war directory that the app.nocache.js was overwritten and has a new timestamp.

Reload the page from Chrome and verify once again that the server sent a 200 OK response to the app.nocache.js.

The browser once again tries to load 6E89D5C912DD8F3F806083C8AA626B83.cache.html and fails.  The browser is still using the old cached copy of app.nocache.js.

Made absolutely certain in the war directory that nothing is referring to 6E89D5C912DD8F3F806083C8AA626B83.cache.html (via find and grep)

What is going wrong?  Why is the browser caching this nocache.js file even when the server is sending it a new copy?

Here is a copy of the HTTP request/response headers when clicking reload in the browser.  In this trace, the server content hasn't been recompiled since the last GET (but note that the cached version of nocache.js is still wrong!):

```<code>Request URL:http://192.168.2.4/xbts_ui/xbts_ui.nocache.js
Request Method:GET
Status Code:304 Not Modified
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Host:192.168.2.4
If-Modified-Since:Thu, 25 Oct 2012 17:55:26 GMT
If-None-Match:"2881105249"
Referer:http://192.168.2.4/XBTS_ui.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4
Response Headersview source
Accept-Ranges:bytes
Content-Type:text/javascript
Date:Thu, 25 Oct 2012 20:27:55 GMT
ETag:"2881105249"
Last-Modified:Thu, 25 Oct 2012 17:55:26 GMT
Server:lighttpd/1.4.31
</code>```

答:
Open the page in cognito mode just to get-rid of cache issue and unblock yourself.

You need to configure cache time as mentioned in others comments.

Body:
I'm developing a web app using GWT and am seeing a crazy problem with caching of the app.nocache.js file in the browser even though the web server sent a new copy of the file!

I am using Eclipse to compile the app, which works in dev mode.  To test production mode, I have a virtual machine (Oracle VirtualBox) with a Ubuntu guest OS running on my host machine (Windows 7).  I'm running lighttpd web server in the VM.  The VM is sharing my project's war directory, and the web server is serving this dir.

I'm using Chrome as the browser, but the same thing happens in Firefox.

Here's the scenario:

The web page for the app is blank. Accorind to Chrome's "Inspect Element" tool, it's because it is trying fetch 6E89D5C912DD8F3F806083C8AA626B83.cache.html, which doesn't exist (404 not found).

I check the war directory, and sure enough, that file doesn't exist.

The app.nocache.js on the browser WAS RELOADED from the web server (200 OK), because the file on the server was newer than the browser cache.  I verified that file size and timestamp for the new file returned by the server were correct.  (This is info Chrome reports about the server's HTTP response)

However, if I open the app.nocache.js on the browser, the javascript is referring to 6E89D5C912DD8F3F806083C8AA626B83.cache.html!!!  That is, even though the web server sent a new app.nocache.js, the browser seems to have ignored that and kept using its cached copy!

Goto Google->GWT Compile in Eclipse. Recompile the whole thing.

Verify in the war directory that the app.nocache.js was overwritten and has a new timestamp.

Reload the page from Chrome and verify once again that the server sent a 200 OK response to the app.nocache.js.

The browser once again tries to load 6E89D5C912DD8F3F806083C8AA626B83.cache.html and fails.  The browser is still using the old cached copy of app.nocache.js.

Made absolutely certain in the war directory that nothing is referring to 6E89D5C912DD8F3F806083C8AA626B83.cache.html (via find and grep)

What is going wrong?  Why is the browser caching this nocache.js file even when the server is sending it a new copy?

Here is a copy of the HTTP request/response headers when clicking reload in the browser.  In this trace, the server content hasn't been recompiled since the last GET (but note that the cached version of nocache.js is still wrong!):

Request URL:http://192.168.2.4/xbts_ui/xbts_ui.nocache.js
Request Method:GET
Status Code:304 Not Modified
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Host:192.168.2.4
If-Modified-Since:Thu, 25 Oct 2012 17:55:26 GMT
If-None-Match:"2881105249"
Referer:http://192.168.2.4/XBTS_ui.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4
Response Headersview source
Accept-Ranges:bytes
Content-Type:text/javascript
Date:Thu, 25 Oct 2012 20:27:55 GMT
ETag:"2881105249"
Last-Modified:Thu, 25 Oct 2012 17:55:26 GMT
Server:lighttpd/1.4.31


问:
border-image not showing in HTML Email
So I have a div with a border. However, the border image is not showing up. It displays it as an ordinary solid border. It's weird, the URL is valid and working, it is from google drive, everything looks good. The HTML itself works, but when I use it in an email it doesn't.

Hello world!!!
```

It's really weird; I've never seen anything like this. I'm sending to Gmail BTW and am not sure if it works with Outlook or something else.

PS: I know the border looks a little weird; that's because its height is small. I am aware of that, so don't complain about it.

答:
Since border-image is not supported by most Email vendors, You can just simulate a border-image using the background-image (since that one is supported by Gmail) property in combination with a div or any other element you feel like using. You will have to modify the padding property a bit if you are using it on your div. But this is how i did it and it looks just like a border-image.

Here is how mine looks:

Title: border-image not showing in HTML Email

Body:
So I have a div with a border. However, the border image is not showing up. It displays it as an ordinary solid border. It's weird, the URL is valid and working, it is from google drive, everything looks good. The HTML itself works, but when I use it in an email it doesn't.

Hello world!!!

It's really weird; I've never seen anything like this. I'm sending to Gmail BTW and am not sure if it works with Outlook or something else.

PS: I know the border looks a little weird; that's because its height is small. I am aware of that, so don't complain about it.


问:
Outlier detection function
I have created the function to detect outliers for datasets, but when I am applying it shows error, Codes & Errors are shown following.

function

```<code>def find_outlairs_tukey(x):
    q1 = np.percentile(x, 25)
    q3 = np.percentile(x, 75)
    iqr = q3 - q1
    floor = q1 - 1.5*iqr
    ceiling = q3 + 1.5*iqr
    outlair_indices = list(x.index[(x < floor) | (x > ceiling)])
    outlair_values = list(x[outlair_indices])
</code>```

Apply

```<code>LotFrontage_indices, LotFrontage_values = find_outlairs_tukey(house_1['LotArea'])
print(np.sort(turkey_values))
</code>```

Error

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-208-4923f848f510> in <module>()
----> 1 LotFrontage_indices, LotFrontage_values = find_outlairs_tukey(house_1['LotArea'])
      2 print(np.sort(turkey_values))

TypeError: 'NoneType' object is not iterable
</code>```

答:
Add return to your function:</p>

```<code>return outlair_indices, outlair_values
</code>```

Title: Outlier detection function

Body:
I have created the function to detect outliers for datasets, but when I am applying it shows error, Codes & Errors are shown following.

function

def find_outlairs_tukey(x):
    q1 = np.percentile(x, 25)
    q3 = np.percentile(x, 75)
    iqr = q3 - q1
    floor = q1 - 1.5*iqr
    ceiling = q3 + 1.5*iqr
    outlair_indices = list(x.index[(x < floor) | (x > ceiling)])
    outlair_values = list(x[outlair_indices])

Apply

LotFrontage_indices, LotFrontage_values = find_outlairs_tukey(house_1['LotArea'])
print(np.sort(turkey_values))

Error

TypeError                                 Traceback (most recent call last)
<ipython-input-208-4923f848f510> in <module>()
----> 1 LotFrontage_indices, LotFrontage_values = find_outlairs_tukey(house_1['LotArea'])
      2 print(np.sort(turkey_values))

TypeError: 'NoneType' object is not iterable

Body:
Add return to your function:

return outlair_indices, outlair_values


问:
How to authenticate user via OIM API?
I need to do oim user authentication from third party application. I am searching for OIM API for the same.</p>

答:
```<code>public static final String OIM_HOSTNAME = "oim.hpt.lab";
public static final String OIM_PORT = "14000";
public static final String OIM_PROVIDER_URL = "t3://"+ OIM_HOSTNAME + ":" + OIM_PORT;
public static final String OIM_USERNAME = "tungpt";
public static final String OIM_PASSWORD = "Hpt123456";
public static final String OIM_CLIENT_HOME = "F:/designconsole11gr3/config";
public static final String AUTHWL_PATH = OIM_CLIENT_HOME + "/authwl.conf";

public static void main(String[] args) {
    // TODO Auto-generated method stub
    OIMClient oimClient = null;
    try {
        //Set system properties required for OIMClient
        System.setProperty("java.security.auth.login.config", AUTHWL_PATH);
        System.setProperty("APPSERVER_TYPE", "wls");

        // Create an instance of OIMClient with OIM environment information
        Hashtable env = new Hashtable();
        env.put(OIMClient.JAVA_NAMING_FACTORY_INITIAL, "weblogic.jndi.WLInitialContextFactory");
        env.put(OIMClient.JAVA_NAMING_PROVIDER_URL, OIM_PROVIDER_URL);
        oimClient = new OIMClient(env);

        // Login to OIM with the approriate credentials
        System.out.println("Login by: "+ OIM_USERNAME);
        oimClient.login(OIM_USERNAME, OIM_PASSWORD.toCharArray());
        System.out.println("Login Done!");
    }catch(Exception e){
        e.printStackTrace();
    }
}
</code>```

Title: How to authenticate user via OIM API?


问:
height:100%; doesn't show up
It looks easy problem but it's impossible to show .l-main up as height:100% if i insert height:100% in css. its too big. unless, it too tiny. I already tried to insert html, body {margin:0;padding:0;height:100%;}

Actually, I use bootstrap and angular.

index.ejs

```<code><div class="l-cotents">
    <div class="l-main">
        <nav class="l-side child">
            <bl-side ng-reflect-title="設定" ng-reflect-items="[object Object],[object Object">
            <nav class="l-side bl-side">
                <ul class="c-nav">
                    <li class="c-nav__list">
                        <span class="c-nav__mejorItem">ワンオフ</span>
                    </li>
                    <li class="c-nav__list">
                        <span><a class="c-nav__link c-nav__link--side" ng-reflect-router-link="/custvcle-title" href="./mastar_m/mastar_m.ejs">マスメン</a></span>
                    </li>
                    <li class="c-nav__list">
                        <span><a class="c-nav__link c-nav__link--side" ng-reflect-router-link="/employee" href="/maintenance/employee">ガイド</a></span>
                    </li>
                    <li class="c-nav__list">
                        <span><a class="c-nav__link c-nav__link--side" ng-reflect-router-link="/label" href="/maintenance/label"></a></span>
                    </li>
                    <li class="c-nav__list">
                        <span><a class="c-nav__link c-nav__link--side" ng-reflect-router-link="/companymgt" href="/maintenance/companymgt"></a></span>
                    </li>
                    <li class="c-nav__list">
                        <span><a class="c-nav__link c-nav__link--side" ng-reflect-router-link="/organization" href="/maintenance/organization"></a></span>
                    </li>
                    <li class="c-nav__list">
                        <span><a class="c-nav__link c-nav__link--side" ng-reflect-router-link="/vcleregoffice" href="/maintenance/vcleregoffice"></a></span>
                    </li>
                    <li class="c-nav__list">
                        <span><a class="c-nav__link c-nav__link--side" ng-reflect-router-link="/listitem" href="/maintenance/listitem"></a></span>
                    </li>
                    <li class="c-nav__list">
                        <span><a class="c-nav__link c-nav__link--side" ng-reflect-router-link="/numbering" href="/maintenance/numbering"></a></span>
                    </li>
                    <li class="c-nav__list">
                        <span><a class="c-nav__link c-nav__link--side" ng-reflect-router-link="/general-initial" href="/maintenance/general-initial"></a></span>
                    </li>
                    <li class="c-nav__list">
                        <span><a class="c-nav__link c-nav__link--side" ng-reflect-router-link="/vehicle-makername" href="/maintenance/vehicle-makername"></a></span>
                    </li>
                    <li class="c-nav__list">
                        <span><a class="c-nav__link c-nav__link--side" ng-reflect-router-link="/carinsurance" href="/maintenance/carinsurance"></a></span>
                    </li>
                    <li class="c-nav__list">
                        <span><a class="c-nav__link c-nav__link--side" ng-reflect-router-link="/vehicle-modelname" href="/maintenance/vehicle-modelname"></a></span>
                    </li>
                    <li class="c-nav__list">
                        <span><a class="c-nav__link c-nav__link--side" ng-reflect-router-link="/custvcle-remarks" href="/maintenance/custvcle-remarks"></a></span>
                    </li>
                    <li class="c-nav__list">
                        <span><a class="c-nav__link c-nav__link--side" ng-reflect-router-link="" href="/maintenance/"></a></span>
                    </li>
                    <li class="c-nav__list">
                        <span><a class="c-nav__link c-nav__link--side" ng-reflect-router-link="/carowner" href="/maintenance/carowner"></a></span>
                    </li>
                </ul>
            </nav>
            </bl-side>
        </nav>
        <section class="l-common content">
            <div class="l-common__inner">
                <div class="l-common__inner__cell l-common__inner__cell--contents main-content">
                    <router-outlet></router-outlet>
                    <ng-component ng-version="4.0.1">
                    <bl-title _nghost-c8="" ng-reflect-title="TOP" ng-reflect-is-complete-button-group-view="false" ng-reflect-is-trash-mode-button-view="true">
                    <h1 class="c-headding u-shadow--headding bl-title">
                       <div><span class="bl-title-title">ワンオフ</span></div>
                        <div class="btn-group btn-toggle pull-right">
                            <button class="btn-group btn-toggle bl-title-heading-button" ng-reflect-klass="btn-group btn-toggle bl-title-" ng-reflect-ng-class="[object Object]">
                              <span class="btn c-btn--blue"><span>編集</span></span>
                              <span class="btn c-btn--gray"><span>ゴミ箱</span></span>
                            </button>
                        </div>
                    </h1>
                    </bl-title>
                    <div class="maintenance-body col-lg-11 col-md-11 col-sm-11 col-xs-11"></div>
                    <span></span>
                    </ng-component>
                </div>
            </div>
            <div class="u-margin20">
                <p class="u-mg15"><a href="#">002_業務メニュー</a></p>
                <p class="u-mg15"><a href="#">003_整備メニュー</a></p>
                <p class="u-mg15"><a href="#">004_日次メニュー</a></p>
                <p class="u-mg15"><a href="#">005_マスタメンテメニュー</a></p>
                <p class="u-mg15"><a href="#">013_ヘルプ</a></p>
                <p class="u-mg15"><a href="#">014_大分類操作ナビゲーション</a></p>
                <p class="u-mg15"><a href="#">015_中分類操作ナビゲーション</a></p>
                <p class="u-mg15"><a href="#">016_ナビゲーションリスト</a></p>
                <p class="u-mg15"><a href="#">021_顧客車両整備履歴照会</a></p>
            </div>
        </section>
    </div>
</div>
</code>```

_menu.scss

```<code>html, body {margin:0;padding:0;height:100%;}

.l-cotents {
    height: 100%!important;
}
  .l-side a, .l-sideSub a {
    color: #fff;
    text-decoration: none; }

.l-side {
    display: inline-block;
    width: 26.5rem;
    min-height:100%;
}

.l-sideSub {
  width: 19.4rem;
}

.l-common.content {
    display: inline-block;
    width: 84%;
    min-height: 100%;
}
.parent {
  overflow: hidden;
  zoom: 1;
}
.child {
  float: left;
}
.parent:after {
  content: "";
  clear: both;
  display: block;
}
.l-main {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    position: relative;
    height: calc(100% - 125px);
}
.l-side, .l-sideSub {
    position: relative;
    color: #fff;
    background-color: #263141;
    z-index: 1;
}
</code>```

答:
In your code
 is the parent and you have made the height as height: 100%!important; you define this height to a fixed height like height: 200px !important; so you can add the child class height: 100%!important;

Give html element 100% height, give body element 100% height

```<code>html, body {
      width: 100%;
      height: 100%;
      background: white;
      margin:0;
      padding:0;
    }
</code>```

Title: height:100%; doesn't show up

Body:
It looks easy problem but it's impossible to show .l-main up as height:100% if i insert height:100% in css. its too big. unless, it too tiny. I already tried to insert html, body {margin:0;padding:0;height:100%;}

Actually, I use bootstrap and angular.

index.ejs

            <bl-side ng-reflect-title="設定" ng-reflect-items="[object Object],[object Object">

                        ワンオフ

                        マスメン

                        ガイド

            </bl-side>

                    <router-outlet></router-outlet>
                    <ng-component ng-version="4.0.1">
                    <bl-title _nghost-c8="" ng-reflect-title="TOP" ng-reflect-is-complete-button-group-view="false" ng-reflect-is-trash-mode-button-view="true">

ワンオフ

                            <button class="btn-group btn-toggle bl-title-heading-button" ng-reflect-klass="btn-group btn-toggle bl-title-" ng-reflect-ng-class="[object Object]">
                              編集
                              ゴミ箱
                            </button>

                    </bl-title>

                    </ng-component>

002_業務メニュー

003_整備メニュー

004_日次メニュー

005_マスタメンテメニュー

013_ヘルプ

014_大分類操作ナビゲーション

015_中分類操作ナビゲーション

016_ナビゲーションリスト

021_顧客車両整備履歴照会

_menu.scss

html, body {margin:0;padding:0;height:100%;}

.l-cotents {
    height: 100%!important;
}
  .l-side a, .l-sideSub a {
    color: #fff;
    text-decoration: none; }

.l-side {
    display: inline-block;
    width: 26.5rem;
    min-height:100%;
}

.l-sideSub {
  width: 19.4rem;
}

.l-common.content {
    display: inline-block;
    width: 84%;
    min-height: 100%;
}
.parent {
  overflow: hidden;
  zoom: 1;
}
.child {
  float: left;
}
.parent:after {
  content: "";
  clear: both;
  display: block;
}
.l-main {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    position: relative;
    height: calc(100% - 125px);
}
.l-side, .l-sideSub {
    position: relative;
    color: #fff;
    background-color: #263141;
    z-index: 1;
}

Body:
In your code  <div class="l-cotents"> is the parent and you have made the height as height: 100%!important; you define this height to a fixed height like height: 200px !important; so you can add the child class height: 100%!important;

Give html element 100% height, give body element 100% height

html, body {
      width: 100%;
      height: 100%;
      background: white;
      margin:0;
      padding:0;
    }