答:
I think this is what you meant, to write lines which are not present infruits list and also lines which is not in uppercase letters and  to preserve the order you can use differnce of set intersetion and   sorted with key as lines index.

```<code>import os
import time
import pandas as pd
import numpy as nb
fr = open('d:\\srcfile1')
lines = fr.readlines()
lines = [line.strip() for line in lines if line.islower() ]
output = sorted(set(lines) - set(fruit).intersection(set(lines)), key=lines.index)
fw = open('destfile1.txt', 'w')
for line in output:
    fw.write(line+'\n')
fw.close()
</code>```

Output:

```
paper
wood
plastic
fire
water
house
onion
ginger
mints
watermelon
pepper
```

Title: extract data from csv file based on two lists with priority for items in the first list

Body:
I have csv files and I want to extract part of data form each one into another file based on keywords from two different lists. That is, the the program should match every line in the original file with the keywords in the first list and write those lines until a match is found. once match is found, it should break the execution. In case the program reached the last line in the csv file without finding any match, then it should start matching with the second list and repeat the same.
I want to give the priority to the first list and if there is no match then start the process using the second list.

The first list fruit=['orange', 'apple', 'grape', 'banana','phone', 'TV', 'w']
The second list veg=['tomato','potato','onion']

following is a sample of the contents of one of the files called srcfile1

 paper
 wood
 plastic
 fire
 water
 house
 onion
 ginger
 mints
 banana
 TV
 watermelon
 phone
 pepper

I have written following python code:

import os
from tqdm import *
import time
import pandas as pd
import numpy as nb
line = fr.readline()
fr = open('d:\\srcfile1')
fw = open('destfile1', 'w')
found=False
while line:
      line = fr.readline()
      if any (item.lower() in line.lower() for item in fruit):
          found=True
          fw.close()
          break
      elif any (item.lower() in line.lower() for item in veg) and found==False:
            fw.close()
            break
      fw.writelines(line)

fr.close()
fw.close()

The desired outcome from the code should be:

 paper
 wood
 plastic
 fire
 water
 house
 onion
 ginger
 mints

But When I run this code, it just match any element from both lists and does not give the priority to fruit list. It just give the following output:

 paper
 wood
 plastic
 fire
 water
 house

I would be grateful if anybody could help me in this.

Body:
I think this is what you meant, to write lines which are not present infruits list and also lines which is not in uppercase letters and  to preserve the order you can use differnce of set intersetion and   sorted with key as lines index.

import os
import time
import pandas as pd
import numpy as nb
fr = open('d:\\srcfile1')
lines = fr.readlines()
lines = [line.strip() for line in lines if line.islower() ]
output = sorted(set(lines) - set(fruit).intersection(set(lines)), key=lines.index)
fw = open('destfile1.txt', 'w')
for line in output:
    fw.write(line+'\n')
fw.close()

Output:

paper
wood
plastic
fire
water
house
onion
ginger
mints
watermelon
pepper


来源: stackexchange

问:
how to open large .mat file that wasn't saved with -v7.3 flag?
I am trying to open a .mat file with one huge array in it.
When I use matfile function like below:

```<code>file=matfile('input_file');
</code>```

Following errors show up:

Warning: The file 'C:...\input_file.mat' was saved in a
  format that does not support partial loading. Temporarily loading variable 'var_name' into memory. To use partial loading
  efficiently, save MAT-files with the -v7.3 flag.

Error using my_function (line 11)
  Cannot read file C:...\input_file.mat.

How can I "resave" it properly? Or is there any other way to load data from the file?
Thank you

答:
To load a file, you can:

Double click on that file in the workspace directory.

Use the command:

load('file.mat');

To save a file after processing data, you can use:

```<code>save('filename.mat',nameobj,'-v7.3');
</code>```

or

```<code>save('filename.mat',nameobj);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to open a .mat file with one huge array in it.
When I use matfile function like below:

file=matfile('input_file');

Following errors show up:

Warning: The file 'C:...\input_file.mat' was saved in a
  format that does not support partial loading. Temporarily loading variable 'var_name' into memory. To use partial loading
  efficiently, save MAT-files with the -v7.3 flag.

Error using my_function (line 11)
  Cannot read file C:...\input_file.mat.

How can I "resave" it properly? Or is there any other way to load data from the file?
Thank you

Body:
To load a file, you can:

Double click on that file in the workspace directory.

Use the command:

load('file.mat');

To save a file after processing data, you can use:

save('filename.mat',nameobj,'-v7.3');

or

save('filename.mat',nameobj);


问:
Add cookie to response with OkHttp3 / Retrofit
I am trying to add a header to HTTP responses. This is my Interceptor which is not working:

```<code>builder.addInterceptor(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        Request addedTestRequest = request.newBuilder().addHeader("TEST", "test").build();

        Response response = chain.proceed(addedTestRequest);

        final Response addedTestResponse = response.newBuilder().addHeader("TEST", "test").build();

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

I can see the header TEST in outgoing traffic (requests) but not in incoming traffic (responses). Do you know what is the problem or is there another way to add headers to responses?

Note: I am using franmontiel/PersistentCookieJar with OkHttp3 / Retrofit, if that influences anything.

答:
You can simply add two interceptors into your OkHttp instance, which will do next operations:

scan cookies from the responses;

save found cookies into the prefs;

attach cookies from the prefs into the requests;

Of course, you can customize this logic according to your tasks.

```<code>public class AddCookiesInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        HashSet<String> preferences = (HashSet) Preferences.getDefaultPreferences().getStringSet(Preferences.PREF_COOKIES, new HashSet<>());
        for (String cookie : preferences) {
            builder.addHeader("Cookie", cookie);
        }

        return chain.proceed(builder.build());
    }
}
</code>```

```<code>public class ReceivedCookiesInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());

        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            HashSet<String> cookies = new HashSet<>();

            for (String header : originalResponse.headers("Set-Cookie")) {
              cookies.add(header);
            }

            Preferences.getDefaultPreferences().edit()
                    .putStringSet(Preferences.PREF_COOKIES, cookies)
                    .apply();
        }

        return originalResponse;
    }
}
</code>```

```<code> OkHttpClient okHttpClient = new OkHttpClient();
 okHttpClient.interceptors().add(new AddCookiesInterceptor());
 okHttpClient.interceptors().add(new ReceivedCookiesInterceptor());
</code>```

Body:
I am trying to add a header to HTTP responses. This is my Interceptor which is not working:

builder.addInterceptor(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        Request addedTestRequest = request.newBuilder().addHeader("TEST", "test").build();

        Response response = chain.proceed(addedTestRequest);

        final Response addedTestResponse = response.newBuilder().addHeader("TEST", "test").build();

        return addedTestResponse;
    }
});

I can see the header TEST in outgoing traffic (requests) but not in incoming traffic (responses). Do you know what is the problem or is there another way to add headers to responses?

Note: I am using franmontiel/PersistentCookieJar with OkHttp3 / Retrofit, if that influences anything.

Body:
You can simply add two interceptors into your OkHttp instance, which will do next operations:

scan cookies from the responses;

save found cookies into the prefs;

attach cookies from the prefs into the requests;

Of course, you can customize this logic according to your tasks.

public class AddCookiesInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        HashSet<String> preferences = (HashSet) Preferences.getDefaultPreferences().getStringSet(Preferences.PREF_COOKIES, new HashSet<>());
        for (String cookie : preferences) {
            builder.addHeader("Cookie", cookie);
        }

        return chain.proceed(builder.build());
    }
}

public class ReceivedCookiesInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());

        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            HashSet<String> cookies = new HashSet<>();

            for (String header : originalResponse.headers("Set-Cookie")) {
              cookies.add(header);
            }

            Preferences.getDefaultPreferences().edit()
                    .putStringSet(Preferences.PREF_COOKIES, cookies)
                    .apply();
        }

        return originalResponse;
    }
}

 OkHttpClient okHttpClient = new OkHttpClient();
 okHttpClient.interceptors().add(new AddCookiesInterceptor());
 okHttpClient.interceptors().add(new ReceivedCookiesInterceptor());


问:
Laravel with xampp
I need to understand this behavior.

I use xampp for web development. I start to apache server in the xampp gui and then I can start my projects in the browser via localhost...

Since yesterday I have added laravel to my mac book. My project is in the xampp htdocs folder and I want to use it witch xampp. But when the xampp apache server instance is running, nothing is happened to my laravel project until I run php artisan serve in the cmd.

How can I combine larael with xampp?
And what exactly does php artisan serve do? Start another apache server instance?

答:
Create virtual host and point it to laravel_directory/public/index.php and restart apache.

Creating apache virtual host:
http://laravel-recipes.com/recipes/25/creating-an-apache-virtualhost

If you don't want to do that load, localhost/lara_dir/public/index.php

index.php is where all the requests go through.

ContentLicense: CC BY-SA 4.0

Title: Laravel with xampp


问:
Capture between round brackets and square brackets
I have a text similar to this:

```<code>[text]
(more text)
(text...)
[text!]
(last text)
</code>```

I need to match the text between () and [].

The output should be something like this:

```<code>[
  "text",
  "more text",
  "text...",
  "text!",
  "last text"
]
</code>```

I already tried /[\[\(](.*?)[\]\)]/ but it didn't work in PHP.

Here is the code if you need it:

```<code> preg_match_all('/[\[\(](.*?)[\]\)]/', $text, $matches, PREG_SET_ORDER, 0);
 var_dump($matches);
</code>```

How do I achieve this using regex in PHP?

Thanks in advance,

Skayo

答:
Actually, that code works like a charm. You just need to add a line to filter out the matched sections:

```<code>$texts = array_column($matches, 1);
</code>```

See https://3v4l.org/uCHIB for a working example.

Body:
I have a text similar to this:

[text]
(more text)
(text...)
[text!]
(last text)

I need to match the text between () and [].

The output should be something like this:

[
  "text",
  "more text",
  "text...",
  "text!",
  "last text"
]

I already tried /[\[\(](.*?)[\]\)]/ but it didn't work in PHP.

Here is the code if you need it:

 preg_match_all('/[\[\(](.*?)[\]\)]/', $text, $matches, PREG_SET_ORDER, 0);
 var_dump($matches);

How do I achieve this using regex in PHP?

Thanks in advance,

Skayo

Body:
Actually, that code works like a charm. You just need to add a line to filter out the matched sections:

$texts = array_column($matches, 1);

See https://3v4l.org/uCHIB for a working example.


问:
Store Ascii Values
how to store Ascii character a to z in any one type of variable using strcpy?</p>

```<code>for(i=97;i<122;i++)
{
    for(j=97;j<122;j++)
    {
        printf("%c%c",i,j);
        int a = strcpy(i,j);
    }
}
</code>```

答:
Ηow to store Ascii character in any one type of variable using strcpy()?

You don't need it, since for a single character strcpy() is unnecessary.

Moreover, you try to handle an int with strcpy(), whereas this function handles char*.

What you could do is something like this:

```<code>char myarray[3] = {0};
for(i = 97; i < 122; i++)
{
    for(j = 97; j < 122; j++)
    {
        printf("%c%c\n", i, j);
        myarray[0] = i;
        myarray[1] = j;
        printf("%s\n", myarray);
    }
}
</code>```

where I used a char array, since if you store the ASCII character in an int you cannot expect it to print the same character, as it was stored in a char. Even if you try Convert char array to a int number in C, you will not be able to succeed in it.

Title: Store Ascii Values

Body:
how to store Ascii character a to z in any one type of variable using strcpy?

for(i=97;i<122;i++)
{
    for(j=97;j<122;j++)
    {
        printf("%c%c",i,j);
        int a = strcpy(i,j);
    }
}

Body:
Ηow to store Ascii character in any one type of variable using strcpy()?

You don't need it, since for a single character strcpy() is unnecessary.

Moreover, you try to handle an int with strcpy(), whereas this function handles char*.

What you could do is something like this:

char myarray[3] = {0};
for(i = 97; i < 122; i++)
{
    for(j = 97; j < 122; j++)
    {
        printf("%c%c\n", i, j);
        myarray[0] = i;
        myarray[1] = j;
        printf("%s\n", myarray);
    }
}

where I used a char array, since if you store the ASCII character in an int you cannot expect it to print the same character, as it was stored in a char. Even if you try Convert char array to a int number in C, you will not be able to succeed in it.


问:
C-CDA validation fails because of "Unknown type" in my server but not in standalone project
I was checking how to use the MDHT libraries to validate C-CDA documents, reviewing the current implementations, to create a validation web service for my project. I firstly made a Eclipse local Java Project, added the JARs to the classpath, and implement the code. The execution was successful. But when I copy the same code to my web project (made with Spring Boot) and send a request that executes such code, the program fails.

To explain better, I made the following minimal method:

```<code>public void executeMDHTCode(byte[] fileContents) {
    System.out.println(Arrays.toString(fileContents));
    ValidationResult result = new ValidationResult();
    ClinicalDocument doc = null;

    try {
        ConsolPackage.eINSTANCE.eClass();
        doc = CDAUtil.load(new ByteArrayInputStream(fileContents), result);
    } catch (ClassCastException|SAXParseException|Resource.IOWrappedException e) {
        doc = null;
    } catch (Exception e) {
        throw new RuntimeException("Unknown error: " + e.getMessage(), e);
    }
}
</code>```

Then I used it in the following main method in my test project

```<code>public static void main(String[] args) throws IOException {
    ByteArrayOutputStream outstr = new ByteArrayOutputStream();
    int b = -1;
    InputStream stream = AppTest.class.getResourceAsStream("xml_ccda_invalid.xml");
    while((b = stream.read()) != -1) {
        outstr.write(b);
    }

    executeMDHTCode(outstr.toByteArray());   // only added 'static'
}
</code>```

And then used the same code in my server project (encapsulating it in a ccdaService)

```<code>@RequestMapping(/*POST endpoint properties*/)
public ResponseEntity<Object> validateCCDAFile(@RequestBody MultipartFile file) throws IOException {
    ccdaService.executeMDHTCode(file.getBytes());
    return null;
}
</code>```

The document to be tested in both cases, xml_ccda_invalid.xml, contains the following:

```<code><?xml version="1.0" encoding="UTF-8"?>
<ClinicalDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:hl7-org:v3" xsi:schemaLocation="urn:hl7-org:v3 CDA.xsd">
  <realmCode code="US"/>
</ClinicalDocument>
</code>```

As I said, the test project version terminates correctly. But the server version throws the following exception:

```<code>java.lang.UnsupportedOperationException: Unknown type ([vocab, ActClinicalDocument, DOCCLIN])
    at org.eclipse.mdht.uml.cda.operations.ClinicalDocumentOperations.validateClassCode(ClinicalDocumentOperations.java:133) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.mdht.uml.cda.impl.ClinicalDocumentImpl.validateClassCode(ClinicalDocumentImpl.java:1659) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.mdht.uml.cda.util.CDAValidator.validateClinicalDocument_validateClassCode(CDAValidator.java:1769) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.mdht.uml.cda.util.CDAValidator.validateClinicalDocument(CDAValidator.java:1753) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.mdht.uml.cda.util.CDAValidator.validate(CDAValidator.java:1075) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.emf.ecore.util.EObjectValidator.validate(EObjectValidator.java:324) ~[org.eclipse.emf.ecore-2.12.0.v20160420-0247.jar:?]
    at org.eclipse.emf.ecore.util.Diagnostician.doValidate(Diagnostician.java:171) ~[org.eclipse.emf.ecore-2.12.0.v20160420-0247.jar:?]
    at org.eclipse.emf.ecore.util.Diagnostician.validate(Diagnostician.java:158) ~[org.eclipse.emf.ecore-2.12.0.v20160420-0247.jar:?]
    at org.eclipse.emf.ecore.util.Diagnostician.validate(Diagnostician.java:137) ~[org.eclipse.emf.ecore-2.12.0.v20160420-0247.jar:?]
    at org.eclipse.emf.ecore.util.Diagnostician.validate(Diagnostician.java:108) ~[org.eclipse.emf.ecore-2.12.0.v20160420-0247.jar:?]
    at org.eclipse.mdht.uml.cda.util.CDAUtil.validate(CDAUtil.java:707) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.mdht.uml.cda.util.CDAUtil.validate(CDAUtil.java:696) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.mdht.uml.cda.util.CDAUtil.performEMFValidation(CDAUtil.java:830) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.mdht.uml.cda.util.CDAUtil.load(CDAUtil.java:277) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.mdht.uml.cda.util.CDAUtil.load(CDAUtil.java:252) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at companypackage.service.impl.CCDAServiceImpl.executeMDHTCode(CCDAServiceImpl.java:109) ~[bin/:?]
    at companypackage.controller.CCDAController.validateCCDAFile(CCDAController.java:32) ~[bin/:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_102]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_102]
    at (other spring and apache calls...)
</code>```

I used the println statement to check the contents of the input array, and they are in both cases identical, so it's not a matter of server processing of the file.

I have not idea why this happens. I put all the jars of the server project into the test project's classpath and it still worked, so it's not a class name clash. It seems to be only interfere when actually used.

What could I be missing?

答:
The looks to be an issue with the war file deployment - the ActClinicalDocument is defined in the org.eclipse.mdht.uml.hl7.vocab jar;  if you are using maven for the build you can look at the following maven example https://github.com/mdht/mdht-models/tree/develop/examples/org.openhealthtools.mdht.cda.maven.example

if not make sure in your eclipse project that the jars etc are included in the binary build

Body:
I was checking how to use the MDHT libraries to validate C-CDA documents, reviewing the current implementations, to create a validation web service for my project. I firstly made a Eclipse local Java Project, added the JARs to the classpath, and implement the code. The execution was successful. But when I copy the same code to my web project (made with Spring Boot) and send a request that executes such code, the program fails.

To explain better, I made the following minimal method:

public void executeMDHTCode(byte[] fileContents) {
    System.out.println(Arrays.toString(fileContents));
    ValidationResult result = new ValidationResult();
    ClinicalDocument doc = null;

    try {
        ConsolPackage.eINSTANCE.eClass();
        doc = CDAUtil.load(new ByteArrayInputStream(fileContents), result);
    } catch (ClassCastException|SAXParseException|Resource.IOWrappedException e) {
        doc = null;
    } catch (Exception e) {
        throw new RuntimeException("Unknown error: " + e.getMessage(), e);
    }
}

Then I used it in the following main method in my test project

public static void main(String[] args) throws IOException {
    ByteArrayOutputStream outstr = new ByteArrayOutputStream();
    int b = -1;
    InputStream stream = AppTest.class.getResourceAsStream("xml_ccda_invalid.xml");
    while((b = stream.read()) != -1) {
        outstr.write(b);
    }

    executeMDHTCode(outstr.toByteArray());   // only added 'static'
}

And then used the same code in my server project (encapsulating it in a ccdaService)

@RequestMapping(/*POST endpoint properties*/)
public ResponseEntity<Object> validateCCDAFile(@RequestBody MultipartFile file) throws IOException {
    ccdaService.executeMDHTCode(file.getBytes());
    return null;
}

The document to be tested in both cases, xml_ccda_invalid.xml, contains the following:

<?xml version="1.0" encoding="UTF-8"?>
<ClinicalDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:hl7-org:v3" xsi:schemaLocation="urn:hl7-org:v3 CDA.xsd">
  <realmCode code="US"/>
</ClinicalDocument>

As I said, the test project version terminates correctly. But the server version throws the following exception:

java.lang.UnsupportedOperationException: Unknown type ([vocab, ActClinicalDocument, DOCCLIN])
    at org.eclipse.mdht.uml.cda.operations.ClinicalDocumentOperations.validateClassCode(ClinicalDocumentOperations.java:133) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.mdht.uml.cda.impl.ClinicalDocumentImpl.validateClassCode(ClinicalDocumentImpl.java:1659) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.mdht.uml.cda.util.CDAValidator.validateClinicalDocument_validateClassCode(CDAValidator.java:1769) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.mdht.uml.cda.util.CDAValidator.validateClinicalDocument(CDAValidator.java:1753) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.mdht.uml.cda.util.CDAValidator.validate(CDAValidator.java:1075) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.emf.ecore.util.EObjectValidator.validate(EObjectValidator.java:324) ~[org.eclipse.emf.ecore-2.12.0.v20160420-0247.jar:?]
    at org.eclipse.emf.ecore.util.Diagnostician.doValidate(Diagnostician.java:171) ~[org.eclipse.emf.ecore-2.12.0.v20160420-0247.jar:?]
    at org.eclipse.emf.ecore.util.Diagnostician.validate(Diagnostician.java:158) ~[org.eclipse.emf.ecore-2.12.0.v20160420-0247.jar:?]
    at org.eclipse.emf.ecore.util.Diagnostician.validate(Diagnostician.java:137) ~[org.eclipse.emf.ecore-2.12.0.v20160420-0247.jar:?]
    at org.eclipse.emf.ecore.util.Diagnostician.validate(Diagnostician.java:108) ~[org.eclipse.emf.ecore-2.12.0.v20160420-0247.jar:?]
    at org.eclipse.mdht.uml.cda.util.CDAUtil.validate(CDAUtil.java:707) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.mdht.uml.cda.util.CDAUtil.validate(CDAUtil.java:696) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.mdht.uml.cda.util.CDAUtil.performEMFValidation(CDAUtil.java:830) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.mdht.uml.cda.util.CDAUtil.load(CDAUtil.java:277) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at org.eclipse.mdht.uml.cda.util.CDAUtil.load(CDAUtil.java:252) ~[org.eclipse.mdht.uml.cda-3.0.0.201706220503.jar:?]
    at companypackage.service.impl.CCDAServiceImpl.executeMDHTCode(CCDAServiceImpl.java:109) ~[bin/:?]
    at companypackage.controller.CCDAController.validateCCDAFile(CCDAController.java:32) ~[bin/:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_102]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_102]
    at (other spring and apache calls...)

I used the println statement to check the contents of the input array, and they are in both cases identical, so it's not a matter of server processing of the file.

I have not idea why this happens. I put all the jars of the server project into the test project's classpath and it still worked, so it's not a class name clash. It seems to be only interfere when actually used.

What could I be missing?


问:
Wordpress Shortcode to get Youtube Channel Views via YouTube API
I am Wordpress User and not the Programmer.
I want to create a shortcode in the functions.php to get the total views of any youtube channel.

I use the shortcode and give the channel ID Value. After the shortcode function gives back via YouTube API the current Channel Views of the given Channel ID.

In the YouTube Documentation, I found the following Code:

```<code>function channelsListById($service, $part, $params) {
    $params = array_filter($params);
    $response = $service->channels->listChannels(
        $part,
        $params
    );

    print_r($response);
}

channelsListById($service,
    'statistics',
    array('id' => 'UC_x5XG1OV2P6uZZ5FSM9Ttw'));
}
</code>```

The Response looks like that:

```<code>/**
 * API response
 */
{
  "kind": "youtube#channelListResponse",
  "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/d9WwK8U1FuV6c-shZpzmnYUgGvQ\"",
  "pageInfo": {
    "totalResults": 1,
    "resultsPerPage": 1
  },
  "items": [
    {
      "kind": "youtube#channel",
      "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/Psv3E9LCdk66gkF4HSIYK44crMI\"",
      "id": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
      "statistics": {
        "viewCount": "118283693",
        "commentCount": "393",
        "subscriberCount": "1165598",
        "hiddenSubscriberCount": false,
        "videoCount": "4435"
      }
    }
  ]
}
</code>```

I think, I need to add some code to get the item field "viewCount" Value.

I don´t know if it is possible to do that, but I hope some of you Pros know the solution.

At the End of the Code, I just have to add:

```<code>add_shortcode( 'channel_views', 'shortcode_title' );
</code>```

Would be amazing, if you could respond with the code I have to invert to the functions.php ;)

If you need more information to be able to respond, just ask me.

答:
Use this plugin.

https://wordpress.org/plugins/youmax-channel-embeds-for-youtube-businesses/

This plugin simply gets all the videos from youtube channel in the grid format.

Body:
I am Wordpress User and not the Programmer.
I want to create a shortcode in the functions.php to get the total views of any youtube channel.

I use the shortcode and give the channel ID Value. After the shortcode function gives back via YouTube API the current Channel Views of the given Channel ID.

In the YouTube Documentation, I found the following Code:

function channelsListById($service, $part, $params) {
    $params = array_filter($params);
    $response = $service->channels->listChannels(
        $part,
        $params
    );

    print_r($response);
}

channelsListById($service,
    'statistics',
    array('id' => 'UC_x5XG1OV2P6uZZ5FSM9Ttw'));
}

The Response looks like that:

/**
 * API response
 */
{
  "kind": "youtube#channelListResponse",
  "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/d9WwK8U1FuV6c-shZpzmnYUgGvQ\"",
  "pageInfo": {
    "totalResults": 1,
    "resultsPerPage": 1
  },
  "items": [
    {
      "kind": "youtube#channel",
      "etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/Psv3E9LCdk66gkF4HSIYK44crMI\"",
      "id": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
      "statistics": {
        "viewCount": "118283693",
        "commentCount": "393",
        "subscriberCount": "1165598",
        "hiddenSubscriberCount": false,
        "videoCount": "4435"
      }
    }
  ]
}

I think, I need to add some code to get the item field "viewCount" Value.

I don´t know if it is possible to do that, but I hope some of you Pros know the solution.

At the End of the Code, I just have to add:

add_shortcode( 'channel_views', 'shortcode_title' );

Would be amazing, if you could respond with the code I have to invert to the functions.php ;)

If you need more information to be able to respond, just ask me.


问:
change the image doesnt work
here is my javasript:

```<code>$(function() {
    $(".image2").click(function() {
        var image = $(this).attr("rel");
        $('#random_img').hide();
        $('#random_img').fadeIn('slow');
        $('#random_img').attr('src') == image;
        var image2 = $('#random_img').attr('src');
        $("#thumb2 a img").removeClass("open");
        $("#thumb2 a[rel='" + image2 + "'] img").addClass("open");
        return false;
    });
});
</code>```

here is my html:

```<code><div id="image2">
    <img id="random_img" src="/documents/templates/projedepo/banner/indigovision.jpg" height="420" width="964" />
</div>
<div id="thumb2">
    <a href="#" rel="/documents/templates/projedepo/banner/canon.jpg" class="image2">
        <img title="Canon" class="slider_thumb" src="/documents/templates/bilgiteknolojileri/images/t_flash/t1.png" border="0"/></a>
    <a href="#" rel="/documents/templates/projedepo/banner/indigovision.jpg" class="image2">
        <img title="IndigoVision" class="slider_thumb" src="/documents/templates/bilgiteknolojileri/images/t_flash/t2.png" border="0"/>
    </a>
</div>
</code>```

when i click on a thumbnail, the animation fadeIn and hide works, but the image is not changed...why?

答:
To change the image, specify second argument to attr:

```<code>$('#random_img').attr('src', image);
</code>```

Instead of this which won't work:

```<code>$('#random_img').attr('src') = image;
</code>```

Check out the second version of attr here for more info.

You are also not storing src in your image variable but its rel attribute here:

```<code>var image = $(this).attr("rel");
</code>```

Which should be:

```<code>var image = $(this).attr("src");
</code>```

ContentLicense: CC BY-SA 2.5

Title: change the image doesnt work

Body:
here is my javasript:

$(function() {
    $(".image2").click(function() {
        var image = $(this).attr("rel");
        $('#random_img').hide();
        $('#random_img').fadeIn('slow');
        $('#random_img').attr('src') == image;
        var image2 = $('#random_img').attr('src');
        $("#thumb2 a img").removeClass("open");
        $("#thumb2 a[rel='" + image2 + "'] img").addClass("open");
        return false;
    });
});

here is my html:

when i click on a thumbnail, the animation fadeIn and hide works, but the image is not changed...why?

Body:
To change the image, specify second argument to attr:

$('#random_img').attr('src', image);

Instead of this which won't work:

$('#random_img').attr('src') = image;

Check out the second version of attr here for more info.

You are also not storing src in your image variable but its rel attribute here:

var image = $(this).attr("rel");

Which should be:

var image = $(this).attr("src");


问:
what's wrong with my tensorflow code
I just begin to study tensorflow and I want to create a DNN for MNIST. In the tutorial, there is a very simple neural network with 784 input nodes, 10 output nodes and no hidden nodes. I try to modify these codes to create a DNN network. Here is my code. I think I just add a hidden layer with 500 nodes between input and output layers, but the test accuracy is just 10%, which means it is not trained. Do you know what's wrong with my codes?

```<code>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

import os
os.chdir('../')

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

x=tf.placeholder(tf.float32,[None,784])
W_h1=tf.Variable(tf.zeros([784,500]))
B_h1=tf.Variable(tf.zeros([500]))
h1=tf.nn.relu(tf.matmul(x,W_h1)+B_h1)
'''
W_h2=tf.Variable(tf.zeros([5,5]))
B_h2=tf.Variable(tf.zeros([5]))
h2=tf.nn.relu(tf.matmul(h1,W_h2)+B_h2)
'''
B_o=tf.Variable(tf.zeros([10]))
W_o=tf.Variable(tf.zeros([500,10]))
y=tf.nn.relu(tf.matmul(h1,W_o)+B_o)

y_=tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

train_step = tf.train.GradientDescentOptimizer(0.05).minimize(cross_entropy)
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

number_steps = 10000
batch_size = 100
for _ in range(number_steps):
  batch_xs, batch_ys = mnist.train.next_batch(batch_size)
  train=sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

  # Print classifier's accuracy
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
</code>```

OK, according to @lejlot's suggestion, I change my code as following.

```<code>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

import os
os.chdir('../')

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

x=tf.placeholder(tf.float32,[None,784])
W_h1=tf.Variable(tf.random_normal([784,500]))
B_h1=tf.Variable(tf.random_normal([500]))
h1=tf.nn.relu(tf.matmul(x,W_h1)+B_h1)
'''
W_h2=tf.Variable(tf.random_normal([500,500]))
B_h2=tf.Variable(tf.random_normal([500]))
h2=tf.nn.relu(tf.matmul(h1,W_h2)+B_h2)
'''
B_o=tf.Variable(tf.random_normal([10]))
W_o=tf.Variable(tf.random_normal([500,10]))
y= tf.matmul(h1,W_o)+B_o # notice no activation

y_=tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.nn.log_softmax(y), # notice log_softmax
                  reduction_indices=[1]))

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

number_steps = 10000
batch_size = 100
for i in range(number_steps):
  batch_xs, batch_ys = mnist.train.next_batch(batch_size)
  train=sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
  if i % 1000==0:
    acc=sess.run(accuracy,feed_dict={x: mnist.test.images, y_: mnist.test.labels})
    print('Current loop %d, Accuracy: %g'%(i,acc))

  # Print classifier's accuracy
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
</code>```

There are two modification:

change the initial value of W_h1 and B_h1 with tf.random_normal

change the define of y and cross_entropy

The modification dose work. But I still don't know what's wrong with my original code. I call the tf.global_variables_initializer().run(), and I think this function will random the value of W_h1 and B_h1. Besides, if I define y and cross_entropy as following, it doesn't work.

```<code>y= tf.nn.softmax(tf.matmul(h1,W_o)+B_o)
y_=tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1]))
</code>```

答:
First of all this is not valid classifier model.

```<code>y=tf.nn.relu(tf.matmul(h1,W_o)+B_o)

y_=tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
</code>```

You are using explicit equation for cross entropy which requires y to be a (row-wise) probability distribution, yet you produce y by applying relu, meaning that you are simply outputing some non-negative numbers. In fact, if you ever output zeros, your code will produce NaNs and fail (as log of 0 is minus infinity).

You should use

```<code>y = tf.nn.softmax(tf.matmul(h1,W_o)+B_o)
</code>```

instead. Or even better (for better numerical stability):

```<code>y= tf.matmul(h1,W_o)+B_o # notice no activation

y_=tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(
                  -tf.reduce_sum(y_ * tf.nn.log_softmax(y), # notice log_softmax
                  reduction_indices=[1]))
</code>```

update

Second issue is initialisation - you cannot initialise neural network weights to zeros, they have to be random numbers, typically sampled from low-variance zero-mean Gaussians. Global initialiser does not randomise weights, it simply runs all the initialisation ops - if the initialisation ops are constant ones (like zeros), it simply makes sure these zeros are assigned to variables, nothing else (thus it can be used to reset the network etc.). Zero initialisation works only for convex problems, such as logistic regression, but cannot work for complex model like neural network.

Title: what's wrong with my tensorflow code

Body:
I just begin to study tensorflow and I want to create a DNN for MNIST. In the tutorial, there is a very simple neural network with 784 input nodes, 10 output nodes and no hidden nodes. I try to modify these codes to create a DNN network. Here is my code. I think I just add a hidden layer with 500 nodes between input and output layers, but the test accuracy is just 10%, which means it is not trained. Do you know what's wrong with my codes?

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

import os
os.chdir('../')

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

x=tf.placeholder(tf.float32,[None,784])
W_h1=tf.Variable(tf.zeros([784,500]))
B_h1=tf.Variable(tf.zeros([500]))
h1=tf.nn.relu(tf.matmul(x,W_h1)+B_h1)
'''
W_h2=tf.Variable(tf.zeros([5,5]))
B_h2=tf.Variable(tf.zeros([5]))
h2=tf.nn.relu(tf.matmul(h1,W_h2)+B_h2)
'''
B_o=tf.Variable(tf.zeros([10]))
W_o=tf.Variable(tf.zeros([500,10]))
y=tf.nn.relu(tf.matmul(h1,W_o)+B_o)

y_=tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

train_step = tf.train.GradientDescentOptimizer(0.05).minimize(cross_entropy)
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

number_steps = 10000
batch_size = 100
for _ in range(number_steps):
  batch_xs, batch_ys = mnist.train.next_batch(batch_size)
  train=sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

  # Print classifier's accuracy
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

OK, according to @lejlot's suggestion, I change my code as following.

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

import os
os.chdir('../')

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

x=tf.placeholder(tf.float32,[None,784])
W_h1=tf.Variable(tf.random_normal([784,500]))
B_h1=tf.Variable(tf.random_normal([500]))
h1=tf.nn.relu(tf.matmul(x,W_h1)+B_h1)
'''
W_h2=tf.Variable(tf.random_normal([500,500]))
B_h2=tf.Variable(tf.random_normal([500]))
h2=tf.nn.relu(tf.matmul(h1,W_h2)+B_h2)
'''
B_o=tf.Variable(tf.random_normal([10]))
W_o=tf.Variable(tf.random_normal([500,10]))
y= tf.matmul(h1,W_o)+B_o # notice no activation

y_=tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.nn.log_softmax(y), # notice log_softmax
                  reduction_indices=[1]))

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

number_steps = 10000
batch_size = 100
for i in range(number_steps):
  batch_xs, batch_ys = mnist.train.next_batch(batch_size)
  train=sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
  if i % 1000==0:
    acc=sess.run(accuracy,feed_dict={x: mnist.test.images, y_: mnist.test.labels})
    print('Current loop %d, Accuracy: %g'%(i,acc))

  # Print classifier's accuracy
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

There are two modification:

change the initial value of W_h1 and B_h1 with tf.random_normal

change the define of y and cross_entropy

The modification dose work. But I still don't know what's wrong with my original code. I call the tf.global_variables_initializer().run(), and I think this function will random the value of W_h1 and B_h1. Besides, if I define y and cross_entropy as following, it doesn't work.

y= tf.nn.softmax(tf.matmul(h1,W_o)+B_o)
y_=tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1]))

Body:
First of all this is not valid classifier model.

y=tf.nn.relu(tf.matmul(h1,W_o)+B_o)

y_=tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))

You are using explicit equation for cross entropy which requires y to be a (row-wise) probability distribution, yet you produce y by applying relu, meaning that you are simply outputing some non-negative numbers. In fact, if you ever output zeros, your code will produce NaNs and fail (as log of 0 is minus infinity).

You should use

y = tf.nn.softmax(tf.matmul(h1,W_o)+B_o)

instead. Or even better (for better numerical stability):

y= tf.matmul(h1,W_o)+B_o # notice no activation

y_=tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(
                  -tf.reduce_sum(y_ * tf.nn.log_softmax(y), # notice log_softmax
                  reduction_indices=[1]))

update

Second issue is initialisation - you cannot initialise neural network weights to zeros, they have to be random numbers, typically sampled from low-variance zero-mean Gaussians. Global initialiser does not randomise weights, it simply runs all the initialisation ops - if the initialisation ops are constant ones (like zeros), it simply makes sure these zeros are assigned to variables, nothing else (thus it can be used to reset the network etc.). Zero initialisation works only for convex problems, such as logistic regression, but cannot work for complex model like neural network.


问:
Update data frame values as per multiple where condition using numpy
I want to change DateWork['Variable'] values as per multiple where conditions and update in  DateWork['Date']

If Frequency=3 and len(Variable)=6 then replace M with "-0" and update in DateWork['Date']
If Frequency=3 and len(Variable)=7 then replace M with "-" and update in DateWork['Date']

DataFrame: DateWork

```<code>Frequency Variable      Date
3         1950M2        1950-02-01
3         1950M3        1950-03-01
2         1950-07-01    1950-07-01
3         1950M9        1950-09-01
2         1950-10-01    1950-10-01
3         1950M10       1950-10-01
</code>```

My code:

```<code>DateWork.loc[DateWork['Date']] = np.where(((DateWork['Frequency'] == 3) & (DateWork['variable'].str.len() == 6)), 'M', '-0',  DateWork['Date'])
DateWork.loc[DateWork['Date']] = np.where(((DateWork['Frequency'] == 3) & (DateWork['variable'].str.len() == 7)), 'M', '-',  DateWork['Date'])
DateWork.loc[DateWork['Frequency'] == 3, 'Date'] = DateWork.loc[DateWork['Frequency'] == 3, 'variable'] + '-01'
</code>```

This gives error:

TypeError: where() takes at most 3 arguments (4 given)

Body:
I want to change DateWork['Variable'] values as per multiple where conditions and update in  DateWork['Date']

If Frequency=3 and len(Variable)=6 then replace M with "-0" and update in DateWork['Date']
If Frequency=3 and len(Variable)=7 then replace M with "-" and update in DateWork['Date']

DataFrame: DateWork

Frequency Variable      Date
3         1950M2        1950-02-01
3         1950M3        1950-03-01
2         1950-07-01    1950-07-01
3         1950M9        1950-09-01
2         1950-10-01    1950-10-01
3         1950M10       1950-10-01

My code:

DateWork.loc[DateWork['Date']] = np.where(((DateWork['Frequency'] == 3) & (DateWork['variable'].str.len() == 6)), 'M', '-0',  DateWork['Date'])
DateWork.loc[DateWork['Date']] = np.where(((DateWork['Frequency'] == 3) & (DateWork['variable'].str.len() == 7)), 'M', '-',  DateWork['Date'])
DateWork.loc[DateWork['Frequency'] == 3, 'Date'] = DateWork.loc[DateWork['Frequency'] == 3, 'variable'] + '-01'

This gives error:

TypeError: where() takes at most 3 arguments (4 given)

Body:
If nesting np.where is hard to read,

DateWork
Out[32]:
   Frequency    Variable        Date
0          3      1950M2  1950-02-01
1          3      1950M3  1950-03-01
2          2  1950-07-01  1950-07-01
3          3      1950M9  1950-09-01
4          2  1950-10-01  1950-10-01
5          3     1950M10  1950-10-01

First if:

The else condition is the original Date column itself

DateWork['Date'] = np.where((DateWork['Frequency'] == 3) & (DateWork['Variable'].str.len() == 6), DateWork['Variable'].str.replace('M','-0'), DateWork['Date'])

DateWork
Out[34]:
   Frequency    Variable        Date
0          3      1950M2     1950-02
1          3      1950M3     1950-03
2          2  1950-07-01  1950-07-01
3          3      1950M9     1950-09
4          2  1950-10-01  1950-10-01
5          3     1950M10  1950-10-01

Second If:

Here, the else condition is the output date column of the above step

DateWork['Date'] = np.where((DateWork['Frequency'] == 3) & (DateWork['Variable'].str.len() == 7), DateWork['Variable'].str.replace('M','-'), DateWork['Date'])

DateWork
Out[36]:
   Frequency    Variable        Date
0          3      1950M2     1950-02
1          3      1950M3     1950-03
2          2  1950-07-01  1950-07-01
3          3      1950M9     1950-09
4          2  1950-10-01  1950-10-01
5          3     1950M10     1950-10


问:
How to check if a string contains an element from an array in Perl
I want to check if string $name ends with any of the elements from $end array_ref</p>

```<code>my $end=['.a[bc', '.de[f', '.xy]z'];
my $name="test.a[bc";

# But this is not working:
if(grep{$name=~m/\Q.+$_$/} @{$end}) { print "Yes\n"; } else {print "No\n"; } # prints "No"
</code>```

答:
The problem is that \Q escapes (and thus matches literally) .+ and $ (in addition to the contents of $_).

Fix:

```<code>grep { $name =~ /\Q$_\E\z/ } @{$end}
</code>```

You don't need the .+ part at all.

\E limits the escaping to just $_.

\z anchors the match to the end of the string ($ would also allow a \n before the end of the string).

Body:
I want to check if string $name ends with any of the elements from $end array_ref

my $end=['.a[bc', '.de[f', '.xy]z'];
my $name="test.a[bc";

# But this is not working:
if(grep{$name=~m/\Q.+$_$/} @{$end}) { print "Yes\n"; } else {print "No\n"; } # prints "No"

Body:
The problem is that \Q escapes (and thus matches literally) .+ and $ (in addition to the contents of $_).

Fix:

grep { $name =~ /\Q$_\E\z/ } @{$end}

You don't need the .+ part at all.

\E limits the escaping to just $_.

\z anchors the match to the end of the string ($ would also allow a \n before the end of the string).


问:
Jupyter pyspark : no module named pyspark
Google is literally littered with solutions to this problem, but unfortunately even after trying out all the possibilities, am unable to get it working, so please bear with me and see if something strikes you.

OS: MAC

Spark : 1.6.3 (2.10)

Jupyter Notebook : 4.4.0

Python : 2.7

Scala : 2.12.1

I was able to successfully install and run Jupyter notebook. Next, i tried configuring it to work with Spark, for which i installed spark interpreter using Apache Toree. Now when i try running any RDD operation in notebook, following error is thrown

```<code>Error from python worker:
  /usr/bin/python: No module named pyspark
PYTHONPATH was:
  /private/tmp/hadoop-xxxx/nm-local-dir/usercache/xxxx/filecache/33/spark-assembly-1.6.3-hadoop2.2.0.jar
</code>```

Things already tried:
1. Set PYTHONPATH in .bash_profile
2. Am able to import 'pyspark' in python-cli on local
3. Have tried updating interpreter kernel.json to following

```<code>{
  "language": "python",
  "display_name": "Apache Toree - PySpark",
  "env": {
    "__TOREE_SPARK_OPTS__": "",
    "SPARK_HOME": "/Users/xxxx/Desktop/utils/spark",
    "__TOREE_OPTS__": "",
    "DEFAULT_INTERPRETER": "PySpark",
    "PYTHONPATH": "/Users/xxxx/Desktop/utils/spark/python:/Users/xxxx/Desktop/utils/spark/python/lib/py4j-0.9-src.zip:/Users/xxxx/Desktop/utils/spark/python/lib/pyspark.zip:/Users/xxxx/Desktop/utils/spark/bin",
  "PYSPARK_SUBMIT_ARGS": "--master local --conf spark.serializer=org.apache.spark.serializer.KryoSerializer",
    "PYTHON_EXEC": "python"
  },
  "argv": [
    "/usr/local/share/jupyter/kernels/apache_toree_pyspark/bin/run.sh",
    "--profile",
    "{connection_file}"
  ]
}
</code>```

Have even updated interpreter run.sh to explicitly load py4j-0.9-src.zip and pyspark.zip files. When the opening the PySpark notebook, and creating of SparkContext, I can see the spark-assembly, py4j and pyspark packages being uploaded from local, but still when an action is invoked, somehow pyspark is not found.

答:
I tried the following command in Windows  to link pyspark on jupyter.

On *nix, use export instead of set

Type below code in CMD/Command Prompt

```<code>set PYSPARK_DRIVER_PYTHON=ipython
set PYSPARK_DRIVER_PYTHON_OPTS=notebook
pyspark
</code>```

Body:
Google is literally littered with solutions to this problem, but unfortunately even after trying out all the possibilities, am unable to get it working, so please bear with me and see if something strikes you.

OS: MAC

Spark : 1.6.3 (2.10)

Jupyter Notebook : 4.4.0

Python : 2.7

Scala : 2.12.1

I was able to successfully install and run Jupyter notebook. Next, i tried configuring it to work with Spark, for which i installed spark interpreter using Apache Toree. Now when i try running any RDD operation in notebook, following error is thrown

Error from python worker:
  /usr/bin/python: No module named pyspark
PYTHONPATH was:
  /private/tmp/hadoop-xxxx/nm-local-dir/usercache/xxxx/filecache/33/spark-assembly-1.6.3-hadoop2.2.0.jar

Things already tried:
1. Set PYTHONPATH in .bash_profile
2. Am able to import 'pyspark' in python-cli on local
3. Have tried updating interpreter kernel.json to following

{
  "language": "python",
  "display_name": "Apache Toree - PySpark",
  "env": {
    "__TOREE_SPARK_OPTS__": "",
    "SPARK_HOME": "/Users/xxxx/Desktop/utils/spark",
    "__TOREE_OPTS__": "",
    "DEFAULT_INTERPRETER": "PySpark",
    "PYTHONPATH": "/Users/xxxx/Desktop/utils/spark/python:/Users/xxxx/Desktop/utils/spark/python/lib/py4j-0.9-src.zip:/Users/xxxx/Desktop/utils/spark/python/lib/pyspark.zip:/Users/xxxx/Desktop/utils/spark/bin",
  "PYSPARK_SUBMIT_ARGS": "--master local --conf spark.serializer=org.apache.spark.serializer.KryoSerializer",
    "PYTHON_EXEC": "python"
  },
  "argv": [
    "/usr/local/share/jupyter/kernels/apache_toree_pyspark/bin/run.sh",
    "--profile",
    "{connection_file}"
  ]
}

Have even updated interpreter run.sh to explicitly load py4j-0.9-src.zip and pyspark.zip files. When the opening the PySpark notebook, and creating of SparkContext, I can see the spark-assembly, py4j and pyspark packages being uploaded from local, but still when an action is invoked, somehow pyspark is not found.

Body:
I tried the following command in Windows  to link pyspark on jupyter.

On *nix, use export instead of set

Type below code in CMD/Command Prompt

set PYSPARK_DRIVER_PYTHON=ipython
set PYSPARK_DRIVER_PYTHON_OPTS=notebook
pyspark


问:
Uncaught ReferenceError: sample is not defined
Please JS and inspect experts help me solve this out,

I see this error when I create any page that has google maps with my WordPress theme I see it on inspect element right now.

```<code> Uncaught ReferenceError: compileposh is not defined
  at crossBrowserFixes (publicjava.js:9471)
  at HTMLDocument.<anonymous> (publicjava.js:9532)
  at i (jquery.js:2)
  at Object.fireWith [as resolveWith] (jquery.js:2)
  at Function.ready (jquery.js:2)
  at HTMLDocument.K (jquery.js:2)
</code>```

What do all the above mean? I have a compileposh reference but why it's not defined ?

the error lines codes added at below:

```<code> 9470   //remove ajaxy from single posts when using Disqus
 9471   if(compileposh.disqusComments == 'true')
 $(
     '#post-zone article a,
     .blog_next_prev_buttons a,
     #portfolio-nav #prev-link a,
     #portfolio-nav #next-link a,
     .portfolio-items
     .col
     .work-item
     .work-info a'
 ).addClass('no-ajaxy');
</code>```

this code located at publicjava.js file located on themefile/js/publicjava.js and called from functions.php also I have a map.js file but the map section I used is a plugin - and I have original theme options that I declared on public java but with all tryings the same error coming to inspect element.

also, there are some more error lines: publicjava.js 9532

```<code> 9532    crossBrowserFixes();
</code>```

and jquery.js that not included with my theme : jquery.js: 2

and this at bottom :

```<code>chrome-extension://foobgjfmnkeainefnnoeghobcdcidhme/javascripts/content_script.js:1 Uncaught SyntaxError: Illegal return statement
</code>```

答:
Search For:

wp_localize_script

in your WordPress theme files. May be in functions.php or search for the whole project.

you can also search for compilelove. and change it to compileposh.

Body:
Please JS and inspect experts help me solve this out,

I see this error when I create any page that has google maps with my WordPress theme I see it on inspect element right now.

 Uncaught ReferenceError: compileposh is not defined
  at crossBrowserFixes (publicjava.js:9471)
  at HTMLDocument.<anonymous> (publicjava.js:9532)
  at i (jquery.js:2)
  at Object.fireWith [as resolveWith] (jquery.js:2)
  at Function.ready (jquery.js:2)
  at HTMLDocument.K (jquery.js:2)

What do all the above mean? I have a compileposh reference but why it's not defined ?

the error lines codes added at below:

 9470   //remove ajaxy from single posts when using Disqus
 9471   if(compileposh.disqusComments == 'true')
 $(
     '#post-zone article a,
     .blog_next_prev_buttons a,
     #portfolio-nav #prev-link a,
     #portfolio-nav #next-link a,
     .portfolio-items
     .col
     .work-item
     .work-info a'
 ).addClass('no-ajaxy');

this code located at publicjava.js file located on themefile/js/publicjava.js and called from functions.php also I have a map.js file but the map section I used is a plugin - and I have original theme options that I declared on public java but with all tryings the same error coming to inspect element.

also, there are some more error lines: publicjava.js 9532

 9532    crossBrowserFixes();

and jquery.js that not included with my theme : jquery.js: 2

and this at bottom :

chrome-extension://foobgjfmnkeainefnnoeghobcdcidhme/javascripts/content_script.js:1 Uncaught SyntaxError: Illegal return statement


问:
Android Wallpaper App - Resizing Images for scrollable background
I have a wallpaper app, which sets a selected image as background for the phone's menu. It is scrollable (by default), but the problem is that the background is just a cutout of the original image. Here is my code to set the image as background:

```<code>private Bitmap image = [...];

[...]

private void setBackgroundImage(){
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
        wallpaperManager.setBitmap(pic);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

My question now is: How can I determine the right size for the image, so that every phone has the entire picture as it's background picture and not just a cutout?

答:
my java file: like this

```<code>public class MainActivity extends AppCompatActivity {

    Button button;
    ImageView imageView;
    WallpaperManager wallpaperManager ;
    Bitmap bitmap1, bitmap2 ;
    DisplayMetrics displayMetrics ;
    int width, height;
    BitmapDrawable bitmapDrawable ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button)findViewById(R.id.button);

        imageView = (ImageView)findViewById(R.id.imageView);

        wallpaperManager  = WallpaperManager.getInstance(getApplicationContext());

        bitmapDrawable = (BitmapDrawable) imageView.getDrawable();

        bitmap1 = bitmapDrawable.getBitmap();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                GetScreenWidthHeight();

                SetBitmapSize();

                wallpaperManager = WallpaperManager.getInstance(MainActivity.this);

                try {

                    wallpaperManager.setBitmap(bitmap2);

                    wallpaperManager.suggestDesiredDimensions(width, height);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void GetScreenWidthHeight(){

        displayMetrics = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        width = displayMetrics.widthPixels;

        height = displayMetrics.heightPixels;

        Toast.makeText(MainActivity.this,"width:"+width+", height:"+height,Toast.LENGTH_SHORT).show();

    }

    public void SetBitmapSize(){

        bitmap2 = Bitmap.createScaledBitmap(bitmap1, width, height, false);

    }
}
</code>```

and my layout file. like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/imageView"
        android:src="@drawable/sample_image_wallpaper"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Click here to Set this image as Wallpaper in android programmatically"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="94dp" />

</RelativeLayout>
</code>```

Hope this will help.

Body:
I have a wallpaper app, which sets a selected image as background for the phone's menu. It is scrollable (by default), but the problem is that the background is just a cutout of the original image. Here is my code to set the image as background:

private Bitmap image = [...];

[...]

private void setBackgroundImage(){
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
        wallpaperManager.setBitmap(pic);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

My question now is: How can I determine the right size for the image, so that every phone has the entire picture as it's background picture and not just a cutout?

Body:
my java file: like this

public class MainActivity extends AppCompatActivity {

    Button button;
    ImageView imageView;
    WallpaperManager wallpaperManager ;
    Bitmap bitmap1, bitmap2 ;
    DisplayMetrics displayMetrics ;
    int width, height;
    BitmapDrawable bitmapDrawable ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button)findViewById(R.id.button);

        imageView = (ImageView)findViewById(R.id.imageView);

        wallpaperManager  = WallpaperManager.getInstance(getApplicationContext());

        bitmapDrawable = (BitmapDrawable) imageView.getDrawable();

        bitmap1 = bitmapDrawable.getBitmap();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                GetScreenWidthHeight();

                SetBitmapSize();

                wallpaperManager = WallpaperManager.getInstance(MainActivity.this);

                try {

                    wallpaperManager.setBitmap(bitmap2);

                    wallpaperManager.suggestDesiredDimensions(width, height);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void GetScreenWidthHeight(){

        displayMetrics = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        width = displayMetrics.widthPixels;

        height = displayMetrics.heightPixels;

        Toast.makeText(MainActivity.this,"width:"+width+", height:"+height,Toast.LENGTH_SHORT).show();

    }

    public void SetBitmapSize(){

        bitmap2 = Bitmap.createScaledBitmap(bitmap1, width, height, false);

    }
}

and my layout file. like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/imageView"
        android:src="@drawable/sample_image_wallpaper"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Click here to Set this image as Wallpaper in android programmatically"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="94dp" />

</RelativeLayout>

Hope this will help.


问:
Edittext and error message
I have 9 edittext my question is when you type a number in an edittext I can not type another number in the other 8 edittext remaining For example if I type 5 in editext and 1 if I want to type another 5 in the 8 edittext restants does not put anything and an error message will be displayed.</p>

```<code>    et1.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            tester();
        }
    });
    et2.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {

        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {
            tester();

        }

    });
    et3.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {

        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {
            tester1();

        }

    });
    et4.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {

        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {

        }

    });
    et5.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {

        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {

        }
    });

    et6.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {

        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {

        }
    });
    et7.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {

        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {

        }
    });
    et8.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {

        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {
            tester();

        }
    });
    et9.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {

        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {

        }
    })
protected void tester()

{
    if (et1.getText().toString().equals(et2.getText().toString()) ||
            et1.getText().toString().equals(et3.getText().toString()) ||
            et1.getText().toString().equals(et4.getText().toString()) ||
            et1.getText().toString().equals(et5.getText().toString()) ||
            et1.getText().toString().equals(et6.getText().toString()) ||
            et1.getText().toString().equals(et7.getText().toString()) ||
            et1.getText().toString().equals(et8.getText().toString()) ||
            et1.getText().toString().equals(et9.getText().toString())) {
        Toast.makeText(this, "vous ne devez utiliser ce nombre deux fois ", Toast.LENGTH_SHORT).show();

    }
}
</code>```

答:
use this</p>

```<code>public class MainActivity extends AppCompatActivity {

    EditText edt_1,edt_2,edt_3,edt_4,edt_5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edt_1 = (EditText)findViewById(R.id.edt_1);
        edt_2 = (EditText)findViewById(R.id.edt_2);
        edt_3 = (EditText)findViewById(R.id.edt_3);
        edt_4 = (EditText)findViewById(R.id.edt_4);
        edt_5 = (EditText)findViewById(R.id.edt_5);

        editTextWatcher(edt_1);
        editTextWatcher(edt_2);
        editTextWatcher(edt_3);
        editTextWatcher(edt_4);
        editTextWatcher(edt_5);
    }

    public void editTextWatcher(final EditText edt) {
        edt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                edt.removeTextChangedListener(this);
                edt.setText("");
                edt.addTextChangedListener(this);

                ArrayList<String> texts = new ArrayList<String>();
                texts.add(edt_1.getText().toString());
                texts.add(edt_2.getText().toString());
                texts.add(edt_3.getText().toString());
                texts.add(edt_4.getText().toString());
                texts.add(edt_5.getText().toString());

                for (String text : texts){
                    if(s.toString().equals(text)){
                        Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
                        edt.removeTextChangedListener(this);
                        edt.setText("");
                        edt.addTextChangedListener(this);
                        return;
                    }
                }

                edt.removeTextChangedListener(this);
                edt.setText(s.toString());
                edt.addTextChangedListener(this);

            }
        });
    }

}
</code>```

Title: Edittext and error message

Body:
I have 9 edittext my question is when you type a number in an edittext I can not type another number in the other 8 edittext remaining For example if I type 5 in editext and 1 if I want to type another 5 in the 8 edittext restants does not put anything and an error message will be displayed.

    et1.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            tester();
        }
    });
    et2.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {

        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {
            tester();

        }

    });
    et3.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {

        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {
            tester1();

        }

    });
    et4.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {

        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {

        }

    });
    et5.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {

        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {

        }
    });

    et6.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {

        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {

        }
    });
    et7.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {

        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {

        }
    });
    et8.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {

        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {
            tester();

        }
    });
    et9.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {

        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {

        }

        @Override
        public void afterTextChanged(final Editable s) {

        }
    })
protected void tester()

{
    if (et1.getText().toString().equals(et2.getText().toString()) ||
            et1.getText().toString().equals(et3.getText().toString()) ||
            et1.getText().toString().equals(et4.getText().toString()) ||
            et1.getText().toString().equals(et5.getText().toString()) ||
            et1.getText().toString().equals(et6.getText().toString()) ||
            et1.getText().toString().equals(et7.getText().toString()) ||
            et1.getText().toString().equals(et8.getText().toString()) ||
            et1.getText().toString().equals(et9.getText().toString())) {
        Toast.makeText(this, "vous ne devez utiliser ce nombre deux fois ", Toast.LENGTH_SHORT).show();

    }
}

Body:
use this

public class MainActivity extends AppCompatActivity {

    EditText edt_1,edt_2,edt_3,edt_4,edt_5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edt_1 = (EditText)findViewById(R.id.edt_1);
        edt_2 = (EditText)findViewById(R.id.edt_2);
        edt_3 = (EditText)findViewById(R.id.edt_3);
        edt_4 = (EditText)findViewById(R.id.edt_4);
        edt_5 = (EditText)findViewById(R.id.edt_5);

        editTextWatcher(edt_1);
        editTextWatcher(edt_2);
        editTextWatcher(edt_3);
        editTextWatcher(edt_4);
        editTextWatcher(edt_5);
    }

    public void editTextWatcher(final EditText edt) {
        edt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                edt.removeTextChangedListener(this);
                edt.setText("");
                edt.addTextChangedListener(this);

                ArrayList<String> texts = new ArrayList<String>();
                texts.add(edt_1.getText().toString());
                texts.add(edt_2.getText().toString());
                texts.add(edt_3.getText().toString());
                texts.add(edt_4.getText().toString());
                texts.add(edt_5.getText().toString());

                for (String text : texts){
                    if(s.toString().equals(text)){
                        Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
                        edt.removeTextChangedListener(this);
                        edt.setText("");
                        edt.addTextChangedListener(this);
                        return;
                    }
                }

                edt.removeTextChangedListener(this);
                edt.setText(s.toString());
                edt.addTextChangedListener(this);

            }
        });
    }

}


问:
Error 500 after Laravel 5.4 upload
I have a laravel 5.4 app and I did upload this on a shared hosting server and did change .env file...

But I still have error 500

When I use php error reporting, this report will come from server:

Warning: require(/home/axaanir/domains/photobooks.ir/public_html/vendor/composer/../guzzlehttp/psr7/src/functions_include.php): failed to open stream: No such file or directory in /home/axaanir/domains/photobooks.ir/public_html/vendor/composer/autoload_real.php on line 66

Fatal error: require(): Failed opening required '/home/axaanir/domains/photobooks.ir/public_html/vendor/composer/../guzzlehttp/psr7/src/functions_include.php' (include_path='.:/usr/local/php-5.6/lib/php') in /home/axaanir/domains/photobooks.ir/public_html/vendor/composer/autoload_real.php on line 66

But these folder exists on the returned path by server...!!!
Does anyone know how should I fix this?

Thanks in advance...

答:
Make sure you run a composer install on the server.

check you can storage write permission to storage folder

You need to define path to public in your apache configuration to be
able to open without public

Title: Error 500 after Laravel 5.4 upload


问:
Run code once a day
I was just wondering if it is possible to have a javascript for loop that only iterates through the loop once a day i.e. when the date changes?

```<code>for(i=0; i < myArray.length; i++){

    alert(myArray[i]);

}
</code>```

So in the above loop, let it run, and freeze it or something only till the data changes, and the do another iteration, and just keep on doing that.. You know what I mean.

Thanks in advance!

答:
the best way to achieve it is by creating a cookie that lasts for1 day..
Even if after the refresh of the web page or browser gets closed that countdown will still continue..

```<code>setcookie($cookie_name, $cookie_value, time() + 86400, "/");
</code>```

This means 86400 = 1 day

Hope it helps

Title: Run code once a day

Body:
I was just wondering if it is possible to have a javascript for loop that only iterates through the loop once a day i.e. when the date changes?

for(i=0; i < myArray.length; i++){

    alert(myArray[i]);

}

So in the above loop, let it run, and freeze it or something only till the data changes, and the do another iteration, and just keep on doing that.. You know what I mean.

Thanks in advance!

Body:
the best way to achieve it is by creating a cookie that lasts for1 day..
Even if after the refresh of the web page or browser gets closed that countdown will still continue..

setcookie($cookie_name, $cookie_value, time() + 86400, "/");

This means 86400 = 1 day

Hope it helps


问:
Laravel 5 Can't send data from url
Hi Im currently trying to make a basic crud for my questions resource on laravel 5

so far so good, but now Im having troubles displaying the edit view, because the url is not being created correctly when I try to send the resource id in the url

here's the anchor Im using

```<code><a href="{{route('admin/questions/update',$question->id)}}"><button class="submit-form button button btn btn-primary" style="margin: 0 1em;" type="submit">Editar</button></a>
</code>```

here's the route in my routes file

```<code>Route::get('admin/preguntas/editar/{id}','QuestionsController@edit')->name('admin/questions/update');
</code>```

the method in the controller works just fine, when I manually type this url

/admin/preguntas/editar/4

It shows the view without problems, but when I go from the anchor the url it goes is this one

/admin/preguntas/editar?4

of course the 4 is the id from my resource, but why is not typing the correct url?

thanks in advance

答:
First write proper link button as Devon said:

```<code><a href="{{route('admin.questions.update', ['id' => $question->id])}}" class="submit-form button button btn btn-primary" style="margin: 0 1em;">Editar</a>
</code>```

Second you must write proper route name format:

```<code>Route::get('admin/preguntas/editar/{id}','QuestionsController@edit')->name('admin.questions.update');
</code>```

Hope it will help you to solve the problem :)

Title: Laravel 5 Can't send data from url

Body:
Hi Im currently trying to make a basic crud for my questions resource on laravel 5

so far so good, but now Im having troubles displaying the edit view, because the url is not being created correctly when I try to send the resource id in the url

here's the anchor Im using

id)}}"><button class="submit-form button button btn btn-primary" style="margin: 0 1em;" type="submit">Editar</button>

here's the route in my routes file

Route::get('admin/preguntas/editar/{id}','QuestionsController@edit')->name('admin/questions/update');

the method in the controller works just fine, when I manually type this url

/admin/preguntas/editar/4

It shows the view without problems, but when I go from the anchor the url it goes is this one

/admin/preguntas/editar?4

of course the 4 is the id from my resource, but why is not typing the correct url?

thanks in advance

Body:
First write proper link button as Devon said:

<a href="{{route('admin.questions.update', ['id' => $question->id])}}" class="submit-form button button btn btn-primary" style="margin: 0 1em;">Editar</a>

Second you must write proper route name format:

Route::get('admin/preguntas/editar/{id}','QuestionsController@edit')->name('admin.questions.update');

Hope it will help you to solve the problem :)


问:
Removing the file extension from URLs, like .php or .html
I want to remove my any extension of file from URLs of my website.

For example: www.example.ml/dash/logins/sign.php

to: www.example/dash/logins/sign/

I had done a lot of googling, but none of the answers worked for me.
I think it didn't work, because in the logins folder I have not a single file.

There are many other files, like index.php, sign.php, etc. Do I have to keep each file in a separate folder or sing.php can change to sign/.  Also, what would happen to this:

```<code>sign.php?usercode=1
</code>```

Will it get converted to

```<code>sign/usercode=1
</code>```

?

I already have some code present in .htaccess, so please give your answer after referring this code.

```<code>php_value display_errors Off
php_flag magic_quotes 1
php_flag magic_quotes_gpc 1
php_value mbstring.http_input auto
php_value date.timezone America/New_York

Options -Indexes

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www.example.ml$ [NC]

RewriteRule ^(.*)$ https://www.example.ml/$1 [L,R=301]
</code>```

答:
Use this code in your .htaccess file. It will redirect to PHP file into a non-PHP version.

```<code># Turn on the rewrite engine
RewriteEngine  on
# If the request doesn't end in .php (case insensitive) continue processing rules
RewriteCond %{REQUEST_URI} !\.php$ [NC]
# If the request doesn't end in a slash continue processing the rules
RewriteCond %{REQUEST_URI} [^/]$
# Rewrite the request with a .php extension. L means this is the 'Last' rule
RewriteRule ^(.*)$ $1.php [L]
</code>```

The example is taken from Tim Bielwa,
Remove .php extension with .htaccess

Body:
I want to remove my any extension of file from URLs of my website.

For example: www.example.ml/dash/logins/sign.php

to: www.example/dash/logins/sign/

I had done a lot of googling, but none of the answers worked for me.
I think it didn't work, because in the logins folder I have not a single file.

There are many other files, like index.php, sign.php, etc. Do I have to keep each file in a separate folder or sing.php can change to sign/.  Also, what would happen to this:

sign.php?usercode=1

Will it get converted to

sign/usercode=1

?

I already have some code present in .htaccess, so please give your answer after referring this code.

php_value display_errors Off
php_flag magic_quotes 1
php_flag magic_quotes_gpc 1
php_value mbstring.http_input auto
php_value date.timezone America/New_York

Options -Indexes

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www.example.ml$ [NC]

RewriteRule ^(.*)$ https://www.example.ml/$1 [L,R=301]

Body:
Use this code in your .htaccess file. It will redirect to PHP file into a non-PHP version.

# Turn on the rewrite engine
RewriteEngine  on
# If the request doesn't end in .php (case insensitive) continue processing rules
RewriteCond %{REQUEST_URI} !\.php$ [NC]
# If the request doesn't end in a slash continue processing the rules
RewriteCond %{REQUEST_URI} [^/]$
# Rewrite the request with a .php extension. L means this is the 'Last' rule
RewriteRule ^(.*)$ $1.php [L]

The example is taken from Tim Bielwa,
Remove .php extension with .htaccess


问:
How do I merge two sorted object lists based on common attribute in Java
I have two object lists both with a common attribute called timestamp and both are sorted by timestamp.

I want to broadcast these objects one by one based on the timestamp, example if first object of 1st list has timestamp < first object of 2nd list, broadcast first object of the 1st list and then compare second object of the 1st list with the first object of the 2nd list.

I am a newbie in java. This is what I have come up with:

```<code> //Merge the 2 object lists based on timestamp
        ListIterator<x> xIterator = list1.listIterator();
        ListIterator<y> yIterator = list2.listIterator();
        while (xIterator.hasNext() && yIterator.hasNext()) {
            if (xIterator.next().timestamp <= yIterator.next().timestamp) {
                Bundle extra = new Bundle();
                extra.putParcelable(LocalBroadcastConstants.ACTION, xIterator.previous());
                MyBroadcastManager.getInstance(getTargetContext()).sendBroadcast(
                        new Intent(LocalBroadcastConstants.ACTION_SEND).putExtras(extra)
                );
                yIterator.previous();
            } else {
                Bundle extra = new Bundle();
                extra.putParcelable(LocalBroadcastConstants.ACTION,
                        yIterator.previous());
                MyBroadcastManager.getInstance(getTargetContext()).sendBroadcast(
                        new Intent(LocalBroadcastConstants.ACTION_SEND).putExtras(extra)
                );
                xIterator.previous();
            }
</code>```

I know my logic is incorrect because for the first item in the Iterators, xIterator.previous and yIterator.previous will point to nothing. I can't seem to find the correct solution for this problem statement. Please help.

答:
A simple but easy to implement solution:

create a list that simply contains all objects from both lists

create a Comparator that knows how to extract timestamps from both different classes - to then compare them

use Collections .sort() to sort the merged list using that comparator

That's it. Now you loop the sorted list to broadcast objects in order.

Body:
I have two object lists both with a common attribute called timestamp and both are sorted by timestamp.

I want to broadcast these objects one by one based on the timestamp, example if first object of 1st list has timestamp < first object of 2nd list, broadcast first object of the 1st list and then compare second object of the 1st list with the first object of the 2nd list.

I am a newbie in java. This is what I have come up with:

 //Merge the 2 object lists based on timestamp
        ListIterator<x> xIterator = list1.listIterator();
        ListIterator<y> yIterator = list2.listIterator();
        while (xIterator.hasNext() && yIterator.hasNext()) {
            if (xIterator.next().timestamp <= yIterator.next().timestamp) {
                Bundle extra = new Bundle();
                extra.putParcelable(LocalBroadcastConstants.ACTION, xIterator.previous());
                MyBroadcastManager.getInstance(getTargetContext()).sendBroadcast(
                        new Intent(LocalBroadcastConstants.ACTION_SEND).putExtras(extra)
                );
                yIterator.previous();
            } else {
                Bundle extra = new Bundle();
                extra.putParcelable(LocalBroadcastConstants.ACTION,
                        yIterator.previous());
                MyBroadcastManager.getInstance(getTargetContext()).sendBroadcast(
                        new Intent(LocalBroadcastConstants.ACTION_SEND).putExtras(extra)
                );
                xIterator.previous();
            }

I know my logic is incorrect because for the first item in the Iterators, xIterator.previous and yIterator.previous will point to nothing. I can't seem to find the correct solution for this problem statement. Please help.