问:
Using json and location to display data from a Weather API
I am trying to request a JSON froM a url to get specific data as shown below using separate java class.

```<code>package com.example.user.test4;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;
/**
 * Created by user on 05/12/2017.
*/

public class Parser {
// the below line is for making debugging easier
final String TAG = "Parser.java";
// where the returned json data from service will be stored when downloaded
static String json = "";

public String getJSONFromUrl(String url) {

    //// TODO: 05/12/2017 https://stackoverflow.com/questions/4308554/simplest-way-to-read-json-from-a-url-in-java
    try {
        // this code block represents/configures a connection to your REST service
        // it also represents an HTTP 'GET' request to get data from the REST service, not POST!
        URL u = new URL(url);
        HttpURLConnection restConnection = (HttpURLConnection) u.openConnection();
        restConnection.setRequestMethod("GET");
        restConnection.setRequestProperty("Content-length", "main");
        restConnection.setRequestProperty("Content-length", "sys");
        restConnection.setRequestProperty("Content-length", "weather");
        restConnection.setUseCaches(false);
        restConnection.setAllowUserInteraction(false);
        restConnection.setConnectTimeout(10000);
        restConnection.setReadTimeout(10000);
        restConnection.connect();
        int status = restConnection.getResponseCode();

        // switch statement to catch HTTP 200 and 201 errors
        switch (status) {
            case 200:
            case 201:
                // live connection to your REST service is established here using getInputStream() method
                BufferedReader br = new BufferedReader(new InputStreamReader(restConnection.getInputStream()));

                // create a new string builder to store json data returned from the REST service
                StringBuilder sb = new StringBuilder();
                String line;

                // loop through returned data line by line and append to stringbuilder 'sb' variable
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();

                // remember, you are storing the json as a stringy
                try {
                    json = sb.toString();
                } catch (Exception e) {
                    Log.e(TAG, "Error parsing data " + e.toString());
                }
                // return JSON String containing data to activity (or whatever your activity is called!)
                return json;
        }
        // HTTP 200 and 201 error handling from switch statement
    } catch (MalformedURLException ex) {
        Log.e(TAG, "Malformed URL ");
    } catch (IOException ex) {
        Log.e(TAG, "IO Exception ");
    }
    return null;
}
}
</code>```

Then in another another activity I am getting longitude and latitude and bind it to text to display it:

```<code>LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);

    // Use GPS provider to get last known location
    String locationProvider = LocationManager.GPS_PROVIDER;
    Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

 if (lastKnownLocation == null)
    {
        // if no last location is available set lat/long to Lincoln Location
        lat = 53.228029;
        longi = -0.546055;
    }
    else
    {
        // if last location exists then get/set the lat/long
        lat = lastKnownLocation.getLatitude();
        longi = lastKnownLocation.getLongitude();
    }
</code>```

Afterwards I send information to another application using this code and start the activity:

```<code>      public void sendLocation(View view) {
    Intent coordinates = new Intent(this,MainActivity.class);
    coordinates.putExtra("lat", lat);
    coordinates.putExtra("longi", longi);
    startActivity(coordinates);
}
</code>```

Then in the main activity I am trying to receive data and display it yet I caught and issue that the data is either not sent or received yet when the latitude and longitude are set in the following code to 0 the lat and longi are still classified as null and display and error message.

```<code> public void getCoordinates(View view) {
    // FIXME: 05/12/2017
    final Button coordinates = (Button) findViewById(R.id.getCoordinates);
    final Button displayData = (Button) findViewById(R.id.displayData);

    coordinates.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getLocation = MainActivity.this.getIntent();
            extras = getLocation.getExtras();
            lat = extras.getDouble("lat");
            longi = extras.getDouble("longi");

            //Checking if there is data stored in the doubles, if not the user will be warned
            if (lat == null && longi == null) {
                Toast.makeText(MainActivity.this, "No Data recorded, please use permissions", Toast.LENGTH_SHORT).show();
            } else {
                displayData.setVisibility(View.VISIBLE);
            }
</code>```

The application is supposed to use the collected latitude and longitude to access url and display the weather data but as I don't get any lat/longi I cannot show anything.

I am sorry for the amount of code but I have no clue at which point I have managed to make a mistake so hopefully someone will be able to help.

Thanks.

答:
I see a couple of issues, but it's been a while since I messed with Android java.

Why are you passing a View to SendLocation() and getCoordinates()?  Each Activity should control their own screen usage.

You retrieve your MainActivity intent inside an onClick() handler.  Instead, this should be in the main line, either from OnCreate(), onNewIntent(), etc.  My guess is that this is the cause of your issue.  If you capture the MainActivity Intent() at the start of this activity, you can control whether to continue processing or not (if 0's are passed for example).

Also, you don't show how any of these Activity's or the getJSONFromURL class are invoked, which could have an impact on what you see.

HTH, Jim

Body:
I am trying to request a JSON froM a url to get specific data as shown below using separate java class.

package com.example.user.test4;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;
/**
 * Created by user on 05/12/2017.
*/

public class Parser {
// the below line is for making debugging easier
final String TAG = "Parser.java";
// where the returned json data from service will be stored when downloaded
static String json = "";

public String getJSONFromUrl(String url) {

    //// TODO: 05/12/2017 https://stackoverflow.com/questions/4308554/simplest-way-to-read-json-from-a-url-in-java
    try {
        // this code block represents/configures a connection to your REST service
        // it also represents an HTTP 'GET' request to get data from the REST service, not POST!
        URL u = new URL(url);
        HttpURLConnection restConnection = (HttpURLConnection) u.openConnection();
        restConnection.setRequestMethod("GET");
        restConnection.setRequestProperty("Content-length", "main");
        restConnection.setRequestProperty("Content-length", "sys");
        restConnection.setRequestProperty("Content-length", "weather");
        restConnection.setUseCaches(false);
        restConnection.setAllowUserInteraction(false);
        restConnection.setConnectTimeout(10000);
        restConnection.setReadTimeout(10000);
        restConnection.connect();
        int status = restConnection.getResponseCode();

        // switch statement to catch HTTP 200 and 201 errors
        switch (status) {
            case 200:
            case 201:
                // live connection to your REST service is established here using getInputStream() method
                BufferedReader br = new BufferedReader(new InputStreamReader(restConnection.getInputStream()));

                // create a new string builder to store json data returned from the REST service
                StringBuilder sb = new StringBuilder();
                String line;

                // loop through returned data line by line and append to stringbuilder 'sb' variable
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();

                // remember, you are storing the json as a stringy
                try {
                    json = sb.toString();
                } catch (Exception e) {
                    Log.e(TAG, "Error parsing data " + e.toString());
                }
                // return JSON String containing data to activity (or whatever your activity is called!)
                return json;
        }
        // HTTP 200 and 201 error handling from switch statement
    } catch (MalformedURLException ex) {
        Log.e(TAG, "Malformed URL ");
    } catch (IOException ex) {
        Log.e(TAG, "IO Exception ");
    }
    return null;
}
}

Then in another another activity I am getting longitude and latitude and bind it to text to display it:

LocationManager locationManager = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);

    // Use GPS provider to get last known location
    String locationProvider = LocationManager.GPS_PROVIDER;
    Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

 if (lastKnownLocation == null)
    {
        // if no last location is available set lat/long to Lincoln Location
        lat = 53.228029;
        longi = -0.546055;
    }
    else
    {
        // if last location exists then get/set the lat/long
        lat = lastKnownLocation.getLatitude();
        longi = lastKnownLocation.getLongitude();
    }

Afterwards I send information to another application using this code and start the activity:

      public void sendLocation(View view) {
    Intent coordinates = new Intent(this,MainActivity.class);
    coordinates.putExtra("lat", lat);
    coordinates.putExtra("longi", longi);
    startActivity(coordinates);
}

Then in the main activity I am trying to receive data and display it yet I caught and issue that the data is either not sent or received yet when the latitude and longitude are set in the following code to 0 the lat and longi are still classified as null and display and error message.

 public void getCoordinates(View view) {
    // FIXME: 05/12/2017
    final Button coordinates = (Button) findViewById(R.id.getCoordinates);
    final Button displayData = (Button) findViewById(R.id.displayData);

    coordinates.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            getLocation = MainActivity.this.getIntent();
            extras = getLocation.getExtras();
            lat = extras.getDouble("lat");
            longi = extras.getDouble("longi");

            //Checking if there is data stored in the doubles, if not the user will be warned
            if (lat == null && longi == null) {
                Toast.makeText(MainActivity.this, "No Data recorded, please use permissions", Toast.LENGTH_SHORT).show();
            } else {
                displayData.setVisibility(View.VISIBLE);
            }

The application is supposed to use the collected latitude and longitude to access url and display the weather data but as I don't get any lat/longi I cannot show anything.

I am sorry for the amount of code but I have no clue at which point I have managed to make a mistake so hopefully someone will be able to help.

Thanks.


来源: stackexchange

问:
Xamarin ffimageloading plugin tap to full screen
The code below render an image with 200px height using ffimageloading component. I need to tap on this image and display the image in a fullscreen or zoom it. Is it posible with ffimageloading or I need implement it by each platform (android and ios)?

View

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             xmlns:ffimageloading="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"
             x:Class="Namespace.Views.MyClass">

<Grid Padding="0"
                  Margin="0"
                  BackgroundColor="{StaticResource BackgroundColor}">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="200" />
                    </Grid.RowDefinitions>

                    <ffimageloading:CachedImage
                        Grid.Row="0"
                        Source="{Binding ThumbPath}"
                        Aspect="AspectFill">
                        <ffimageloading:CachedImage.LoadingPlaceholder>
                            <OnPlatform
                            x:TypeArguments="ImageSource"
                            iOS="logo_header"
                            Android="logo_header" />
                        </ffimageloading:CachedImage.LoadingPlaceholder>
                        <ffimageloading:CachedImage.ErrorPlaceholder>
                            <OnPlatform
                            x:TypeArguments="ImageSource"
                            iOS="noimage"
                            Android="noimage" />
                        </ffimageloading:CachedImage.ErrorPlaceholder>
                    </ffimageloading:CachedImage>
                </Grid>
</ContentPage>
</code>```

ViewModel (using prism)

```<code>public class MyClassViewModel : BindableBase, INavigationAware
{
   public MyClassViewModel()
   {
   }

    private string _thumbPath;

    public PerfilPetDto ThumbPath
    {
        get
        {
            return "https://www.google.com.br/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
        }
        set
        {
            _thumbPath = value;
            RaisePropertyChanged(nameof(ThumbPath));
        }
    }
}
</code>```

答:
The first thing to do is add a gesture recogniser to the cached image

```<code><ffimageloading:CachedImage.GestureRecognizers>
    <TapGestureRecognizer Command="{Binding ViewImageCommand}" />
</ffimageloading:CachedImage.GestureRecognizers>
</code>```

This uses a command binding to a command in the view model

```<code>private Command _viewImageCommand;
public Command ViewImageCommand => _viewImageCommand ?? (_viewImageCommand = new Command(async () => await ViewImage()));

private async Task ViewImage()
{
    await CoreMethods.PushPageModel<FullScreenImagePageModel>(imageName, false);
}
</code>```

This pushes another page to display the image as full screen.

I'm using FreshMvvm to pass the name of the image to the full screen image view model.

ContentLicense: CC BY-SA 3.0

Body:
The code below render an image with 200px height using ffimageloading component. I need to tap on this image and display the image in a fullscreen or zoom it. Is it posible with ffimageloading or I need implement it by each platform (android and ios)?

View

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             xmlns:ffimageloading="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"
             x:Class="Namespace.Views.MyClass">

<Grid Padding="0"
                  Margin="0"
                  BackgroundColor="{StaticResource BackgroundColor}">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="200" />
                    </Grid.RowDefinitions>

                    <ffimageloading:CachedImage
                        Grid.Row="0"
                        Source="{Binding ThumbPath}"
                        Aspect="AspectFill">
                        <ffimageloading:CachedImage.LoadingPlaceholder>
                            <OnPlatform
                            x:TypeArguments="ImageSource"
                            iOS="logo_header"
                            Android="logo_header" />
                        </ffimageloading:CachedImage.LoadingPlaceholder>
                        <ffimageloading:CachedImage.ErrorPlaceholder>
                            <OnPlatform
                            x:TypeArguments="ImageSource"
                            iOS="noimage"
                            Android="noimage" />
                        </ffimageloading:CachedImage.ErrorPlaceholder>
                    </ffimageloading:CachedImage>
                </Grid>
</ContentPage>

ViewModel (using prism)

public class MyClassViewModel : BindableBase, INavigationAware
{
   public MyClassViewModel()
   {
   }

    private string _thumbPath;

    public PerfilPetDto ThumbPath
    {
        get
        {
            return "https://www.google.com.br/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
        }
        set
        {
            _thumbPath = value;
            RaisePropertyChanged(nameof(ThumbPath));
        }
    }
}

Body:
The first thing to do is add a gesture recogniser to the cached image

<ffimageloading:CachedImage.GestureRecognizers>
    <TapGestureRecognizer Command="{Binding ViewImageCommand}" />
</ffimageloading:CachedImage.GestureRecognizers>

This uses a command binding to a command in the view model

private Command _viewImageCommand;
public Command ViewImageCommand => _viewImageCommand ?? (_viewImageCommand = new Command(async () => await ViewImage()));

private async Task ViewImage()
{
    await CoreMethods.PushPageModel<FullScreenImagePageModel>(imageName, false);
}

This pushes another page to display the image as full screen.

I'm using FreshMvvm to pass the name of the image to the full screen image view model.


问:
Why does Mandrill not recognize my merge tags?
I am using the Mandrill API and have a simple template:

```<code><html>
    <body>
        <p>Hello *|name|*
        </p>
    </body>
</html>
</code>```

And am using the send-template.json API from here: https://mandrillapp.com/api/docs/messages.JSON.html#method=send-template

And when i insert my payload then the 'name' var is still not populated, any idea why?

```<code>{
    "key": "secret",
    "template_name": "mandrill-sunday",
    "template_content": [
        {
            "name": "example name"
        }
    ],
    "message": {
        "html": "<p>Example HTML content</p>",
        "text": "Example text content",
        "subject": "example subject",
        "from_email": "message.from_email@example.com",
        "from_name": "Example Name",
        "to": [
            {
                "email": "myemail@gmail.com",
                "name": "Recipient Name"
            }
        ],
        "headers": {
            "Reply-To": "myemail@yahoo.com"
        },
        "important": false,
        "track_opens": null,
        "track_clicks": null,
        "auto_text": null,
        "auto_html": null,
        "inline_css": null,
        "url_strip_qs": null,
        "preserve_recipients": null,
        "bcc_address": "kamil@myemail.com",
        "tracking_domain": null,
        "signing_domain": null,
        "merge": true,
        "global_merge_vars": [
            {
                "name": "merge1"
            }
        ],
        "merge_vars": [
            {
                "rcpt": "myemail@gmail.com",
                "vars": [
                    {
                        "name": "merge2"
                    }
                ]
            }
        ],
        "tags": [
            "password-resets"
        ],
        "google_analytics_domains": [
            "mydomain.com"
        ],
        "google_analytics_campaign": "mandrill-sunday",
        "metadata": {
            "website": "www.mydomain.com"
        },
        "recipient_metadata": [
            {
                "rcpt": "myemail@gmail.com",
                "values": {
                    "user_id": 123456
                }
            }
        ]
    },
    "async": false
}
</code>```

But the only thing i get back in my email sent is:

```<code>Hello *|name|*
</code>```

答:
There's two things that could trip you up here.

1) (as others have mentioned) Each merge variable object has two key-value pairs, name and content:

```<code>'global_merge_vars': [
            {
                'name': 'fullName',
                'content': 'foo bar',
            },
            {
                'name': 'email',
                'content': 'foobar@gmail.com',
            }

 ],
</code>```

2) Make sure to set your merge language to either mailchimp or handlebars for mandrill.

```<code>'merge_language': 'mailchimp',
</code>```

Source: https://mandrillapp.com/api/docs/messages.python.html#method=send-template

Body:
I am using the Mandrill API and have a simple template:

Hello *|name|*

And am using the send-template.json API from here: https://mandrillapp.com/api/docs/messages.JSON.html#method=send-template

And when i insert my payload then the 'name' var is still not populated, any idea why?

{
    "key": "secret",
    "template_name": "mandrill-sunday",
    "template_content": [
        {
            "name": "example name"
        }
    ],
    "message": {
        "html": "
Example HTML content
",
        "text": "Example text content",
        "subject": "example subject",
        "from_email": "message.from_email@example.com",
        "from_name": "Example Name",
        "to": [
            {
                "email": "myemail@gmail.com",
                "name": "Recipient Name"
            }
        ],
        "headers": {
            "Reply-To": "myemail@yahoo.com"
        },
        "important": false,
        "track_opens": null,
        "track_clicks": null,
        "auto_text": null,
        "auto_html": null,
        "inline_css": null,
        "url_strip_qs": null,
        "preserve_recipients": null,
        "bcc_address": "kamil@myemail.com",
        "tracking_domain": null,
        "signing_domain": null,
        "merge": true,
        "global_merge_vars": [
            {
                "name": "merge1"
            }
        ],
        "merge_vars": [
            {
                "rcpt": "myemail@gmail.com",
                "vars": [
                    {
                        "name": "merge2"
                    }
                ]
            }
        ],
        "tags": [
            "password-resets"
        ],
        "google_analytics_domains": [
            "mydomain.com"
        ],
        "google_analytics_campaign": "mandrill-sunday",
        "metadata": {
            "website": "www.mydomain.com"
        },
        "recipient_metadata": [
            {
                "rcpt": "myemail@gmail.com",
                "values": {
                    "user_id": 123456
                }
            }
        ]
    },
    "async": false
}

But the only thing i get back in my email sent is:

Hello *|name|*

Body:
There's two things that could trip you up here.

1) (as others have mentioned) Each merge variable object has two key-value pairs, name and content:

'global_merge_vars': [
            {
                'name': 'fullName',
                'content': 'foo bar',
            },
            {
                'name': 'email',
                'content': 'foobar@gmail.com',
            }

 ],

2) Make sure to set your merge language to either mailchimp or handlebars for mandrill.

'merge_language': 'mailchimp',

Source: https://mandrillapp.com/api/docs/messages.python.html#method=send-template


问:
Foreign characters in website
I found a website that contains the string "donâ€™t". The obvious intent was the word "don't". I looked at the source expecting to see some character references, but didn't (it just shows the literal string "donâ€™t". A Google search yielded nothing (expect lots of other sites that have the same problem!). Can anyone explain what's happening here?

Edit: Here's the meta tag that was used:

```<code><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</code>```

Would this not cause the page to be served up as Latin-1 in the HTTP header?

答: In your browser, switch the page encoding to "UTF-8".  You're seeing a right single quote character, which is encoded by the octets 0xE2 0x80 0x99 in UTF-8.  In your charset, windows-1252, those 3 octets render as "â€™".  The page should be explicitly specifying UTF-8 as its charset either in the HTTP headers or in an HTML <meta> tag, but it probably isn't.

ContentLicense: CC BY-SA 2.5

Title: Foreign characters in website

Body:
I found a website that contains the string "donâ€™t". The obvious intent was the word "don't". I looked at the source expecting to see some character references, but didn't (it just shows the literal string "donâ€™t". A Google search yielded nothing (expect lots of other sites that have the same problem!). Can anyone explain what's happening here?

Edit: Here's the meta tag that was used:

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

Would this not cause the page to be served up as Latin-1 in the HTTP header?


问:
Binary search tree traversal method, in order toString
I made a binary search tree from scratch with my own nodes which functions perfectly when I add nodes and when I print the tree in order to the console. However, I'm having a time and a half getting the toString method working.

I changed my toString method to MakeString, because I thought it was getting confused when converting comparable type data to a string. I can either get the method to return one node or just in object form, but never the whole tree in string form. The printInOrder() method works perfectly, so why won't my MakeString() method?

```<code>public void printInOrder(){

    if (left != null) left.printInOrder();

     System.out.println(data);

    if (right != null) right.printInOrder();
}

public String MakeString(){

    String OrderedTree;
    StringBuilder sb = new StringBuilder();
    if (data == null) return "Tree is empty";

    if (left != null) left.MakeString();

     sb.append(data);

    if (right != null) right.MakeString();
</code>```

答:
If you need something to be preserved throughout the recursion, then it should be passed as a parameter. This will often result in a pair of methods if you want  to avoid having to prep the initial call or otherwise have something to do before or after the recursion.

In your case you are using a StringBuilder which needs to be created before the recursion, preserved throughout, and then used afterward.

Ex:

```<code>public String MakeString() {
   if (data == null)
      return "Tree is empty";

   StringBuilder sb = new StringBuilder();

   MakeString(sb);

   return sb.toString();
}

private void MakeString(StringBuilder sb) {
   if (left != null)
      left.MakeString(sb);

   sb.append(data);

   if (right != null)
      right.MakeString(sb);
}
</code>```

Body:
I made a binary search tree from scratch with my own nodes which functions perfectly when I add nodes and when I print the tree in order to the console. However, I'm having a time and a half getting the toString method working.

I changed my toString method to MakeString, because I thought it was getting confused when converting comparable type data to a string. I can either get the method to return one node or just in object form, but never the whole tree in string form. The printInOrder() method works perfectly, so why won't my MakeString() method?

public void printInOrder(){

    if (left != null) left.printInOrder();

     System.out.println(data);

    if (right != null) right.printInOrder();
}

public String MakeString(){

    String OrderedTree;
    StringBuilder sb = new StringBuilder();
    if (data == null) return "Tree is empty";

    if (left != null) left.MakeString();

     sb.append(data);

    if (right != null) right.MakeString();

Body:
If you need something to be preserved throughout the recursion, then it should be passed as a parameter. This will often result in a pair of methods if you want  to avoid having to prep the initial call or otherwise have something to do before or after the recursion.

In your case you are using a StringBuilder which needs to be created before the recursion, preserved throughout, and then used afterward.

Ex:

public String MakeString() {
   if (data == null)
      return "Tree is empty";

   StringBuilder sb = new StringBuilder();

   MakeString(sb);

   return sb.toString();
}

private void MakeString(StringBuilder sb) {
   if (left != null)
      left.MakeString(sb);

   sb.append(data);

   if (right != null)
      right.MakeString(sb);
}


问:
use variable from other function in same class codeigniter
i'm newbie codeigniter programmer.

i want to use function and all variable from this function to another function in same class controller. this my code

```<code>function page()
{

    $page_id = $this->uri->segment(3);
    $page_details = $this->m_module->submenu($page_id)->row_array();
    $data['title']= $page_details['sub_title'];
    $data['menu'] = $page_details['title'];
    $data['submenu'] = $page_details['sub_title'];
    $data['link'] = $page_details['sub_target'];
    $data['page_id'] = $page_id;
}

function employee()
    {
        $data['employee']= $this->m_module->employee()->result_array();
        $this->page();
        $this->template->display($data['link'],$data);
    }
</code>```

the problem is variable function page() can't call in function employee().

this i get at browser

```<code>A PHP Error was encountered

Severity: Notice

Message: Undefined index: link

Filename: controllers/Module.php

Line Number: 39
</code>```

please help.

Thank you

答:
You can set a class variable to pass the value of link between functions</p>

```<code><?php
    class MyController extends CI_Controller {
        private $link;

        public function page($data){
            $this->link = $data['link'];
        }

        public function page(){
            echo $this->link;
        }

    }
?>
</code>```

Body:
i'm newbie codeigniter programmer.

i want to use function and all variable from this function to another function in same class controller. this my code

function page()
{

    $page_id = $this->uri->segment(3);
    $page_details = $this->m_module->submenu($page_id)->row_array();
    $data['title']= $page_details['sub_title'];
    $data['menu'] = $page_details['title'];
    $data['submenu'] = $page_details['sub_title'];
    $data['link'] = $page_details['sub_target'];
    $data['page_id'] = $page_id;
}

function employee()
    {
        $data['employee']= $this->m_module->employee()->result_array();
        $this->page();
        $this->template->display($data['link'],$data);
    }

the problem is variable function page() can't call in function employee().

this i get at browser

A PHP Error was encountered

Severity: Notice

Message: Undefined index: link

Filename: controllers/Module.php

Line Number: 39

please help.

Thank you

Body:
You can set a class variable to pass the value of link between functions

<?php
    class MyController extends CI_Controller {
        private $link;

        public function page($data){
            $this->link = $data['link'];
        }

        public function page(){
            echo $this->link;
        }

    }
?>


问:
How could I rename the first 5 files in a folder with a different extension while keeping the old ones the same?
I have about 20 files in a folder. I want to rename the extension of the first 5 from .txt to .html. I want to keep the first 5 files with the .txt extension though. Here is what I have so far. It is a bash script</p>

```<code>cp 'ls | head -5 "files would go here I think"
</code>```

答:
You should be able to pipe these commands to get what you need.</p>

```<code>ls *.txt | head -5 | sed -e 's/.txt$//' | xargs -n1 -I% cp %.txt %.html
</code>```

Body:
I have about 20 files in a folder. I want to rename the extension of the first 5 from .txt to .html. I want to keep the first 5 files with the .txt extension though. Here is what I have so far. It is a bash script

cp 'ls | head -5 "files would go here I think"

Body:
You should be able to pipe these commands to get what you need.

ls *.txt | head -5 | sed -e 's/.txt$//' | xargs -n1 -I% cp %.txt %.html


问:
Create a Generator to read email and process messages
I am trying to write some code to read my inbox and process some attachments if present.  I decided this would be a good time to learn how generators work as I want to process all messages that have a particular subject.  I have gotten to the point where I can get all the attachments and relevant subjects but I sort of had to fake it as the iterator in the for i in range . . . was not advancing so I am advancing the latest_email_id in the loop

```<code>def read_email_from_gmail():
    try:
        print 'got here'
        mail = imaplib.IMAP4_SSL(SMTP_SERVER)
        mail.login(FROM_EMAIL,FROM_PWD)
        mail.select('inbox')

        type, data = mail.search(None, 'ALL')
        mail_ids = data[0]

        id_list = mail_ids.split()
        first_email_id = int(id_list[0])
        latest_email_id = int(id_list[-1])
        print latest_email_id

        while True:
            for i in range(latest_email_id,first_email_id - 1, -1):
                latest_email_id -= 1
                #do stuff to get attachment and subject
                yield attachment_data, subject

    except Exception, e:
        print str(e)

for attachment, subject in read_email_from_gmail():
    x = process_attachment(attachment)
    y = process_subject(subject)
</code>```

Is there a more pythonic way to advance through my in-box using a generator to hold state in the in-box?

答:
I have learned a bit more about generators and played around with the code I started with so I have a function that uses a generator to send each relevant email message subject to the main function.  This is what I have so far, and it works great for my needs

```<code>import imaplib
import email
FROM_EMAIL  = 'myemail@gmail.com'
FROM_PWD    = "mygmail_password"
SMTP_SERVER = "imap.gmail.com"
SMTP_PORT   = 993
STOP_MESSAGES = set(['Could not connect to mailbox',
                     'No Messages or None Retrieved Successfully',
                     'Could not retrieve some message',
                     'Finished processing'])

def  read_emails():
    mail = imaplib.IMAP4_SSL(SMTP_SERVER)
    mail.login(FROM_EMAIL,FROM_PWD)
    mail.select('inbox')
    con_status, data = mail.uid('search', None, "ALL")
    if con_status != 'OK':
        yield 'Could not connect to mailbox'
    try:
        mail_ids = data[0].split()
    except Exception:
        yield 'No Messages or None Retrieved Successfully'
    print mail_ids

    processed = []
    while True:
        for mail_id in mail_ids:
            status, mdata = mail.uid('fetch', mail_id, '(RFC822)')
            if status != 'OK':
                yield 'Could not retrieve some message'
            if mail_id in processed:
                yield 'Finished processing'
            raw_msg = mdata[0][1]
            structured_msg = email.message_from_string(raw_msg)
            msg_subject = structured_msg['subject']
            processed.append(mail_id)
            yield msg_subject
</code>```

To access my messages one by one, I then use the following block to get my messages

```<code>for msg_subj in read_emails():
    if msg_subj not in STOP_MESSAGES:
         do some stuff here with msg_subj
    else:
        print msg_subj
        break
</code>```

I am accessing these messages by their uid as I will be deleting them later and would like to use the uid as the key to manage deletion.  For me the trick was to collect the uid in the list named processed and then check to see if I was going to circle through them again because I was working with a uid that had already been processed.

Body:
I am trying to write some code to read my inbox and process some attachments if present.  I decided this would be a good time to learn how generators work as I want to process all messages that have a particular subject.  I have gotten to the point where I can get all the attachments and relevant subjects but I sort of had to fake it as the iterator in the for i in range . . . was not advancing so I am advancing the latest_email_id in the loop

def read_email_from_gmail():
    try:
        print 'got here'
        mail = imaplib.IMAP4_SSL(SMTP_SERVER)
        mail.login(FROM_EMAIL,FROM_PWD)
        mail.select('inbox')

        type, data = mail.search(None, 'ALL')
        mail_ids = data[0]

        id_list = mail_ids.split()
        first_email_id = int(id_list[0])
        latest_email_id = int(id_list[-1])
        print latest_email_id

        while True:
            for i in range(latest_email_id,first_email_id - 1, -1):
                latest_email_id -= 1
                #do stuff to get attachment and subject
                yield attachment_data, subject

    except Exception, e:
        print str(e)

for attachment, subject in read_email_from_gmail():
    x = process_attachment(attachment)
    y = process_subject(subject)

Is there a more pythonic way to advance through my in-box using a generator to hold state in the in-box?

Body:
I have learned a bit more about generators and played around with the code I started with so I have a function that uses a generator to send each relevant email message subject to the main function.  This is what I have so far, and it works great for my needs

import imaplib
import email
FROM_EMAIL  = 'myemail@gmail.com'
FROM_PWD    = "mygmail_password"
SMTP_SERVER = "imap.gmail.com"
SMTP_PORT   = 993
STOP_MESSAGES = set(['Could not connect to mailbox',
                     'No Messages or None Retrieved Successfully',
                     'Could not retrieve some message',
                     'Finished processing'])

def  read_emails():
    mail = imaplib.IMAP4_SSL(SMTP_SERVER)
    mail.login(FROM_EMAIL,FROM_PWD)
    mail.select('inbox')
    con_status, data = mail.uid('search', None, "ALL")
    if con_status != 'OK':
        yield 'Could not connect to mailbox'
    try:
        mail_ids = data[0].split()
    except Exception:
        yield 'No Messages or None Retrieved Successfully'
    print mail_ids

    processed = []
    while True:
        for mail_id in mail_ids:
            status, mdata = mail.uid('fetch', mail_id, '(RFC822)')
            if status != 'OK':
                yield 'Could not retrieve some message'
            if mail_id in processed:
                yield 'Finished processing'
            raw_msg = mdata[0][1]
            structured_msg = email.message_from_string(raw_msg)
            msg_subject = structured_msg['subject']
            processed.append(mail_id)
            yield msg_subject

To access my messages one by one, I then use the following block to get my messages

for msg_subj in read_emails():
    if msg_subj not in STOP_MESSAGES:
         do some stuff here with msg_subj
    else:
        print msg_subj
        break

I am accessing these messages by their uid as I will be deleting them later and would like to use the uid as the key to manage deletion.  For me the trick was to collect the uid in the list named processed and then check to see if I was going to circle through them again because I was working with a uid that had already been processed.


问:
CSRF Token is not set..How to set CSRF cookie in Typescript?
as title I have no idea how to set CSRF token inside my typescript file, I am a beginner about typescript and CSRF Token.

This is the typescript file I use to post my info.

```<code>getUsers2() {

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let body2 = {
      site: this.selectedSite,
      zone: this.selectedZone,
      user: this.username,
      categoryType: this.problemType,
      ser: 'High',
      conNo:'012-8888888'
    };

    this.http.post('http://localhost:8000/apidb/report/', JSON.stringify(body2), {headers: headers})
        .map(res => res.json())
        .subscribe(data => {
            console.log("herererererere" ,data);
        });

    this.restProvider.getUsers2().then(data2 => {
      this.locations = data2;
      console.log(this.locations);
    });
  }
</code>```

Inside my setting.py I have already install the middleware

```<code>MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
]
</code>```

In my views.py I not sure about is this correct or not

```<code>def report(request):
    import pdb; pdb.set_trace()
    if request.method == 'POST':
        z1= site(country_site="New Penang Site")
        site.save()
    else:
        return HttpResponse(request.method, content_type="application/json")
</code>```

When I post a data to my API it shows me that CSRF is not set..

Can anyone provide me any tutorial or guideline about this problem ?? Thanks !!

答:
you have to append the CSRF token to the POSTdata sent in HTTPrequest (in this case your body2 var). You'll have to check Django docs for what name they are looking for in POST (in Laravel, its '_token').

the value of this POST var will be set by echoing the token server side at the top of the page (i.e. var x = (server-side echo of CSRF token);)

Body:
as title I have no idea how to set CSRF token inside my typescript file, I am a beginner about typescript and CSRF Token.

This is the typescript file I use to post my info.

getUsers2() {

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let body2 = {
      site: this.selectedSite,
      zone: this.selectedZone,
      user: this.username,
      categoryType: this.problemType,
      ser: 'High',
      conNo:'012-8888888'
    };

    this.http.post('http://localhost:8000/apidb/report/', JSON.stringify(body2), {headers: headers})
        .map(res => res.json())
        .subscribe(data => {
            console.log("herererererere" ,data);
        });

    this.restProvider.getUsers2().then(data2 => {
      this.locations = data2;
      console.log(this.locations);
    });
  }

Inside my setting.py I have already install the middleware

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
]

In my views.py I not sure about is this correct or not

def report(request):
    import pdb; pdb.set_trace()
    if request.method == 'POST':
        z1= site(country_site="New Penang Site")
        site.save()
    else:
        return HttpResponse(request.method, content_type="application/json")

When I post a data to my API it shows me that CSRF is not set..

Can anyone provide me any tutorial or guideline about this problem ?? Thanks !!


问:
Lowercase and Uppercase are the same JS
I am creating a program that will pull up the first non repeated word within a string. While doing this I bump into a logic problem where I need to count a word in uppercase and lowercase the same but still returns the original uppercase version of the string.

Here's my codes:

```<code>function firstNonRepeatingLetter(str) {
 // split the array and transform it to lowercase
 str = str.split('');

 // create an obj that will hold the counter of each characters
 let myObj = {};

 // create a new arr for all the char w/ 1 value
 let uniq = [];

 // iterate through the splitted array
 str.forEach((char) => {
    // if the obj contains the same key (char)
   if(myObj.hasOwnProperty(char)){
      // we add 1 to its value
     myObj[char]++;
   }else{
      // otherwise we set the key value to 1
     myObj[char] = 1;
   }
 });

 // check the obj with 1 value,
 for(let prop in myObj){
  // and then push the key inside a
   // new arr with only 1 counter
   if(myObj[prop] === 1){
     uniq.push(prop);
   }
 }

 console.log(myObj);

 // return the first elem in the arr
 return uniq.length !== 0 ? uniq[0] : '';
}

firstNonRepeatingLetter('sTress') // => must return 'T' instead return 't'
firstNonRepeatingLetter('NecEssarY') // => must return 'N' instead return 'n'
</code>```

The object looks like this: { N: 1, e: 1, c: 1, E: 1, s: 2, a: 1, r: 1, Y: 1 }it counts the 'N' and 'n'separately.

Any idea how to retain the actual case without affecting the functionality?

Thanks!

答:
I suggest you convert the all the characters of the string to either lowercase or uppercase first.

```<code>var res = str.toLowerCase();
</code>```

That way it won't count the characters separately.

Title: Lowercase and Uppercase are the same JS

Body:
I am creating a program that will pull up the first non repeated word within a string. While doing this I bump into a logic problem where I need to count a word in uppercase and lowercase the same but still returns the original uppercase version of the string.

Here's my codes:

function firstNonRepeatingLetter(str) {
 // split the array and transform it to lowercase
 str = str.split('');

 // create an obj that will hold the counter of each characters
 let myObj = {};

 // create a new arr for all the char w/ 1 value
 let uniq = [];

 // iterate through the splitted array
 str.forEach((char) => {
    // if the obj contains the same key (char)
   if(myObj.hasOwnProperty(char)){
      // we add 1 to its value
     myObj[char]++;
   }else{
      // otherwise we set the key value to 1
     myObj[char] = 1;
   }
 });

 // check the obj with 1 value,
 for(let prop in myObj){
  // and then push the key inside a
   // new arr with only 1 counter
   if(myObj[prop] === 1){
     uniq.push(prop);
   }
 }

 console.log(myObj);

 // return the first elem in the arr
 return uniq.length !== 0 ? uniq[0] : '';
}

firstNonRepeatingLetter('sTress') // => must return 'T' instead return 't'
firstNonRepeatingLetter('NecEssarY') // => must return 'N' instead return 'n'

The object looks like this: { N: 1, e: 1, c: 1, E: 1, s: 2, a: 1, r: 1, Y: 1 }it counts the 'N' and 'n'separately.

Any idea how to retain the actual case without affecting the functionality?

Thanks!

Body:
I suggest you convert the all the characters of the string to either lowercase or uppercase first.

var res = str.toLowerCase();

That way it won't count the characters separately.


问:
Angular Material - show mat-error on button click
I am trying to do validation using the <mat-form-field> and <mat-error>. This works fine when user tabs out of the input without filling. But how do I force this error to show when I click a button? I am not using submit. Also, using template-driven forms.

This is my code:

HTML:

```<code><mat-form-field>
    <input matInput placeholder="Due Date" name="dueDate" [(ngModel)]="dueDate" [formControl]="dueDateValidator" required>
    <mat-error *ngIf="dueDateValidator.invalid">Due Date is required for Tasks</mat-error>
</mat-form-field>
</code>```

TS:

dueDateValidator: FormControl =  new FormControl('', [Validators.required]);

答:
See how to use a form with a custom ErrorStateMatcher

If you wish to override this behavior (e.g. to show the error as soon
  as the invalid control is dirty or when a parent form group is
  invalid), you can use the errorStateMatcher property of the matInput.
  The property takes an instance of an ErrorStateMatcher object. An
  ErrorStateMatcher must implement a single method isErrorState which
  takes the FormControl for this matInput as well as the parent form and
  returns a boolean indicating whether errors should be shown. (true
  indicating that they should be shown, and false indicating that they
  should not.)

I would make a separate file such as default.error-matcher.ts

/** Error when invalid control is dirty or touched*/
export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return !!(control && control.invalid && (control.dirty || control.touched));
  }
}
```

<p>Then in the TS file add: </p>

```matcher = new MyErrorStateMatcher();
```

<p>Then change the input to use matcher:</p>

<pre class="lang-html prettyprint-override"><code><mat-form-field>
    <input matInput placeholder="Due Date" name="dueDate" [(ngModel)]="dueDate" [formControl]="dueDateValidator" [errorStateMatcher]="matcher" required>
    <mat-error *ngIf="dueDateValidator.invalid">Due Date is required for Tasks</mat-error>
</mat-form-field>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to do validation using the <mat-form-field> and <mat-error>. This works fine when user tabs out of the input without filling. But how do I force this error to show when I click a button? I am not using submit. Also, using template-driven forms.

This is my code:

HTML:

<mat-form-field>
    <input matInput placeholder="Due Date" name="dueDate" [(ngModel)]="dueDate" [formControl]="dueDateValidator" required>
    <mat-error *ngIf="dueDateValidator.invalid">Due Date is required for Tasks</mat-error>
</mat-form-field>

TS:

dueDateValidator: FormControl =  new FormControl('', [Validators.required]);

Body:
See how to use a form with a custom ErrorStateMatcher

If you wish to override this behavior (e.g. to show the error as soon
  as the invalid control is dirty or when a parent form group is
  invalid), you can use the errorStateMatcher property of the matInput.
  The property takes an instance of an ErrorStateMatcher object. An
  ErrorStateMatcher must implement a single method isErrorState which
  takes the FormControl for this matInput as well as the parent form and
  returns a boolean indicating whether errors should be shown. (true
  indicating that they should be shown, and false indicating that they
  should not.)

I would make a separate file such as default.error-matcher.ts

/** Error when invalid control is dirty or touched*/
export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return !!(control && control.invalid && (control.dirty || control.touched));
  }
}

Then in the TS file add:

matcher = new MyErrorStateMatcher();

Then change the input to use matcher:

<mat-form-field>
    <input matInput placeholder="Due Date" name="dueDate" [(ngModel)]="dueDate" [formControl]="dueDateValidator" [errorStateMatcher]="matcher" required>
    <mat-error *ngIf="dueDateValidator.invalid">Due Date is required for Tasks</mat-error>
</mat-form-field>


问:
Unable to get maxheight on resize
I have html and script like this. I want box1 box2 box display with the same height. But when I resize browser to check, the max height is not correct.

```<code><div class="pro_intro>"
   <div class="box box1">
     something 1
   </div>
   <div class="box box2">
     something 2
   </div>
   <div class="box box3">
     something 3
   </div>
</div>

$(window).on("resize", function () {
        var max = -1;
        $(".pro_intro .box").each(function() {
            var h = $(this).outerHeight();
            max = h > max ? h : max;
        });
        $(".pro_intro .box").css("height",max);
        $(".pro_intro .box").css({'visibility':'visible'});
}).resize();
</code>```

Any suggestion for this. Thank you so much

答:
Why not to use CSS's height and max-height properties?

Something like:

.box1, .box2 {
    height: 100%;
    max-height: 300px;
}

Title: Unable to get maxheight on resize

Body:
I have html and script like this. I want box1 box2 box display with the same height. But when I resize browser to check, the max height is not correct.

"

     something 1

     something 2

     something 3

$(window).on("resize", function () {
        var max = -1;
        $(".pro_intro .box").each(function() {
            var h = $(this).outerHeight();
            max = h > max ? h : max;
        });
        $(".pro_intro .box").css("height",max);
        $(".pro_intro .box").css({'visibility':'visible'});
}).resize();

Any suggestion for this. Thank you so much


问:
Xcode -- finding dead methods in a project
I am curious if there are any tools that provide partial solutions for this.  It is a tricky problem because of performSelector . . . but a tool ought to at least be able to come up with candidates, making the human's job easier.</p>

答:
Given the very verbose but descriptive method names often chosen in Objective-C programs, I find that doing a textual Find In Project is usually sufficient.  I will usually just use the first part of a method name so as to avoid having to match method arguments.  This will match normal method calls and use of @selector and NSSelectorFromString.

Of course, this won't work for very common method names or if you need the rest of the method name to disambiguate between many similar methods, but I find that to be a rare occurrence.


问:
JQuery change inner text but preserve html
I would like to change the text of a HTML element but preserve the rest of the inner html with jQuery.

For instance:

```<code><a href="link.html">Some text <img src="image.jpg" /></a>
</code>```

replace "Some text" with "Other text", and the result should look like:

```<code><a href="link.html">Other text <img src="image.jpg" /></a>
</code>```

EDIT:
My current solution is following:

```<code>var aElem = $('a');
var children = aElem.children();

aElem.text("NEW TEXT");
aElem.append(children);
</code>```

But there must be some more elegant way of doing this.

答:
You can change it by .contents()

```<code>$('.yourElement').contents()[0].data = 'New Data';
</code>```

where in your case the "[0].data" is your text data

Body:
I would like to change the text of a HTML element but preserve the rest of the inner html with jQuery.

For instance:

Some text

replace "Some text" with "Other text", and the result should look like:

Other text

EDIT:
My current solution is following:

var aElem = $('a');
var children = aElem.children();

aElem.text("NEW TEXT");
aElem.append(children);

But there must be some more elegant way of doing this.

Body:
You can change it by .contents()

$('.yourElement').contents()[0].data = 'New Data';

where in your case the "[0].data" is your text data


问:
Python Data File Access both Locally and in Distributed Package
Is there a pythonic way to access data files both in local testing of a module and in the distributed package (e.g. with wheel)?

Specifically, I have the same question as the comment linked below.

Python Access Data in Package Subdirectory

答: Putting packages in setup.py in the argument setup(..., data_files=[('', YOUR_DATA_FILES)],...) (the '' is the significant part) copies them in-place, and they can be accessed as they would otherwise be, both in local testing and when distributed.


问:
How to get credentials from Azure Linux VM (kubernetes cluster) on machine different from where it was created?

I need to gain access to Kubernetes cluster in Azure on a Windows Server 2016 machine. I did not create the cluster but I am assigned as Global Admin in the Azure Account. I already made a successful login to the azure account, but not yet to the server. I already installed kubectl CLI in the machine.
Now I need to access the cluster.

I have .kube/config, .ssh/id_rsa and .ssh/id_rsa.pub inside my C:\Users\Administrator folder. I have tried the ssh -i ~/.ssh/id_rsa kubectluser@ourDNSname and I was able to access it. So my private key is good. But, I don't want to work inside the VM. My working directory is supposed to be inside the WinServer2016 machine. I should be able to kubectl get nodes and it must return me a table of the 3 VMs.

This is what happens though (AGAIN, the ssh to VM works, I can do the kubectl commands w/o problem inside the VM)

```<code>az acs kubernetes get-credentials --resource-group=myRGroup --name=myClusterName
</code>```

returns

```<code>Authentication failed. Traceback (most recent call last): File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\azure\cli\main.py", line 36, in main cmd_result = APPLICATION.execute(args) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\azure\cli\core\application.py", line 216, in execute result = expanded_arg.func(params) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\azure\cli\core\commands\__init__.py", line 377, in __call__ return self.handler(*args, **kwargs) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\azure\cli\core\commands\__init__.py", line 620, in _execute_command reraise(*sys.exc_info()) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\six.py", line 693, in reraise raise value File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\azure\cli\core\commands\__init__.py", line 602, in _execute_command result = op(client, **kwargs) if client else op(**kwargs) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\azure\cli\command_modules\acs\custom.py", line 776, in k8s_get_credentials _k8s_get_credentials_internal(name, acs_info, path, ssh_key_file) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\azure\cli\command_modules\acs\custom.py", line 797, in _k8s_get_credentials_internal '.kube/config', path_candidate, key_filename=ssh_key_file) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\azure\cli\command_modules\acs\acs_client.py", line 72, in secure_copy ssh.connect(host, username=user, pkey=pkey, sock=proxy) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\paramiko\client.py", line 416, in connect look_for_keys, gss_auth, gss_kex, gss_deleg_creds, t.gss_host, File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\paramiko\client.py", line 701, in _auth raise saved_exception File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\paramiko\client.py", line 678, in _auth self._transport.auth_publickey(username, key)) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\paramiko\transport.py", line 1447, in auth_publickey return self.auth_handler.wait_for_response(my_event) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\paramiko\auth_handler.py", line 223, in wait_for_response raise e paramiko.ssh_exception.AuthenticationException: Authentication failed.
</code>```

```<code>kubectl get nodes
</code>```

returns

```<code>You must be logged in to the server
</code>```

I can't use kubectl create or kubectl set image deployment because of this.

What do I need to do? What information do I need from the person and machine who/which created the cluster?

Edit:

答:
I have .kube/config, .ssh/id_rsa and .ssh/id_rsa.pub inside my
  C:\Users\Administrator folder.

The default path to an SSH key file is ~\.ssh\id_rsa, in Windows, we should specify the path, like this:

```<code>C:\Users\jason\.ssh>az acs kubernetes get-credentials --resource-group=jasonk8s --name jasonk8s --ssh-key-file C:\Users\jason\.ssh\k8s
Merged "jasontest321mgmt" as current context in C:\Users\jason\.kube\config
C:\Users\jason\.ssh>kubectl.exe get nodes
NAME                    STATUS    ROLES     AGE       VERSION
k8s-agent-c99b4149-0    Ready     agent     7m        v1.7.7
k8s-master-c99b4149-0   Ready     master    8m        v1.7.7
</code>```

In your scenario, please try to use this script to get credentials:

```<code>az acs kubernetes get-credentials --resource-group=myRGroup --name=myClusterName --ssh-key-file C:\Users\Administrator\.ssh\id_rsa
</code>```

Body:
I need to gain access to Kubernetes cluster in Azure on a Windows Server 2016 machine. I did not create the cluster but I am assigned as Global Admin in the Azure Account. I already made a successful login to the azure account, but not yet to the server. I already installed kubectl CLI in the machine.
Now I need to access the cluster.

I have .kube/config, .ssh/id_rsa and .ssh/id_rsa.pub inside my C:\Users\Administrator folder. I have tried the ssh -i ~/.ssh/id_rsa kubectluser@ourDNSname and I was able to access it. So my private key is good. But, I don't want to work inside the VM. My working directory is supposed to be inside the WinServer2016 machine. I should be able to kubectl get nodes and it must return me a table of the 3 VMs.

This is what happens though (AGAIN, the ssh to VM works, I can do the kubectl commands w/o problem inside the VM)

az acs kubernetes get-credentials --resource-group=myRGroup --name=myClusterName

returns

Authentication failed. Traceback (most recent call last): File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\azure\cli\main.py", line 36, in main cmd_result = APPLICATION.execute(args) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\azure\cli\core\application.py", line 216, in execute result = expanded_arg.func(params) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\azure\cli\core\commands\__init__.py", line 377, in __call__ return self.handler(*args, **kwargs) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\azure\cli\core\commands\__init__.py", line 620, in _execute_command reraise(*sys.exc_info()) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\six.py", line 693, in reraise raise value File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\azure\cli\core\commands\__init__.py", line 602, in _execute_command result = op(client, **kwargs) if client else op(**kwargs) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\azure\cli\command_modules\acs\custom.py", line 776, in k8s_get_credentials _k8s_get_credentials_internal(name, acs_info, path, ssh_key_file) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\azure\cli\command_modules\acs\custom.py", line 797, in _k8s_get_credentials_internal '.kube/config', path_candidate, key_filename=ssh_key_file) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\azure\cli\command_modules\acs\acs_client.py", line 72, in secure_copy ssh.connect(host, username=user, pkey=pkey, sock=proxy) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\paramiko\client.py", line 416, in connect look_for_keys, gss_auth, gss_kex, gss_deleg_creds, t.gss_host, File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\paramiko\client.py", line 701, in _auth raise saved_exception File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\paramiko\client.py", line 678, in _auth self._transport.auth_publickey(username, key)) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\paramiko\transport.py", line 1447, in auth_publickey return self.auth_handler.wait_for_response(my_event) File "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\lib\site-packages\paramiko\auth_handler.py", line 223, in wait_for_response raise e paramiko.ssh_exception.AuthenticationException: Authentication failed.

kubectl get nodes

returns

You must be logged in to the server

I can't use kubectl create or kubectl set image deployment because of this.

What do I need to do? What information do I need from the person and machine who/which created the cluster?

Edit:

Body:
I have .kube/config, .ssh/id_rsa and .ssh/id_rsa.pub inside my
  C:\Users\Administrator folder.

The default path to an SSH key file is ~\.ssh\id_rsa, in Windows, we should specify the path, like this:

C:\Users\jason\.ssh>az acs kubernetes get-credentials --resource-group=jasonk8s --name jasonk8s --ssh-key-file C:\Users\jason\.ssh\k8s
Merged "jasontest321mgmt" as current context in C:\Users\jason\.kube\config
C:\Users\jason\.ssh>kubectl.exe get nodes
NAME                    STATUS    ROLES     AGE       VERSION
k8s-agent-c99b4149-0    Ready     agent     7m        v1.7.7
k8s-master-c99b4149-0   Ready     master    8m        v1.7.7

In your scenario, please try to use this script to get credentials:

az acs kubernetes get-credentials --resource-group=myRGroup --name=myClusterName --ssh-key-file C:\Users\Administrator\.ssh\id_rsa


问:
Too many redirect with pagination query string
I am trying to redirect pages

From:
mysite.com/cata/catb

To mysite.com/cata/catb?p=1

But it is ending up with so many p=1

i.e mysite.com/cata/catb?p=1?p=1?p=1?p=1?p=1?p=1?p=1?p=1?p=1

My .htaccess is

```<code>redirect 301 ^/cata/catb$ /cata/catb?p=1
</code>```

Can someone please tell me what is wrong here.

答:
I have the feeling that your redirect 301 ^/cata/catb$ /cata/catb?p=1 redirect regex applies only on the path path of your URL and ignores your ending parameters ?p=1

Therefore the redirection is done in a kind of recursively manner:

```<code>/cata/catb →　/cata/catb?p=1
/cata/catb?p=1　→　/cata/catb?p=1?p=1
/cata/catb?p=1?p=1　→　/cata/catb?p=1?p=1?p=1
...
</code>```

Could you try changing your

redirect 301 ^/cata/catb$ /cata/catb?p=1 in redirect 301 ^/cata/catb$ /cata/catc?p=1 and check the output?

or adding a trailing "/"to your path -> /cata/catb/?p=1 even if it is far from being sexy.

You might also be interested by the following commands RedirectMatch and RewriteEngine on:

https://superuser.com/questions/155139/htaccess-301-redirect-with-regular-expressions

Good luck!

Body:
I am trying to redirect pages

From:
mysite.com/cata/catb

To mysite.com/cata/catb?p=1

But it is ending up with so many p=1

i.e mysite.com/cata/catb?p=1?p=1?p=1?p=1?p=1?p=1?p=1?p=1?p=1

My .htaccess is

redirect 301 ^/cata/catb$ /cata/catb?p=1

Can someone please tell me what is wrong here.

Body:
I have the feeling that your redirect 301 ^/cata/catb$ /cata/catb?p=1 redirect regex applies only on the path path of your URL and ignores your ending parameters ?p=1

Therefore the redirection is done in a kind of recursively manner:

/cata/catb →　/cata/catb?p=1
/cata/catb?p=1　→　/cata/catb?p=1?p=1
/cata/catb?p=1?p=1　→　/cata/catb?p=1?p=1?p=1
...

Could you try changing your

redirect 301 ^/cata/catb$ /cata/catb?p=1 in redirect 301 ^/cata/catb$ /cata/catc?p=1 and check the output?

or adding a trailing "/"to your path -> /cata/catb/?p=1 even if it is far from being sexy.

You might also be interested by the following commands RedirectMatch and RewriteEngine on:

https://superuser.com/questions/155139/htaccess-301-redirect-with-regular-expressions

Good luck!


问:
interchangeable shebang line in Python script for dual OSes?
A script is developed both on OS X and Windows using a virtualenv. The so-called developer has already installed all required packages using a requirements.txt file, but one problem remains:

If the script is running on OS X, the beginning of each Python file must start like this:

```<code>#!/Users/os-x-username/.virtualenvs/some_env/bin/python
#!C:\Users\windows-username\Envs\some_env\Scripts\python.exe
</code>```

But if developing on Windows, the line order must be switched:

```<code>#!C:\Users\windows-username\Envs\some_env\Scripts\python.exe
#!/Users/os-x-username/.virtualenvs/some_env/bin/python
</code>```

How can the so-called developer avoid this tediousness?

答:
If you don't mind adding extra steps, ou can create a launcher script launcher.py like:

```<code>#!/usr/bin/env python

import subprocess
import sys

if __name__ != "__main__":
    print("This is a launcher. Please run only as a main script.")
    exit(-1)

INTERPRETERS = {
    "win": r"C:\Users\windows-username\Envs\some_env\Scripts\python.exe",  # Windows
    "darwin": "/Users/os-x-username/.virtualenvs/some_env/bin/python",  # OSX
    "linux": "/home/linux-user/.virtualenvs/some_env/bin/python"  # Linux
    # etc.
}

TARGET_SCRIPT = "original_script_name.py"

interpreter = None
for i in INTERPRETERS:  # let's find a suitable interpreter for the current platform
    if sys.platform.startswith(i):
        interpreter = i
        break
if not interpreter:
    print("No suitable interpreter found for platform:", sys.platform)
    exit(-1)

main_proc = subprocess.Popen([interpreter, TARGET_SCRIPT] + sys.argv[1:])  # call virtualenv
main_proc.communicate()  # wait for it to finish

exit(main_proc.poll())  # redirect the return code
</code>```

Since this script is there only to run the original_script_name.py in the desired interpreter for the current platform, it doesn't matter what its shebang is - as long as it picks any Python interpreter it will be fine.

It would act as a drop-in replacement for your original script (original_script_name.py) so just call launcher.py instead and it will even redirect the CLI arguments if needed.

Body:
A script is developed both on OS X and Windows using a virtualenv. The so-called developer has already installed all required packages using a requirements.txt file, but one problem remains:

If the script is running on OS X, the beginning of each Python file must start like this:

#!/Users/os-x-username/.virtualenvs/some_env/bin/python
#!C:\Users\windows-username\Envs\some_env\Scripts\python.exe

But if developing on Windows, the line order must be switched:

#!C:\Users\windows-username\Envs\some_env\Scripts\python.exe
#!/Users/os-x-username/.virtualenvs/some_env/bin/python

How can the so-called developer avoid this tediousness?

Body:
If you don't mind adding extra steps, ou can create a launcher script launcher.py like:

#!/usr/bin/env python

import subprocess
import sys

if __name__ != "__main__":
    print("This is a launcher. Please run only as a main script.")
    exit(-1)

INTERPRETERS = {
    "win": r"C:\Users\windows-username\Envs\some_env\Scripts\python.exe",  # Windows
    "darwin": "/Users/os-x-username/.virtualenvs/some_env/bin/python",  # OSX
    "linux": "/home/linux-user/.virtualenvs/some_env/bin/python"  # Linux
    # etc.
}

TARGET_SCRIPT = "original_script_name.py"

interpreter = None
for i in INTERPRETERS:  # let's find a suitable interpreter for the current platform
    if sys.platform.startswith(i):
        interpreter = i
        break
if not interpreter:
    print("No suitable interpreter found for platform:", sys.platform)
    exit(-1)

main_proc = subprocess.Popen([interpreter, TARGET_SCRIPT] + sys.argv[1:])  # call virtualenv
main_proc.communicate()  # wait for it to finish

exit(main_proc.poll())  # redirect the return code

Since this script is there only to run the original_script_name.py in the desired interpreter for the current platform, it doesn't matter what its shebang is - as long as it picks any Python interpreter it will be fine.

It would act as a drop-in replacement for your original script (original_script_name.py) so just call launcher.py instead and it will even redirect the CLI arguments if needed.


问:
tortoise svn giving me "Redirect cycle detected for URL 'domain/svn'"
I want to achieve a svn-root in /var/svn and repositories(projects) in there.
I could get it to work in the browser (http://domain/url gives me "Collection of repositories") but the TortoiseClient is giving me the error mentioned in the title.

I set up a subversion on my ubuntu server by doing the following (shortened):

```<code>mkdir /var/svn
svnadmin create /var/svn/test
</code>```

and my dav_svn.conf looks the following:

```<code><Location /svn>
  DAV svn
  SVNParentPath /var/svn
  SVNListParentPath On
</Location>
</code>```

I read about sym links possibly causing the problem, so I'll attach my 000-default site as well (it's the standard btw):

```<code><VirtualHost *:80>
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory /var/www/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            allow from all
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
    Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>
</code>```

I tried like suggested in How do I list all repositories with the SVNParentPath directive on Apache+SVN?
but unfortunately I get another tortoise error then (while I can still see it fine in my browser)
It then gives me "The OPTIONS request returned invalid XML in the response: XML parse error at line 1: no element found"
(and HTTP OPTIONS to that url indeed gives no response body)

Does anyone know what is causing this problem?

Cheers!

Edit: This is the access.log output after trying to reach http://server/svn through tortoise

(with Location /svn)
Notice the 301 .. TortoiseSVN changes the path to 'http://server/svn' without a leading slash, tho I specified to search within 'http://server/svn / '

```<code>[10/May/2012:00:42:29 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:29 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:29 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:29 +0200] "PROPFIND /svn HTTP/1.1" 301 516 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:29 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:29 +0200] "PROPFIND /svn HTTP/1.1" 301 516 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "PROPFIND /svn HTTP/1.1" 301 516 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "OPTIONS / HTTP/1.1" 200 236 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
</code>```

(with Location /svn/)

```<code>[10/May/2012:00:36:57 +0200] "OPTIONS /svn HTTP/1.1" 200 236 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:36:57 +0200] "OPTIONS /svn HTTP/1.1" 200 236 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:36:57 +0200] "OPTIONS /svn HTTP/1.1" 200 236 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:36:57 +0200] "OPTIONS /svn HTTP/1.1" 200 236 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:36:58 +0200] "OPTIONS /svn HTTP/1.1" 200 236 "-" "SVN/1.7.4 neon/0.29.6"
[10/May/2012:00:36:58 +0200] "OPTIONS /svn HTTP/1.1" 200 236 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:36:58 +0200] "OPTIONS /svn HTTP/1.1" 200 236 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:36:58 +0200] "OPTIONS / HTTP/1.1" 200 236 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
</code>```

答:
Adding the:

```<code>SVNListParentPath on
</code>```

line alone solved this issue for me.

Body:
I want to achieve a svn-root in /var/svn and repositories(projects) in there.
I could get it to work in the browser (http://domain/url gives me "Collection of repositories") but the TortoiseClient is giving me the error mentioned in the title.

I set up a subversion on my ubuntu server by doing the following (shortened):

mkdir /var/svn
svnadmin create /var/svn/test

and my dav_svn.conf looks the following:

<Location /svn>
  DAV svn
  SVNParentPath /var/svn
  SVNListParentPath On
</Location>

I read about sym links possibly causing the problem, so I'll attach my 000-default site as well (it's the standard btw):

<VirtualHost *:80>
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    </Directory>
    <Directory /var/www/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            allow from all
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
    Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>

I tried like suggested in How do I list all repositories with the SVNParentPath directive on Apache+SVN?
but unfortunately I get another tortoise error then (while I can still see it fine in my browser)
It then gives me "The OPTIONS request returned invalid XML in the response: XML parse error at line 1: no element found"
(and HTTP OPTIONS to that url indeed gives no response body)

Does anyone know what is causing this problem?

Cheers!

Edit: This is the access.log output after trying to reach http://server/svn through tortoise

(with Location /svn)
Notice the 301 .. TortoiseSVN changes the path to 'http://server/svn' without a leading slash, tho I specified to search within 'http://server/svn / '

[10/May/2012:00:42:29 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:29 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:29 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:29 +0200] "PROPFIND /svn HTTP/1.1" 301 516 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:29 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:29 +0200] "PROPFIND /svn HTTP/1.1" 301 516 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "PROPFIND /svn HTTP/1.1" 301 516 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "OPTIONS /svn HTTP/1.1" 301 573 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:42:30 +0200] "OPTIONS / HTTP/1.1" 200 236 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"

(with Location /svn/)

[10/May/2012:00:36:57 +0200] "OPTIONS /svn HTTP/1.1" 200 236 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:36:57 +0200] "OPTIONS /svn HTTP/1.1" 200 236 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:36:57 +0200] "OPTIONS /svn HTTP/1.1" 200 236 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:36:57 +0200] "OPTIONS /svn HTTP/1.1" 200 236 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:36:58 +0200] "OPTIONS /svn HTTP/1.1" 200 236 "-" "SVN/1.7.4 neon/0.29.6"
[10/May/2012:00:36:58 +0200] "OPTIONS /svn HTTP/1.1" 200 236 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:36:58 +0200] "OPTIONS /svn HTTP/1.1" 200 236 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"
[10/May/2012:00:36:58 +0200] "OPTIONS / HTTP/1.1" 200 236 "-" "SVN/1.7.4/TortoiseSVN-1.7.6.22632 neon/0.29.6"

Body:
Adding the:

SVNListParentPath on

line alone solved this issue for me.


问:
Can I associate custom metadata with an ALAsset?
I'm building an iPhone app that, among other things, allows the user to take and store photographs associated with locations.  I am currently using the ALAssetLibrary to allow the photographs to be stored in Photos and be accessible outside the app (on a computer for instance via the built-in mechanisms).  There is not a lot of technical content out there for working with the ALAssetLibrary but from what there is I have managed to cobble together a working version of this.  I have had to resort to storing a dictionary of photo URLS in my app and manually detecting if the photo still exists when displaying lists of them because there does not seem to be a way to add custom metadata to an ALAsset.

What I would really like to do is add two custom metadata fields to each asset to provide it with a title and a custom id value that I can use to filter on when enumerating the asset library.

As a secondary task, I'd like the user to be able to update the title metadata.

Can it be done?  At this point, I really don't think it can because the API really doesn't seem to provide the necessary methods to get/set custom metadata.  I'm hoping against all odds that there is some other aspect to the AssetLibrary framework that I have not yet discovered.

At a minimum, if someone can authoritatively say "NO" then at least others might find this breadcrumb on their own trail of hope and change tack more quickly!

And, having 0 reputation I can't tag it with AssetLibrary :( wow, this day is just going downhill.  FML

答:
I've been looking over the documentation and I dont think it is possible to tack on additional fields to the ALAsset object, well you can create your own object or extend theirs but that wont help you when your pulling back assets because you'll need to init yours and populate it then.

Look I know this falls short of a really good answer but I had to try.


问:
Returning a resolved value from 'fetch'
I'm trying to use fetch to get a JSON object from an API, I want to return the final resolved value of the object so that any one who uses the function can directly get the value without any need to resolve the promise it returns.

function f() {
    let result = fetch(url, {
        method: 'GET'
    })
    .then(response => response.json())
    .then(json => {
        return json
    }).catch(err => {
        // Error
    });

    return result;
}```

I don't really know if this is possible or not, but I'll be thankful for help, Thanks in advance.

答:
It is not possible with fetch. It is asynchronous.

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

You could do it with old XMLHttpRequest, it has the special argument for sync calls https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open . I would not recommend it though, it will freeze you ui.

Title: Returning a resolved value from 'fetch'

Body:
I'm trying to use fetch to get a JSON object from an API, I want to return the final resolved value of the object so that any one who uses the function can directly get the value without any need to resolve the promise it returns.

function f() {
    let result = fetch(url, {
        method: 'GET'
    })
    .then(response => response.json())
    .then(json => {
        return json
    }).catch(err => {
        // Error
    });

    return result;
}

I don't really know if this is possible or not, but I'll be thankful for help, Thanks in advance.


问:
PDO::fetchAll not working with MySQL stored procedure
I'm trying to return a row from a database by calling a stored procedure throught PHP. However, when I do this how I normally would I get a "General Error".

```<code>Fatal error:  Uncaught PDOException: SQLSTATE[HY000]: General error in C:\xampp\htdocs\Skilaverkefni 4\Courses\read.php:11
Stack trace:
#0 C:\xampp\htdocs\Skilaverkefni 4\Courses\read.php(11): PDOStatement->fetchAll(2)
#1 C:\xampp\htdocs\Skilaverkefni 4\index.php(13): ReadCourse('FOR3L3U')
#2 {main}
  thrown in C:\xampp\htdocs\Skilaverkefni 4\Courses\read.php on line 11
</code>```

Here is the code:

```<code><?php

    function ReadCourse($courseID)
    {

        require "dbCon.php";
        $SQL = "SET @p0='" . $courseID . "'; CALL ReadCourse(@p0);";
        echo "$SQL";
        $logon = $pdo->prepare($SQL);
        $logon->execute();
        $records = $logon->fetchAll(PDO::FETCH_ASSOC);

        print_r($records);

    }

?>
</code>```

After a long Google-session I found out that the issue is most caused by the way I'm handling the reading of the data returned from the stored procedure, how do I do this correctly?

答:
The whole point of PDO is to make it impossible to run any old database query you choose to pass as a string.

From the documentation:

```<code><?php
/* Call a stored procedure with an INOUT parameter */
$colour = 'red';
$sth = $dbh->prepare('CALL puree_fruit(?)');
$sth->bindParam(1, $colour, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 12);
$sth->execute();
print("After pureeing fruit, the colour is: $colour");
?>
</code>```

Body:
I'm trying to return a row from a database by calling a stored procedure throught PHP. However, when I do this how I normally would I get a "General Error".

Fatal error:  Uncaught PDOException: SQLSTATE[HY000]: General error in C:\xampp\htdocs\Skilaverkefni 4\Courses\read.php:11
Stack trace:
#0 C:\xampp\htdocs\Skilaverkefni 4\Courses\read.php(11): PDOStatement->fetchAll(2)
#1 C:\xampp\htdocs\Skilaverkefni 4\index.php(13): ReadCourse('FOR3L3U')
#2 {main}
  thrown in C:\xampp\htdocs\Skilaverkefni 4\Courses\read.php on line 11

Here is the code:

<?php

    function ReadCourse($courseID)
    {

        require "dbCon.php";
        $SQL = "SET @p0='" . $courseID . "'; CALL ReadCourse(@p0);";
        echo "$SQL";
        $logon = $pdo->prepare($SQL);
        $logon->execute();
        $records = $logon->fetchAll(PDO::FETCH_ASSOC);

        print_r($records);

    }

?>

After a long Google-session I found out that the issue is most caused by the way I'm handling the reading of the data returned from the stored procedure, how do I do this correctly?

Body:
The whole point of PDO is to make it impossible to run any old database query you choose to pass as a string.

From the documentation:

<?php
/* Call a stored procedure with an INOUT parameter */
$colour = 'red';
$sth = $dbh->prepare('CALL puree_fruit(?)');
$sth->bindParam(1, $colour, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 12);
$sth->execute();
print("After pureeing fruit, the colour is: $colour");
?>


问:
How to trigger a method once an option from a drop down list is selected in Rails?
So the code for the drop down list is the following, and once the user clicks on one of the options I want to trigger a method in the controller, but not sure how.  And how do I access the value from the controller page?  </p>

```<code><select>
  <option value="" selected="selected">Please select</option>
  <option value="1">Administrator</option>
  <option value="2">User</option>
  <option value="3">Editor</option>
</select>
</code>```

答:
You can use the onChange feature in jQuery in combination with Ajax.

```<code>$('select').on('change', function() {
  $.ajax({
    url : '/users',
    type : 'GET',
    data : { user_id: this.value },
    dataType:'script'
  });
})
</code>```

You will also need to add your method in your routes.rb

Body:
So the code for the drop down list is the following, and once the user clicks on one of the options I want to trigger a method in the controller, but not sure how.  And how do I access the value from the controller page?

<select>
  <option value="" selected="selected">Please select</option>
  <option value="1">Administrator</option>
  <option value="2">User</option>
  <option value="3">Editor</option>
</select>

Body:
You can use the onChange feature in jQuery in combination with Ajax.

$('select').on('change', function() {
  $.ajax({
    url : '/users',
    type : 'GET',
    data : { user_id: this.value },
    dataType:'script'
  });
})

You will also need to add your method in your routes.rb


问:
ajax innerHTML result doesn`t return html code from PHP
ajax:

```<code>$.ajax({
type: "POST",
url: "calculator/panouri-simple/calcul-panouri-simple.php",
data:  $("#formular_comanda").serialize(),
success: function(result)
{
     document.getElementById("show_panels").innerHTML = result;
},
error: function(result)
{
     console.log("Eroare:");
     console.log(result);
}
});
</code>```

HTML:

```<code><div id="show_panels"></div>
</code>```

when I look into "View page source" on browser, there is no html code between
 and
.

result from ajax is returning some inputs and I call those inputs with another ajax, but in html page source, those inputs are not there.

They are visually in browser, but the html code is not present in source code. I hope you understand what do I mean here. Look at the photos.

I am calling those inputs names in a php file and I get undefined variabile .... This is my problem. Visually, the inputs are there but no html code.

Debugger:

答:
Can I ask why you're using the traditional JavaScript document.getElementById when you've loaded jQuery and are using the syntax for it? You use a jQuery selector $("#formular_comanda").serialize() when you send the data to .ajax. Why not do something like...

```<code>success: function(result) {
    $("#show_panels").html(result);
},
</code>```

Is your PHP file calculator/panouri-simple/calcul-panouri-simple.php expecting any GET parameters? Or anything in the POST that isn't being sent? Does the error appear in the console (you wrote with console.log), since the thing didn't go through?

Is your jQuery snippet, where you call the .ajax statement, inside of an event handler like

```<code>$(document).ready(function() {
    // ...
});
</code>```

or is it just in the source as it is?

Body:
ajax:

$.ajax({
type: "POST",
url: "calculator/panouri-simple/calcul-panouri-simple.php",
data:  $("#formular_comanda").serialize(),
success: function(result)
{
     document.getElementById("show_panels").innerHTML = result;
},
error: function(result)
{
     console.log("Eroare:");
     console.log(result);
}
});

HTML:

when I look into "View page source" on browser, there is no html code between
 and
.

result from ajax is returning some inputs and I call those inputs with another ajax, but in html page source, those inputs are not there.

They are visually in browser, but the html code is not present in source code. I hope you understand what do I mean here. Look at the photos.

I am calling those inputs names in a php file and I get undefined variabile .... This is my problem. Visually, the inputs are there but no html code.

Debugger:

Body:
Can I ask why you're using the traditional JavaScript document.getElementById when you've loaded jQuery and are using the syntax for it? You use a jQuery selector $("#formular_comanda").serialize() when you send the data to .ajax. Why not do something like...

success: function(result) {
    $("#show_panels").html(result);
},

Is your PHP file calculator/panouri-simple/calcul-panouri-simple.php expecting any GET parameters? Or anything in the POST that isn't being sent? Does the error appear in the console (you wrote with console.log), since the thing didn't go through?

Is your jQuery snippet, where you call the .ajax statement, inside of an event handler like

$(document).ready(function() {
    // ...
});

or is it just in the source as it is?


问:
"NOT IN" with HQL and Grails
The following query should select all organisations that are not in the excludedOrgs:

```<code>Organisation.findAll("from Organisation o where o not in elements(?)",
    [excludedOrgs])
</code>```

All I get is an org.springframework.orm.hibernate3.HibernateQueryException telling me: expecting IDENT, found '?'

I'm using Grails 1.3.6.

What's wrong with my query?

答:
both should work (as named and positional params are allowed)</p>

```<code>Organisation.findAll("from Organisation o where o not in (?)", [excludedOrgs])

Organisation.findAll("from Organisation o where o not in (:excludedOrgs)", ["excludedOrgs":excludedOrgs])
</code>```

Title: "NOT IN" with HQL and Grails

Body:
The following query should select all organisations that are not in the excludedOrgs:

Organisation.findAll("from Organisation o where o not in elements(?)",
    [excludedOrgs])

All I get is an org.springframework.orm.hibernate3.HibernateQueryException telling me: expecting IDENT, found '?'

I'm using Grails 1.3.6.

What's wrong with my query?

Body:
both should work (as named and positional params are allowed)

Organisation.findAll("from Organisation o where o not in (?)", [excludedOrgs])

Organisation.findAll("from Organisation o where o not in (:excludedOrgs)", ["excludedOrgs":excludedOrgs])


问:
How to draw charts without displaying it's data in the sheet?
I'm trying to display charts in a Google Sheet using Google App Script.

It appears to me that the only way to feed data to a chart is through displaying this data on a sheet and passing the data's range to the chart. As such:

```<code>var chart = SpreadsheetApp.getActiveSheet().newChart().asPieChart()
    .addRange(range)
    .build();

SpreadsheetApp.getActiveSheet().insertChart(chart);
</code>```

Where range is a range in the sheet holding the chart's data.

My question is if there is a way to display the chart without having to display it's raw data as such ?

答:
How about these workarounds? I couldn't find how to create charts without range of spreadsheet for EmbeddedChartBuilder. So I thought other 2 workarounds.

Workaround 1

In this case, in order to display no data for charts, it uses a range of other spreadsheet.

```<code>var id = "### spreadsheet id ###"; // There is data in this spreadsheet.
var name = "### sheet name ###";
var datarange = "### data range ###";
var range = SpreadsheetApp.openById(id).getSheetByName(name).getRange(datarange);
var chart = SpreadsheetApp.getActiveSheet().newChart().asPieChart()
  .addRange(range)
  .build();
SpreadsheetApp.getActiveSheet().insertChart(chart);
</code>```

Workaround 2

In this case, in order to display no data for charts, it reads data using newDataTable(). You can add your data to newDataTable().

The created chart is imported to spreadsheet as an image. The chart sample is from here.

```<code>var data = Charts.newDataTable()
    .addColumn(Charts.ColumnType.STRING, 'Month')
    .addColumn(Charts.ColumnType.NUMBER, 'In Store')
    .addColumn(Charts.ColumnType.NUMBER, 'Online')
    .addRow(['January', 10, 1])
    .addRow(['February', 12, 1])
    .addRow(['March', 20, 2])
    .addRow(['April', 25, 3])
    .addRow(['May', 30, 4])
    .build();

var chart = Charts.newAreaChart()
    .setDataTable(data)
    .setStacked()
    .setRange(0, 40)
    .setTitle('Sales per Month')
    .build().getBlob();

SpreadsheetApp.getActiveSheet().insertImage(chart, 1, 1);
</code>```

References :

EmbeddedChartBuilder

Charts Service

If these are not useful for you, I'm sorry.

Body:
I'm trying to display charts in a Google Sheet using Google App Script.

It appears to me that the only way to feed data to a chart is through displaying this data on a sheet and passing the data's range to the chart. As such:

var chart = SpreadsheetApp.getActiveSheet().newChart().asPieChart()
    .addRange(range)
    .build();

SpreadsheetApp.getActiveSheet().insertChart(chart);

Where range is a range in the sheet holding the chart's data.

My question is if there is a way to display the chart without having to display it's raw data as such ?

Body:
How about these workarounds? I couldn't find how to create charts without range of spreadsheet for EmbeddedChartBuilder. So I thought other 2 workarounds.

Workaround 1

In this case, in order to display no data for charts, it uses a range of other spreadsheet.

var id = "### spreadsheet id ###"; // There is data in this spreadsheet.
var name = "### sheet name ###";
var datarange = "### data range ###";
var range = SpreadsheetApp.openById(id).getSheetByName(name).getRange(datarange);
var chart = SpreadsheetApp.getActiveSheet().newChart().asPieChart()
  .addRange(range)
  .build();
SpreadsheetApp.getActiveSheet().insertChart(chart);

Workaround 2

In this case, in order to display no data for charts, it reads data using newDataTable(). You can add your data to newDataTable().

The created chart is imported to spreadsheet as an image. The chart sample is from here.

var data = Charts.newDataTable()
    .addColumn(Charts.ColumnType.STRING, 'Month')
    .addColumn(Charts.ColumnType.NUMBER, 'In Store')
    .addColumn(Charts.ColumnType.NUMBER, 'Online')
    .addRow(['January', 10, 1])
    .addRow(['February', 12, 1])
    .addRow(['March', 20, 2])
    .addRow(['April', 25, 3])
    .addRow(['May', 30, 4])
    .build();

var chart = Charts.newAreaChart()
    .setDataTable(data)
    .setStacked()
    .setRange(0, 40)
    .setTitle('Sales per Month')
    .build().getBlob();

SpreadsheetApp.getActiveSheet().insertImage(chart, 1, 1);

References :

EmbeddedChartBuilder

Charts Service

If these are not useful for you, I'm sorry.