问:
overriding malloc, free and calloc cause recursion in Linux
I have overridden the functions malloc, calloc and free functions in Linux platform as below:

```<code>#include <stdio.h>
#include <dlfcn.h>
#include <stdlib.h>
typedef void* (*MALLOCFN)(size_t);
typedef void* (*CALLOCFN)(size_t, size_t);
typedef void* (*CALLOCFN)(size_t, size_t);
typedef void (*FREEFN)(void *);
MALLOCFN real_malloc = (MALLOCFN) 0;
CALLOCFN real_calloc = (CALLOCFN) 0;
FREEFN real_free = (FREEFN) 0;
void *get_realfn(const char *fnm)
{
  void *pfunc = (void *) NULL;
  printf("searching for original %s\n", fnm);
  pfunc = dlsym(RTLD_NEXT, fnm);
  if (pfunc) printf("found original %s\n", fnm);
  else printf("not found original %s\n", fnm);
  return pfunc;
}
void *malloc(size_t s)
{
  printf("called malloc\n");
  if(real_malloc == NULL) real_malloc = (MALLOCFN) get_realfn("malloc");
  if (real_malloc) return real_malloc(s);
  else return NULL;
}
void *calloc(size_t s1, size_t s2)
{
  printf("called calloc\n");
  if(real_calloc == NULL) real_calloc = (CALLOCFN) get_realfn("calloc");
  if (real_calloc) return real_calloc(s1, s2);
  else return NULL;
}
void free (void * ptr)
{
  printf("called free\n");
  if(real_free == NULL) real_free = (FREEFN) get_realfn("free");
  if (real_free) real_free(ptr);
}
int main()
{
  char * c1 = (char *) malloc(400);
  char * c2 = (char *) malloc(400);
  free(c2); free(c1);
  return 0;
}
</code>```

The C program (testalloc.c) is built using g++ 4.9.2 version of compiler:

```<code>g++ -g testalloc.c  -ldl -o testalloc;
</code>```

The first few lines of output shown is as below, it enters into infinite recursion and crashes:

```<code>called malloc
searching for original malloc
called free
searching for original free
called free
searching for original free
called free
searching for original free
called free
searching for original free
called free
. . . .
</code>```

Please suggest how to avoid the recursion.

答:
printf function may allocate memory. So when you call printf before the "real" function pointers are not assigned, it comes into your interposed functions resulting in infinite recursion. So do not use printf statements in the interposing functions.

If you really need to print something, use syscall(2), which would bypass stdio library functions.

```<code>#include <sys/syscall.h>

...

syscall(SYS_write, STDOUT_FILENO, "searching for original\n",
                                  sizeof "searching for original\n" - 1);
</code>```

Body:
I have overridden the functions malloc, calloc and free functions in Linux platform as below:

#include <stdio.h>
#include <dlfcn.h>
#include <stdlib.h>
typedef void* (*MALLOCFN)(size_t);
typedef void* (*CALLOCFN)(size_t, size_t);
typedef void* (*CALLOCFN)(size_t, size_t);
typedef void (*FREEFN)(void *);
MALLOCFN real_malloc = (MALLOCFN) 0;
CALLOCFN real_calloc = (CALLOCFN) 0;
FREEFN real_free = (FREEFN) 0;
void *get_realfn(const char *fnm)
{
  void *pfunc = (void *) NULL;
  printf("searching for original %s\n", fnm);
  pfunc = dlsym(RTLD_NEXT, fnm);
  if (pfunc) printf("found original %s\n", fnm);
  else printf("not found original %s\n", fnm);
  return pfunc;
}
void *malloc(size_t s)
{
  printf("called malloc\n");
  if(real_malloc == NULL) real_malloc = (MALLOCFN) get_realfn("malloc");
  if (real_malloc) return real_malloc(s);
  else return NULL;
}
void *calloc(size_t s1, size_t s2)
{
  printf("called calloc\n");
  if(real_calloc == NULL) real_calloc = (CALLOCFN) get_realfn("calloc");
  if (real_calloc) return real_calloc(s1, s2);
  else return NULL;
}
void free (void * ptr)
{
  printf("called free\n");
  if(real_free == NULL) real_free = (FREEFN) get_realfn("free");
  if (real_free) real_free(ptr);
}
int main()
{
  char * c1 = (char *) malloc(400);
  char * c2 = (char *) malloc(400);
  free(c2); free(c1);
  return 0;
}

The C program (testalloc.c) is built using g++ 4.9.2 version of compiler:

g++ -g testalloc.c  -ldl -o testalloc;

The first few lines of output shown is as below, it enters into infinite recursion and crashes:

called malloc
searching for original malloc
called free
searching for original free
called free
searching for original free
called free
searching for original free
called free
searching for original free
called free
. . . .

Please suggest how to avoid the recursion.

Body:
printf function may allocate memory. So when you call printf before the "real" function pointers are not assigned, it comes into your interposed functions resulting in infinite recursion. So do not use printf statements in the interposing functions.

If you really need to print something, use syscall(2), which would bypass stdio library functions.

#include <sys/syscall.h>

...

syscall(SYS_write, STDOUT_FILENO, "searching for original\n",
                                  sizeof "searching for original\n" - 1);


来源: stackexchange

问:
C# Cannot access a disposed object when adding rows asynchronously to a winform datagridview
I am loading docs in a datagridview from a parallel thread using the code below:
inside a block Task.Run(() => {});

When I close the form I get ObjectDisposedException Cannot access a disposed object. Looks like the if (IsDisposed || Disposing) fails and the code attempts to add a row and in the meantime Disposing has became true.

I could catch this exception but it is dirty.

Adding a flag enabled when closing the form to check if the form has been closed does not work as well. It seems to behave the same way as this.Disposing

Adding a Thread.Sleep(5); before if (this.IsDisposed || this.Disposing) seems enough to avoid the exception to be raised though I am not sure if it could be raised if unlucky enough.

What would probably be the best practice to avoid this issue ?

```<code>  foreach (var doc in docList)
  {
     if (this.InvokeRequired)
     {
         if (IsDisposed || Disposing || dgv.IsDisposed || dgv.isposing) return;
         this.Invoke(new MethodInvoker(() => { dgv.Rows.Add(doc.Name); }));
     }
  }
</code>```

答:
Don't know what you want to do with form after closing. If it's okay to just hide it use this:</p>

```<code>private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        e.Cancel = true;
        this.Hide();
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am loading docs in a datagridview from a parallel thread using the code below:
inside a block Task.Run(() => {});

When I close the form I get ObjectDisposedException Cannot access a disposed object. Looks like the if (IsDisposed || Disposing) fails and the code attempts to add a row and in the meantime Disposing has became true.

I could catch this exception but it is dirty.

Adding a flag enabled when closing the form to check if the form has been closed does not work as well. It seems to behave the same way as this.Disposing

Adding a Thread.Sleep(5); before if (this.IsDisposed || this.Disposing) seems enough to avoid the exception to be raised though I am not sure if it could be raised if unlucky enough.

What would probably be the best practice to avoid this issue ?

  foreach (var doc in docList)
  {
     if (this.InvokeRequired)
     {
         if (IsDisposed || Disposing || dgv.IsDisposed || dgv.isposing) return;
         this.Invoke(new MethodInvoker(() => { dgv.Rows.Add(doc.Name); }));
     }
  }

Body:
Don't know what you want to do with form after closing. If it's okay to just hide it use this:

private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        e.Cancel = true;
        this.Hide();
    }


问:
Activity is resetting values
I have an activity that sum distance according user walks. The problem is when app goes to background and after something around 50 minutes I resume activity, values start again.
I have tried too many things to solve this problem without success.

Does someone have any idea?

Thanks

答:
There is a simple solution go to your manifest file and for that specific activity add below provided line:</p>

```<code><activity
        android:name=".yourActivity"
        android:launchMode="singleTask"
        />
</code>```

Title: Activity is resetting values

Body:
There is a simple solution go to your manifest file and for that specific activity add below provided line:

<activity
        android:name=".yourActivity"
        android:launchMode="singleTask"
        />


问:
Filter for the List<List<String>>
I am trying to write a method that would filter the duplicate inputs in a list of lists of Strings. The problem is that by duplicates I mean also the lists that have the same elemets buts in a different order. So I would like that if the input list is :

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

it would return only

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

I tried to do something like:

```<code>public List<List<String>> filter (List<List<String>> list){
    List<List<String>> filteredList = new LinkedList<>();
    filteredList.addAll(list);
    for(List<String> i:list){
        for(List<String> j:list){
            if (!i.equals(j)&&i.containsAll(j)){
                filteredList.remove(j);
            }
        }
    }
    return filteredList;
}
</code>```

but it would remove too much cause it would still iterate through the whole original list and would find that element "a" is duplicate of element "b" and vice versa. On the other side when I try to do that on the same list (without a temp) I get ConcurrentModificationException cause I can't modify and iterate over the same collection at the same time. Adding the list to a Set would not solve the issue because they are not exact duplicates (.equals would return false). Is there any possible solution to achieve at?

答: Create a new Class for the inner List with a equals-method that does what you need. You could use a set for this.</p>

Title: Filter for the List<List<String>>

Body:
I am trying to write a method that would filter the duplicate inputs in a list of lists of Strings. The problem is that by duplicates I mean also the lists that have the same elemets buts in a different order. So I would like that if the input list is :

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

it would return only

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

I tried to do something like:

public List<List<String>> filter (List<List<String>> list){
    List<List<String>> filteredList = new LinkedList<>();
    filteredList.addAll(list);
    for(List<String> i:list){
        for(List<String> j:list){
            if (!i.equals(j)&&i.containsAll(j)){
                filteredList.remove(j);
            }
        }
    }
    return filteredList;
}

but it would remove too much cause it would still iterate through the whole original list and would find that element "a" is duplicate of element "b" and vice versa. On the other side when I try to do that on the same list (without a temp) I get ConcurrentModificationException cause I can't modify and iterate over the same collection at the same time. Adding the list to a Set would not solve the issue because they are not exact duplicates (.equals would return false). Is there any possible solution to achieve at?


问:
Printing very large BigIntegers to a file in Java
I'm trying to print a very large BigInteger to a .txt file, but when the number reaches a certain size, it prints nothing. Code:

```<code>BigInteger bi = new BigInteger("16777216");
int exponent = 1000000;
bi = bi.pow(exponent);

String txtToPrint = bi.toString();
sendToFile(txtToPrint, "output.txt");

private static void sendToFile(String txtToPrint, String fileName) {

        try {

            FileWriter fileWriter = new FileWriter(fileName);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(txtToPrint);

            bufferedWriter.close();
        }
        catch(IOException e) {
            System.out.println("Error writing to file '" + fileName + "'");
        }

}
</code>```

Whenever the exponent is greater than 566 the output file is empty, instead of containing the number. The goal is to have an exponent of 1 000 000, or even greater.

I thought BigInteger did not have a size limit, so my question is: What limit am I exceeding and is there a way to solve this problem?

EDIT: When trying to flush and close the filewriter, I got this exception:

```<code>java.io.IOException: Stream closed
at sun.nio.cs.StreamEncoder.ensureOpen(Unknown Source)
at sun.nio.cs.StreamEncoder.flush(Unknown Source)
at java.io.OutputStreamWriter.flush(Unknown Source)
at PrintInt.main(PrintInt.java:4
</code>```

EDIT: The problem only occurs when running the program in Eclipse, I tried exporting it to an external jar, and everything worked just fine. I am using Eclipse Mars.1 Release (4.5.1) and Java jre1.8.0_131 and Cp1252 encoding.

答:
I am mostly guessing here. I would guess the problem come from the BufferWriter.

Let's try with a more direct approch, Outputstream and try with resource to close everything properly.

```<code>File f = new File(fileName);
try (
        FileOutputStream fos = new FileOutputStream(f);
        OutputStreamWriter os = new OutputStreamWriter(fos);
        Writer out = new BufferedWriter(os)
){
    out.write(txtToPrint);
} catch(IOException e) {
    System.out.println("Error writing to file '" + fileName + "'");
}
</code>```

I have seen it in the past some OS synchronization issues but the file never loose the data, the data is just copied with a small delayed... but why not ... after the write, just wait for the OS to validate the data is flush in the file (not in the OS cache)

```<code>out.flush(); //flush the stream
fos.getFD().sync(); //sync with the OS
</code>```

Body:
I'm trying to print a very large BigInteger to a .txt file, but when the number reaches a certain size, it prints nothing. Code:

BigInteger bi = new BigInteger("16777216");
int exponent = 1000000;
bi = bi.pow(exponent);

String txtToPrint = bi.toString();
sendToFile(txtToPrint, "output.txt");

private static void sendToFile(String txtToPrint, String fileName) {

        try {

            FileWriter fileWriter = new FileWriter(fileName);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(txtToPrint);

            bufferedWriter.close();
        }
        catch(IOException e) {
            System.out.println("Error writing to file '" + fileName + "'");
        }

}

Whenever the exponent is greater than 566 the output file is empty, instead of containing the number. The goal is to have an exponent of 1 000 000, or even greater.

I thought BigInteger did not have a size limit, so my question is: What limit am I exceeding and is there a way to solve this problem?

EDIT: When trying to flush and close the filewriter, I got this exception:

java.io.IOException: Stream closed
at sun.nio.cs.StreamEncoder.ensureOpen(Unknown Source)
at sun.nio.cs.StreamEncoder.flush(Unknown Source)
at java.io.OutputStreamWriter.flush(Unknown Source)
at PrintInt.main(PrintInt.java:4

EDIT: The problem only occurs when running the program in Eclipse, I tried exporting it to an external jar, and everything worked just fine. I am using Eclipse Mars.1 Release (4.5.1) and Java jre1.8.0_131 and Cp1252 encoding.

Body:
I am mostly guessing here. I would guess the problem come from the BufferWriter.

Let's try with a more direct approch, Outputstream and try with resource to close everything properly.

File f = new File(fileName);
try (
        FileOutputStream fos = new FileOutputStream(f);
        OutputStreamWriter os = new OutputStreamWriter(fos);
        Writer out = new BufferedWriter(os)
){
    out.write(txtToPrint);
} catch(IOException e) {
    System.out.println("Error writing to file '" + fileName + "'");
}

I have seen it in the past some OS synchronization issues but the file never loose the data, the data is just copied with a small delayed... but why not ... after the write, just wait for the OS to validate the data is flush in the file (not in the OS cache)

out.flush(); //flush the stream
fos.getFD().sync(); //sync with the OS


问:
Return facebook profile details xamarin.forms
I am creating a facebook login for iOS and android using xamarin.forms. It successfully allows users to login but I'm not sure how to return the user's details as I need the details to pass to my WebApi. How can I return user's profile details such as name,surname and email.

Code

```<code>public partial class MainPage : ContentPage
    {
        private string ClientId = "";
        public MainPage()
        {
            InitializeComponent();

            var apiRequest = "https://www.facebook.com/dialog/oauth?client_id=" + ClientId + "&display=popup&response_type=token&redirect_uri=https://www.facebook.com/connect/login_success.html";

            var webView = new WebView
            {
                Source = apiRequest,
                HeightRequest=1
            };

            webView.Navigated += WebViewOnNavigated;

            Content = webView;
        }

        private async void WebViewOnNavigated(object sender, WebNavigatedEventArgs e)
        {
            var accessToken = ExtractAccessTokenFromUrl(e.Url);

            if(accessToken != "")
            {
                await GetFacebookProfileAsync(accessToken);
                await Navigation.PushAsync(new Success());
            }
        }

        private string ExtractAccessTokenFromUrl(string url)
        {
            if(url.Contains("access_token") && url.Contains("&expires_in"))
            {
                Navigation.PushAsync(new Success());
            }
            return string.Empty;
        }

        public async Task GetFacebookProfileAsync(string accessToken)
        {
            var requestUrl = "https://graph.facebook.com/me/" + "?fields=name,picture,cover,age_range,devices,email,gender,is_verified" + "&access_token=" + accessToken;

            var httpClient = new HttpClient();
            var userJson = await httpClient.GetStringAsync(requestUrl);

        }
    }
</code>```

答:
You need to issue a GET to:

```<code>"https://graph.facebook.com/me?fields=email,first_name,last_name,gender,picture.type(large)"
</code>```

Insert your facebook auth token to headers:

```<code>client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
</code>```

Body:
I am creating a facebook login for iOS and android using xamarin.forms. It successfully allows users to login but I'm not sure how to return the user's details as I need the details to pass to my WebApi. How can I return user's profile details such as name,surname and email.

Code

public partial class MainPage : ContentPage
    {
        private string ClientId = "";
        public MainPage()
        {
            InitializeComponent();

            var apiRequest = "https://www.facebook.com/dialog/oauth?client_id=" + ClientId + "&display=popup&response_type=token&redirect_uri=https://www.facebook.com/connect/login_success.html";

            var webView = new WebView
            {
                Source = apiRequest,
                HeightRequest=1
            };

            webView.Navigated += WebViewOnNavigated;

            Content = webView;
        }

        private async void WebViewOnNavigated(object sender, WebNavigatedEventArgs e)
        {
            var accessToken = ExtractAccessTokenFromUrl(e.Url);

            if(accessToken != "")
            {
                await GetFacebookProfileAsync(accessToken);
                await Navigation.PushAsync(new Success());
            }
        }

        private string ExtractAccessTokenFromUrl(string url)
        {
            if(url.Contains("access_token") && url.Contains("&expires_in"))
            {
                Navigation.PushAsync(new Success());
            }
            return string.Empty;
        }

        public async Task GetFacebookProfileAsync(string accessToken)
        {
            var requestUrl = "https://graph.facebook.com/me/" + "?fields=name,picture,cover,age_range,devices,email,gender,is_verified" + "&access_token=" + accessToken;

            var httpClient = new HttpClient();
            var userJson = await httpClient.GetStringAsync(requestUrl);

        }
    }

Body:
You need to issue a GET to:

"https://graph.facebook.com/me?fields=email,first_name,last_name,gender,picture.type(large)"

Insert your facebook auth token to headers:

client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);


问:
Windows batch: replace strings in a file case sensitively
I've spent a lot of time writing a script to generate new files using a "template" (coding env.) project.

While on Unix the shell script is laughably easy I spent days doing the same on Windows...

My current batch file does almost everything I need, except that the string replacement is case-insensitive... That is, it replaces "emptyproject" with "EMPTYPROJECT", being the first statement...

Code:

```<code>@echo off & setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION

set argc=0
for %%x in (%*) do set /A argc+=1

if /I "%argc%" EQU "0" (
 echo Usage: %0 PROJECT_NAME >&2
 exit /B 1
)

set curr_dir=%~dp0
set project_name=%1
set project_name_lower=%1
set project_name_upper=%1
set project_file="vstudio\projects\%project_name%.vcxproj"
set project_filters="vstudio\projects\%project_name%.vcxproj.filters"

call :toupper project_name_upper
call :tolower project_name_lower

if not exist %project_file% (
 copy /y "vstudio\projects\EmptyProject.vcxproj" %project_file% >nul
 copy /y "vstudio\projects\EmptyProject.vcxproj.filters" %project_filters% >nul
)

set project_source_dir=..\projects\source\%project_name_lower%

if not exist %project_source_dir% (
 mkdir %project_source_dir%

 call :copy_and_replace_strings "..\projects\source\emptyproject\main.cpp" "%project_source_dir%\main.cpp" %project_name% %project_name_lower% %project_name_upper%
 call :copy_and_replace_strings "..\projects\source\emptyproject\emptyproject.h" "%project_source_dir%\%project_name_lower%.h" %project_name% %project_name_lower% %project_name_upper%
 call :copy_and_replace_strings "..\projects\source\emptyproject\emptyproject_main.cpp" "%project_source_dir%\%project_name_lower%_main.cpp" %project_name% %project_name_lower% %project_name_upper%
 call :copy_and_replace_strings "..\projects\source\emptyproject\emptyproject_eventhandlers.cpp" "%project_source_dir%\%project_name_lower%_eventhandlers.cpp" %project_name% %project_name_lower% %project_name_upper%
)

endlocal
goto :EOF

REM functions
:toupper
 for %%L IN (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO SET %1=!%1:%%L=%%L!
 goto :EOF

:tolower
 for %%L IN (a b c d e f g h i j k l m n o p q r s t u v w x y z) DO SET %1=!%1:%%L=%%L!
 goto :EOF

:copy_and_replace_strings <source_file> <target_file> <name> <lower> <upper>
 for /f "tokens=1,* delims=]" %%a in ('find /n /v "" ^< %1') do (
  set token1=%%a
  set token2=%%b

  if defined token2 (
REM not case sensitive
   set token2=!token2:EMPTYPROJECT=%5!
   set token2=!token2:EmptyProject=%3!
   set token2=!token2:emptyproject=%4!
   echo !token2!>>%2
  ) else (
   echo[>>%2
  )
 )
 goto :EOF
</code>```

I read a lot about this on this forum, but couldn't find a suitable solution. Could someone help me please?

答:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

FOR %%o IN (EMPTYPROJECT EmptyProject emptyproject EmPtYpRoJeCt) DO (
 SET "token2=A line containing %%o in it"
 CALL :magic
 ECHO !token2! -^> !result!
)

GOTO :EOF

:magic
SET "result=!token2!"
ECHO !token2!|FINDSTR "EMPTYPROJECT" >NUL
IF NOT ERRORLEVEL 1 set "result=!token2:EMPTYPROJECT=capiTaLs!"
ECHO !token2!|FINDSTR "EmptyProject" >NUL
IF NOT ERRORLEVEL 1 set "result=!token2:EMPTYPROJECT=Mixed!"
ECHO !token2!|FINDSTR "emptyproject" >NUL
IF NOT ERRORLEVEL 1 set "result=!token2:EMPTYPROJECT=lower!"
GOTO :eof
```

Perhaps this will be of assistance.

Body:
I've spent a lot of time writing a script to generate new files using a "template" (coding env.) project.

While on Unix the shell script is laughably easy I spent days doing the same on Windows...

My current batch file does almost everything I need, except that the string replacement is case-insensitive... That is, it replaces "emptyproject" with "EMPTYPROJECT", being the first statement...

Code:

@echo off & setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION

set argc=0
for %%x in (%*) do set /A argc+=1

if /I "%argc%" EQU "0" (
 echo Usage: %0 PROJECT_NAME >&2
 exit /B 1
)

set curr_dir=%~dp0
set project_name=%1
set project_name_lower=%1
set project_name_upper=%1
set project_file="vstudio\projects\%project_name%.vcxproj"
set project_filters="vstudio\projects\%project_name%.vcxproj.filters"

call :toupper project_name_upper
call :tolower project_name_lower

if not exist %project_file% (
 copy /y "vstudio\projects\EmptyProject.vcxproj" %project_file% >nul
 copy /y "vstudio\projects\EmptyProject.vcxproj.filters" %project_filters% >nul
)

set project_source_dir=..\projects\source\%project_name_lower%

if not exist %project_source_dir% (
 mkdir %project_source_dir%

 call :copy_and_replace_strings "..\projects\source\emptyproject\main.cpp" "%project_source_dir%\main.cpp" %project_name% %project_name_lower% %project_name_upper%
 call :copy_and_replace_strings "..\projects\source\emptyproject\emptyproject.h" "%project_source_dir%\%project_name_lower%.h" %project_name% %project_name_lower% %project_name_upper%
 call :copy_and_replace_strings "..\projects\source\emptyproject\emptyproject_main.cpp" "%project_source_dir%\%project_name_lower%_main.cpp" %project_name% %project_name_lower% %project_name_upper%
 call :copy_and_replace_strings "..\projects\source\emptyproject\emptyproject_eventhandlers.cpp" "%project_source_dir%\%project_name_lower%_eventhandlers.cpp" %project_name% %project_name_lower% %project_name_upper%
)

endlocal
goto :EOF

REM functions
:toupper
 for %%L IN (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO SET %1=!%1:%%L=%%L!
 goto :EOF

:tolower
 for %%L IN (a b c d e f g h i j k l m n o p q r s t u v w x y z) DO SET %1=!%1:%%L=%%L!
 goto :EOF

:copy_and_replace_strings <source_file> <target_file> <name> <lower> <upper>
 for /f "tokens=1,* delims=]" %%a in ('find /n /v "" ^< %1') do (
  set token1=%%a
  set token2=%%b

  if defined token2 (
REM not case sensitive
   set token2=!token2:EMPTYPROJECT=%5!
   set token2=!token2:EmptyProject=%3!
   set token2=!token2:emptyproject=%4!
   echo !token2!>>%2
  ) else (
   echo[>>%2
  )
 )
 goto :EOF

I read a lot about this on this forum, but couldn't find a suitable solution. Could someone help me please?

Body:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

FOR %%o IN (EMPTYPROJECT EmptyProject emptyproject EmPtYpRoJeCt) DO (
 SET "token2=A line containing %%o in it"
 CALL :magic
 ECHO !token2! -^> !result!
)

GOTO :EOF

:magic
SET "result=!token2!"
ECHO !token2!|FINDSTR "EMPTYPROJECT" >NUL
IF NOT ERRORLEVEL 1 set "result=!token2:EMPTYPROJECT=capiTaLs!"
ECHO !token2!|FINDSTR "EmptyProject" >NUL
IF NOT ERRORLEVEL 1 set "result=!token2:EMPTYPROJECT=Mixed!"
ECHO !token2!|FINDSTR "emptyproject" >NUL
IF NOT ERRORLEVEL 1 set "result=!token2:EMPTYPROJECT=lower!"
GOTO :eof

Perhaps this will be of assistance.


问:
phpinfo() is not working on my CentOS server
I have PHP installed on my CentOS server. However, when running a phpinfo() inside my script to test it, I receive the HTML, not the interpreted information.

I can see the folders for PHP. I can even see the php.ini in the etc folder.
But PHP itself does not seem to be working.

I mean my test.php file looks like this:

```<code><?php
    phpinfo();
?>
</code>```

And the response looks like this:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html><head>
<style type="text/css">
body {background-color: #ffffff; color: #000000;}
body, td, th, h1, h2 {font-family: sans-serif;}
pre {margin: 0px; font-family: monospace;}
a:link {color: #000099; text-decoration: none; background-color: #ffffff;}
...
</code>```

and so on.

What seems to be the problem and how do I solve it?

If I copy the HTML returned, paste it into an HTML file, and run it from there, I can see the formatted result, but not by running the test.php. I assume PHP is not loaded somehow... even if in the interpreted HTML I can see the:

```<code>**Server API    Apache 2.0 Handler
Virtual Directory Support    disabled
Configuration File (php.ini) Path    /etc/php.ini
Scan this dir for additional .ini files    /etc/php.d
additional .ini files parsed    /etc/php.d/dbase.ini, /etc/php.d/json.ini, /etc/php.d/mysql.ini, /etc/php.d/mysqli.ini, /etc/php.d/pdo.ini, /etc/php.d/pdo_mysql.ini, /etc/php.d/pdo_sqlite.ini
PHP API    20041225
PHP Extension    20050922
Zend Extension    220051025
Debug Build    no
Thread Safety    disabled
Zend Memory Manager    enabled
IPv6 Support    enabled
Registered PHP Streams    php, file, http, ftp, compress.bzip2, compress.zlib, https, ftps**
</code>```

and so on...

On this system, there are three websites hosted. Does that have anything to do with this problem?

答:
It happened to me as well. On a newly provisioned Red Hat Linux 7 server.

When I run a PHP page, i.e. info.php, I could see plain text PHP scripts instead of executing them.

I just installed PHP:

```<code>[root@localhost ~]# yum install php
</code>```

And then restarted Apache HTTP Server:

```<code>[root@localhost ~]# systemctl restart httpd
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have PHP installed on my CentOS server. However, when running a phpinfo() inside my script to test it, I receive the HTML, not the interpreted information.

I can see the folders for PHP. I can even see the php.ini in the etc folder.
But PHP itself does not seem to be working.

I mean my test.php file looks like this:

<?php
    phpinfo();
?>

And the response looks like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">

Body:
It happened to me as well. On a newly provisioned Red Hat Linux 7 server.

When I run a PHP page, i.e. info.php, I could see plain text PHP scripts instead of executing them.

I just installed PHP:

[root@localhost ~]# yum install php

And then restarted Apache HTTP Server:

[root@localhost ~]# systemctl restart httpd


问:
Sample Cocoa app, ref counting, [pool drain] yields EXC_BAD_ACCESS?
I'm working through Cocoa Programming for Mac OS X (3rd ed) and in chapter 4 I wrote this app:

```<code>int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    //create the date object
    NSCalendarDate *now = [[NSCalendarDate alloc] init];

    //seed random # generator
    srandom(time(NULL));

    NSMutableArray *array;
    array = [[NSMutableArray alloc] init];
    int i;
    for (i=0; i<10; i++){
        //create a date/time that is 'i' weeks from now
        NSCalendarDate *iWeeksFromNow;
        iWeeksFromNow = [now dateByAddingYears:0
                                        months:0
                                          days:(i*7)
                                         hours:0
                                       minutes:0
                                       seconds:0];

        //create a new instance of lottery entry
        LotteryEntry *entry = [[LotteryEntry alloc] init];
        [entry setEntryDate:iWeeksFromNow];

        [array addObject:entry];
        [entry release];
    }
    [now release];
    now = nil;

    for (LotteryEntry *entryToPrint in array) {
        NSLog(@"%@", entryToPrint);
    }
    [array release];
    array = nil;

    NSLog(@"about to drain the pool... (%@)", pool);
    [pool drain];
    NSLog(@"done");
    NSLog(@"GC = %@", [NSGarbageCollector defaultCollector]);
    return 0;
}
</code>```

The LotteryEntry class looks like this:

```<code>@implementation LotteryEntry

- (void)setEntryDate:(NSCalendarDate *)date
{
    entryDate = date;
}

- (NSCalendarDate *)entryDate
{
    return entryDate;
}

- (int)firstNumber
{
    return firstNumber;
}

- (int)secondNumber
{
    return secondNumber;
}

- (id)init
{
    return [self initWithDate:[NSCalendarDate calendarDate]];
}

- (id)initWithDate:(NSCalendarDate *)date
{
    if(![super init])
        return nil;

    NSAssert(date != nil, @"Argument must be non-nil");

    firstNumber = random() % 100 + 1;
    secondNumber = random() % 100 + 1;
    entryDate = [date retain];
    return self;
}

- (NSString *)description
{
    NSString *result;
    result = [[NSString alloc] initWithFormat:@"%@ = %d and %d",
              [entryDate descriptionWithCalendarFormat:@"%b %d %Y"],
              firstNumber,
              secondNumber];
    return result;
}

- (void)dealloc
{
    NSLog(@"deallocating %@", self);
    [entryDate release];
    [super dealloc];
}

@end
</code>```

As you can see I'm retaining and releasing the objects here.  I'm pretty sure my code matches the book's, however when I run the app, at the [pool drain] I get this message:

Program received signal:
  “EXC_BAD_ACCESS”.

I'm not sure what's causing this.  I'm hoping it's something stupid that I missed, but I'd sure appreciate a few other pairs of eyes on it.  Thanks in advance!

(side note:  I'm a .NET developer, so ref counting is pretty foreign to me!)

答:
It also looks like you have a bug in this method:

```<code>- (id)initWithDate:(NSCalendarDate *)date
{
    if(![super init])
        return nil;

    NSAssert(date != nil, @"Argument must be non-nil");

    firstNumber = random() % 100 + 1;
    secondNumber = random() % 100 + 1;
    entryDate = [date retain];
    return self;
}
</code>```

You are essentially discarding the results from [super init], while it may not be a problem in this instance, it could cause serious problems in others.  You should 'always' structure you init methods like this:

```<code>- (id)initWithDate:(NSCalendarDate *)date
{
    if(self = [super init]) {
        NSAssert(date != nil, @"Argument must be non-nil");

        firstNumber = random() % 100 + 1;
        secondNumber = random() % 100 + 1;
        entryDate = [date retain];
}
return self;
</code>```

If you are not going to return self from an init method (for instance it is a factory or something odd like that), you should remember to release self.  It has been alloc'ed, and if you don't return it, it cannot be released properly.  Example:

```<code>- (id) init
{
    NSObject*    newSelf = [[NSObject alloc] init];

    [self release];
    return newSelf;
}
</code>```

OwnerDisplayName: Ben Scheirman

ContentLicense: CC BY-SA 2.5

Body:
I'm working through Cocoa Programming for Mac OS X (3rd ed) and in chapter 4 I wrote this app:

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    //create the date object
    NSCalendarDate *now = [[NSCalendarDate alloc] init];

    //seed random # generator
    srandom(time(NULL));

    NSMutableArray *array;
    array = [[NSMutableArray alloc] init];
    int i;
    for (i=0; i<10; i++){
        //create a date/time that is 'i' weeks from now
        NSCalendarDate *iWeeksFromNow;
        iWeeksFromNow = [now dateByAddingYears:0
                                        months:0
                                          days:(i*7)
                                         hours:0
                                       minutes:0
                                       seconds:0];

        //create a new instance of lottery entry
        LotteryEntry *entry = [[LotteryEntry alloc] init];
        [entry setEntryDate:iWeeksFromNow];

        [array addObject:entry];
        [entry release];
    }
    [now release];
    now = nil;

    for (LotteryEntry *entryToPrint in array) {
        NSLog(@"%@", entryToPrint);
    }
    [array release];
    array = nil;

    NSLog(@"about to drain the pool... (%@)", pool);
    [pool drain];
    NSLog(@"done");
    NSLog(@"GC = %@", [NSGarbageCollector defaultCollector]);
    return 0;
}

The LotteryEntry class looks like this:

@implementation LotteryEntry

- (void)setEntryDate:(NSCalendarDate *)date
{
    entryDate = date;
}

- (NSCalendarDate *)entryDate
{
    return entryDate;
}

- (int)firstNumber
{
    return firstNumber;
}

- (int)secondNumber
{
    return secondNumber;
}

- (id)init
{
    return [self initWithDate:[NSCalendarDate calendarDate]];
}

- (id)initWithDate:(NSCalendarDate *)date
{
    if(![super init])
        return nil;

    NSAssert(date != nil, @"Argument must be non-nil");

    firstNumber = random() % 100 + 1;
    secondNumber = random() % 100 + 1;
    entryDate = [date retain];
    return self;
}

- (NSString *)description
{
    NSString *result;
    result = [[NSString alloc] initWithFormat:@"%@ = %d and %d",
              [entryDate descriptionWithCalendarFormat:@"%b %d %Y"],
              firstNumber,
              secondNumber];
    return result;
}

- (void)dealloc
{
    NSLog(@"deallocating %@", self);
    [entryDate release];
    [super dealloc];
}

@end

As you can see I'm retaining and releasing the objects here.  I'm pretty sure my code matches the book's, however when I run the app, at the [pool drain] I get this message:

Program received signal:
  “EXC_BAD_ACCESS”.

I'm not sure what's causing this.  I'm hoping it's something stupid that I missed, but I'd sure appreciate a few other pairs of eyes on it.  Thanks in advance!

(side note:  I'm a .NET developer, so ref counting is pretty foreign to me!)

Body:
It also looks like you have a bug in this method:

- (id)initWithDate:(NSCalendarDate *)date
{
    if(![super init])
        return nil;

    NSAssert(date != nil, @"Argument must be non-nil");

    firstNumber = random() % 100 + 1;
    secondNumber = random() % 100 + 1;
    entryDate = [date retain];
    return self;
}

You are essentially discarding the results from [super init], while it may not be a problem in this instance, it could cause serious problems in others.  You should 'always' structure you init methods like this:

- (id)initWithDate:(NSCalendarDate *)date
{
    if(self = [super init]) {
        NSAssert(date != nil, @"Argument must be non-nil");

        firstNumber = random() % 100 + 1;
        secondNumber = random() % 100 + 1;
        entryDate = [date retain];
}
return self;

If you are not going to return self from an init method (for instance it is a factory or something odd like that), you should remember to release self.  It has been alloc'ed, and if you don't return it, it cannot be released properly.  Example:

- (id) init
{
    NSObject*    newSelf = [[NSObject alloc] init];

    [self release];
    return newSelf;
}

OwnerDisplayName: Nathan Wertman


问:
Coldfusion Scheduled Tasks - Does the interval reset each time a task runs?
Does anyone know that when a scheduled task in Coldfusion runs it resets the interval timer or does the task run at the set interval time no matter how long that task run for?

For example, i create a task to run every 10 minutes that takes 5 minutes to run starting from 12pm. Will the task run at 12:00, then 12:10, then 12:20 etc etc.

Or would it run at 12:00 which takes 5 minutes, then at 12:15 ten minutes after the task has finished, then another 5 minutes to run so the next one would run at 12:30 etc etc.

Hope that makes sense.

Chris

答:
For example, i create a task to run
  every 10 minutes that takes 5 minutes
  to run starting from 12pm. Will the
  task run at 12:00, then 12:10, then
  12:20 etc etc.

Yes.

The task will always run on the interval. So if you set it every 10 minutes it will run every 10 minutes after the first run.

Note: If the task runs over time (i.e. longer than the interval) than it will NOT queue. That particular run will just be skipped and the task will run at the next interval as per usual.

Hope that helps!


问:
Importing external module in single-file exe created with PyInstaller
I am using PyInstaller to create a single-file executable. Is it possible for my script to perform an import such that i) the imported module is imported from the same directory as the exe (i.e. it's not packaged into the exe) and ii) that imported module can import other modules that were packaged into the exe?

The background here is that the imported module contains configuration that the user should be able to modify. This may include creation of custom derived classes and use of enums from the packaged modules.

I haven't found any advice on this, though it's a difficult search because there are so many similar topics that use basically the same keywords.

答:
Type in Pyinstaller -h.  It will give you info about pyinstaller and tell you about --runtime-hook.  I presume adding this to the executable should work.  There's actually a whole page of documentation for this. Surprised you could not find that.

Anyway,

The docs say put in:
pyinstaller --additional-hooks-dir=. myscript.py.

I presume then something like pyinstaller --additional-hooks-dir=C:\pathtofolder myscript.py should work in theory.  Yet to test it.  Tell us how it goes and what made kinks made it work for you.

Lastly, if you want to be hipster try integrating cython for speed and obfuscation.  Fair warning, cython is not as user friendly as pyinstaller appears to be.  I have yet to use it successfully.


问:
Delete first two characters of elements in a list of lists
Let's say I have the following list of lists:

```<code>final_list = [[1,'pppizza',3,4],[1,'mmmonkey',9,10],[1,'dddoublerainbow',8,2]]
</code>```

Now I need to remove the first 2 characters of the second element of every list, so the result will be:

```<code>final_list = [[1,'pizza',3,4],[1,'monkey',9,10],[1,'doublerainbow',8,2]]
</code>```

答:
```<code>final_list = [[x[2:] if i==1 else x for i, x in enumerate(y)] for y in my_list]
</code>```

Full answer:

```<code>final_list = []
for y in my_list:
    l = []
    for i, x in enumerate(my_list):
    if i==1:  #2nd element in the list
        l.append(x[2:])  # Append a string starting from the 3rd letter to the end
    else:
        l.append(x) . # Just append the element at x
    my_list.append(l)  # Append the list l to my_list
print(my_list)
</code>```

Body:
Let's say I have the following list of lists:

final_list = [[1,'pppizza',3,4],[1,'mmmonkey',9,10],[1,'dddoublerainbow',8,2]]

Now I need to remove the first 2 characters of the second element of every list, so the result will be:

final_list = [[1,'pizza',3,4],[1,'monkey',9,10],[1,'doublerainbow',8,2]]

Body:
final_list = [[x[2:] if i==1 else x for i, x in enumerate(y)] for y in my_list]

Full answer:

final_list = []
for y in my_list:
    l = []
    for i, x in enumerate(my_list):
    if i==1:  #2nd element in the list
        l.append(x[2:])  # Append a string starting from the 3rd letter to the end
    else:
        l.append(x) . # Just append the element at x
    my_list.append(l)  # Append the list l to my_list
print(my_list)


问:
Selecting rows from sql table having multiple values in the field
Here i  have a table 'tbllead' which is having column'leademployees' which contains the values such as

```<code>(450,449,451)- row1
(450,449,451)-row 2
(455,449,454,451)- row3
(450,449,451)-row 4
(450)-row5 )
</code>```

then how to get the rows if my query is

```<code>select *
from TblLead
where LeadEmployees=451
</code>```

The desired result should be...
row 25,26,27,28,29,31,32,33,34,35

答:
You should fix your data model.  Storing lists of numbers as strings SQL is wrong:

Values should have the right data type

Foreign key relationships should be properly defined

SQL has poor string functions

Such queries cannot be optimized very well

Sometimes, you are stuck with someone else's really bad design decisions.  Here is one thing you can use like:

```<code>where ',' + cast(LeadEmployees as varchar(255)) + ',' like '%,' + '451' + ',%'
</code>```

Body:
Here i  have a table 'tbllead' which is having column'leademployees' which contains the values such as

(450,449,451)- row1
(450,449,451)-row 2
(455,449,454,451)- row3
(450,449,451)-row 4
(450)-row5 )

then how to get the rows if my query is

select *
from TblLead
where LeadEmployees=451

The desired result should be...
row 25,26,27,28,29,31,32,33,34,35

Body:
You should fix your data model.  Storing lists of numbers as strings SQL is wrong:

Values should have the right data type

Foreign key relationships should be properly defined

SQL has poor string functions

Such queries cannot be optimized very well

Sometimes, you are stuck with someone else's really bad design decisions.  Here is one thing you can use like:

where ',' + cast(LeadEmployees as varchar(255)) + ',' like '%,' + '451' + ',%'


问:
Angular4 @Input() to pass value from parent component to child component
I have a code in App component.html like this.

```<code> <form>
        <input #box1 (blur)="onKey1(box1.value)" type="text" name="username">
        <p>{{box1.value}}</p>
    </form>
</code>```

In AppComponent.ts I have code like this.

```<code>import { Component } from '@angular/core';
import { OnInit } from '@angular/core/src/metadata/lifecycle_hooks';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent{
    type:string;
    constructor() { }
    onKey1(value:string)
    {
        this.type=value;
    }
}
</code>```

Now I have created a component named MyComponent3. In that component I want to retrieve the data from app component.The code for MyComponent3.html is as follows:

```<code><p>{{type}}</p>
</code>```

In MyComponent3.ts I have the following code.

```<code>import { Component, OnInit, ViewEncapsulation,Input } from '@angular/core';
@Component({
    selector: 'app-my-component3',
    templateUrl: './my-component3.component.html',
    styleUrls: ['./my-component3.component.css'],
    encapsulation: ViewEncapsulation.None
})
export class MyComponent3Component implements OnInit {
    @Input() type;
    ngOnInit() {
    }
}
</code>```

But in the Output the value is not getting passed from AppComponent to My Component3.

答:
Whatever attribute you want to pass to child component should be mentioned in it. You can pass to the child component using @input and the html as follows,</p>

```<code><app-my-component3 [type]="type"></app-my-component3>
</code>```

Body:
I have a code in App component.html like this.

 <form>
        <input #box1 (blur)="onKey1(box1.value)" type="text" name="username">

{{box1.value}}

    </form>

In AppComponent.ts I have code like this.

import { Component } from '@angular/core';
import { OnInit } from '@angular/core/src/metadata/lifecycle_hooks';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent{
    type:string;
    constructor() { }
    onKey1(value:string)
    {
        this.type=value;
    }
}

Now I have created a component named MyComponent3. In that component I want to retrieve the data from app component.The code for MyComponent3.html is as follows:

{{type}}

In MyComponent3.ts I have the following code.

import { Component, OnInit, ViewEncapsulation,Input } from '@angular/core';
@Component({
    selector: 'app-my-component3',
    templateUrl: './my-component3.component.html',
    styleUrls: ['./my-component3.component.css'],
    encapsulation: ViewEncapsulation.None
})
export class MyComponent3Component implements OnInit {
    @Input() type;
    ngOnInit() {
    }
}

But in the Output the value is not getting passed from AppComponent to My Component3.

Body:
Whatever attribute you want to pass to child component should be mentioned in it. You can pass to the child component using @input and the html as follows,

<app-my-component3 [type]="type"></app-my-component3>


问:
pandas locate value from 2 lists and store 3º value
I've 2 lists of items like this:

List 1:

```<code>Type;Color;Weight;
Apples;Red;15gr;
Bananas;Yellow;10gr;
Oranges;Orange;15gr;
</code>```

List 2:

```<code>Type;Color;Price;
Bananas;Yellow;1;
Oranges;Orange;0.85;
Apples;Red;0.50;
</code>```

What i need to acomplish is add to the first list a new column with the price values of the 2 list:

List 1:

```<code>Type;Color;Weight;Price;
Apples;Red;15gr;1;
Bananas;Yellow;10gr;0.85;
Oranges;Orange;15gr;0.50;

#!/usr/bin/python
# -*- coding: utf-8 -*-
import pandas as pd
firstList = 'list1.csv'
secondList = 'list2.csv'

class Fruits:
    def Unify(self):
        List1 = pd.read_csv(firstList,encoding='utf-8',delimiter=';')
        List2 = pd.read_csv(secondList,encoding='utf-8',delimiter=',') # Yes, delimiter it's different
        for row in List1:
            if List1[List1.Type.isin[List2['Type']]] == True:
                List1['Price'] = pd.Series(List2['Price'], index=data.index)
                print List1['Type'], List1['Price']
Test = Fruits()
Test.Unify()
</code>```

But when i run the code it gives me this error:

```<code>TypeError: 'instancemethod' object has no attribute '__getitem__'
</code>```

Any idea how i can fix it ?

Thanks in advance.

答:
Try this:</p>

```<code>joined = List1.merge(List2, how='inner', on=['Type','Color'])[[0,1,2,4]]
</code>```

Body:
I've 2 lists of items like this:

List 1:

Type;Color;Weight;
Apples;Red;15gr;
Bananas;Yellow;10gr;
Oranges;Orange;15gr;

List 2:

Type;Color;Price;
Bananas;Yellow;1;
Oranges;Orange;0.85;
Apples;Red;0.50;

What i need to acomplish is add to the first list a new column with the price values of the 2 list:

List 1:

Type;Color;Weight;Price;
Apples;Red;15gr;1;
Bananas;Yellow;10gr;0.85;
Oranges;Orange;15gr;0.50;

#!/usr/bin/python
# -*- coding: utf-8 -*-
import pandas as pd
firstList = 'list1.csv'
secondList = 'list2.csv'

class Fruits:
    def Unify(self):
        List1 = pd.read_csv(firstList,encoding='utf-8',delimiter=';')
        List2 = pd.read_csv(secondList,encoding='utf-8',delimiter=',') # Yes, delimiter it's different
        for row in List1:
            if List1[List1.Type.isin[List2['Type']]] == True:
                List1['Price'] = pd.Series(List2['Price'], index=data.index)
                print List1['Type'], List1['Price']
Test = Fruits()
Test.Unify()

But when i run the code it gives me this error:

TypeError: 'instancemethod' object has no attribute '__getitem__'

Any idea how i can fix it ?

Thanks in advance.

Body:
Try this:

joined = List1.merge(List2, how='inner', on=['Type','Color'])[[0,1,2,4]]


问:
jquery access plugin as variable
This should be an easy one for you. I made a plugin a while ago and have forgotten how to set the plugin to a variable and then use it. I think my code might help you understand what i'm talking about.

```<code>var $bgcolourpicker1 = $('div.bgcolour1').bpcolourpicker(
    {
        returncolour: bgcolour1,
        cssposition: 'relative'
    });
</code>```

So the control has been established but at any given time I might want to re-set a property like so.

```<code>$('div.bgcolour2').bpcolourpicker({ returncolour: bgcolour1 });
</code>```

That works but i'm sure it can be done by using the variable $bgcolourpicker1 so for instance.

```<code>$bgcolourpicker1.bpcolourpicker({ returncolour: bgcolour1 });
</code>```

Does anyone know if that can be done? I'm sure i've seen it done before.

Thanks

答:
I believe the common design for this case would somewhat look like this:

```<code>var $bgcolourpicker1 = $('div.bgcolour1').bpcolourpicker({
    returncolour: bgcolour1,
    cssposition: 'relative'
});

$bgcolourpicker1.bpcolourpicker('updateSettings', { returncolour: bgcolour2 });
</code>```

You'd then probably save the instance of the plugin using data with the jQuery object (in this case $('div.bgcolour1') and if the first argument is passed into the function is a String rather than an object you'd execute it using the already existing instance.

In your case you might be able to even skip the method and just check if the plugin has already been called on this object:

```<code>$.fn.bpcolourpicker = function(settings) {
    return $(this).each(function(i, e) {
        if ($(e).data('bpcolourpicker'))
            // … use the one you have already
        else
            // … regular plugin execution
    }
};
</code>```

Title: jquery access plugin as variable

Body:
This should be an easy one for you. I made a plugin a while ago and have forgotten how to set the plugin to a variable and then use it. I think my code might help you understand what i'm talking about.

var $bgcolourpicker1 = $('div.bgcolour1').bpcolourpicker(
    {
        returncolour: bgcolour1,
        cssposition: 'relative'
    });

So the control has been established but at any given time I might want to re-set a property like so.

$('div.bgcolour2').bpcolourpicker({ returncolour: bgcolour1 });

That works but i'm sure it can be done by using the variable $bgcolourpicker1 so for instance.

$bgcolourpicker1.bpcolourpicker({ returncolour: bgcolour1 });

Does anyone know if that can be done? I'm sure i've seen it done before.

Thanks

Body:
I believe the common design for this case would somewhat look like this:

var $bgcolourpicker1 = $('div.bgcolour1').bpcolourpicker({
    returncolour: bgcolour1,
    cssposition: 'relative'
});

$bgcolourpicker1.bpcolourpicker('updateSettings', { returncolour: bgcolour2 });

You'd then probably save the instance of the plugin using data with the jQuery object (in this case $('div.bgcolour1') and if the first argument is passed into the function is a String rather than an object you'd execute it using the already existing instance.

In your case you might be able to even skip the method and just check if the plugin has already been called on this object:

$.fn.bpcolourpicker = function(settings) {
    return $(this).each(function(i, e) {
        if ($(e).data('bpcolourpicker'))
            // … use the one you have already
        else
            // … regular plugin execution
    }
};


问:
How to get logs of app from android without using android studio?
I have given App to my friend but its not working.I want to know the issue  so that I want log file of my App.Is there anyway to get logs from android without using android studio or any debugger tool.I want only log file to get solve issue.So What is the way to get log file from android device.
Thanks in advance.</p>

答: Best way is to add Firebase inside your app, With the help of Firebase Crashing Report, you can check all the crashes from your app </p>


问:
Replace every two items in a list for a respective value in a dictionary
I used a program to convert an integer vector to binary, now I need to do the reverse operation, but I believe the logic I am using it's not correct.

```<code>population=[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [6], [0]],
[[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [4], [1]],
[[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [6], [2]],
[[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [4], [3]]]

def BinaryConversion2(population):
    binary_return = []
    binary_index = {(0,0): 0, (0,1): 1, (1,0): 2, (1,1): 3}
    for game in range (0, len(population)):
        converted = [s for num in population[game][0] for s in binary_index[num]]
        binary_return.append(converted)
    return (binary_return)
</code>```

I need to replace every two bits of the binary strings in brackets for the respective dictionary value, but I believe the problem here is that the program is indexing single bits, so it is not working properly.

Does anyone know how to reference every two items in the list for the dictionary respective values? Or anything else that might be useful in this case.

Thank you!

答:
This is a simple solution that works.

```<code>population=[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [6], [0]],
[[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [4], [1]],
[[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [6], [2]],
[[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [4], [3]]]
binary_index = {(0,0): 0, (0,1): 1, (1,0): 2, (1,1): 3}
#zipping
list2 = []
for i in [num[0] for num in population]:
    it = iter(i)
    list2.append(zip(it,it))
converted = [[binary_index[s] for s in num]for num in list2]
</code>```

With this you will get the output in same form as your population list, but I have no idea on what are two single element lists in your each entry, so i just dropped it. You can edit it if you like.

Body:
I used a program to convert an integer vector to binary, now I need to do the reverse operation, but I believe the logic I am using it's not correct.

population=[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [6], [0]],
[[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [4], [1]],
[[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [6], [2]],
[[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [4], [3]]]

def BinaryConversion2(population):
    binary_return = []
    binary_index = {(0,0): 0, (0,1): 1, (1,0): 2, (1,1): 3}
    for game in range (0, len(population)):
        converted = [s for num in population[game][0] for s in binary_index[num]]
        binary_return.append(converted)
    return (binary_return)

I need to replace every two bits of the binary strings in brackets for the respective dictionary value, but I believe the problem here is that the program is indexing single bits, so it is not working properly.

Does anyone know how to reference every two items in the list for the dictionary respective values? Or anything else that might be useful in this case.

Thank you!

Body:
This is a simple solution that works.

population=[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [6], [0]],
[[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [4], [1]],
[[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [6], [2]],
[[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [4], [3]]]
binary_index = {(0,0): 0, (0,1): 1, (1,0): 2, (1,1): 3}
#zipping
list2 = []
for i in [num[0] for num in population]:
    it = iter(i)
    list2.append(zip(it,it))
converted = [[binary_index[s] for s in num]for num in list2]

With this you will get the output in same form as your population list, but I have no idea on what are two single element lists in your each entry, so i just dropped it. You can edit it if you like.


问:
Provide prepared statement in rails
I am using rails-4.2.1 and is trying to fetch data from two tables subjects and elective_subjects table in a single query. As rails 4 does not support UNION , I wrote a raw sql query. I want to search by name in both tables. My code is given below

```<code>query = "(SELECT id as id, name as name, reference as reference from subjects where name like '#{search}') UNION (SELECT id as id, name as name, null as reference from elective_subjects where name like '#{search}')"

@subjects =  ActiveRecord::Base.connection.execute(query)
</code>```

It is working but when I provide ' in my search the query breaks. So how can I make it a prepared statement. So that sql injection can be avoided

答:
I have solved the issue by escaping the search string using following statement.</p>

```<code>search = Mysql2::Client.escape(search)
</code>```

Title: Provide prepared statement in rails

Body:
I am using rails-4.2.1 and is trying to fetch data from two tables subjects and elective_subjects table in a single query. As rails 4 does not support UNION , I wrote a raw sql query. I want to search by name in both tables. My code is given below

query = "(SELECT id as id, name as name, reference as reference from subjects where name like '#{search}') UNION (SELECT id as id, name as name, null as reference from elective_subjects where name like '#{search}')"

@subjects =  ActiveRecord::Base.connection.execute(query)

It is working but when I provide ' in my search the query breaks. So how can I make it a prepared statement. So that sql injection can be avoided

Body:
I have solved the issue by escaping the search string using following statement.

search = Mysql2::Client.escape(search)


答:
You can use Firebase Log events. Please check the link below:
Firebase Log events</p>

Title: How to get logs of app from android without using android studio?

Body:
I have given App to my friend but its not working.I want to know the issue  so that I want log file of my App.Is there anyway to get logs from android without using android studio or any debugger tool.I want only log file to get solve issue.So What is the way to get log file from android device.
Thanks in advance.


问:
PHPCS exit code based on threshold
Im trying to implement PHPCS in my project which has an huge technical depth. I have for example one module with 378 sniffs (both errors and warnings combined). However the fact is that i also have like 29 modules which makes it nearly impossible to finish this technical depth in a short period of time.

What i want is to keep it at least stable so that one of the teams can keep developing where the other can clean up some mess on the spot. The question is how can i enable PHPCS scans but for example let if only fail when it hits more than 378 hits in this case on that module. This way i can ensure that my depth stays the same and a long the way i can ensure that it will be lowered.

As far as i can see the only way with PHPCS itself is to set the severity levels and let it break on there but i'd rather stay as close as possible to the default coding standards and keep it as strict as possible.

Thanks a lot

Pim

答:
I build an own script like Greg above also mentioned that checks the outcome of the --report=summary via a regex. The regex outcome then determines the exit code 0 or 1 from there.

Would be helpfull if PHPCS could do something like that itself but its not there

Title: PHPCS exit code based on threshold


问:
Posting a message to a web worker while it is still running
Say we have a web worker referring to a file called "worker.js". We use the worker to execute a function in "worker.js" that does some lengthy operation. We call post the respective message to the worker and proceed in the main thread. However, before the worker has finished doing its initial work, the main thread posts another message to it.

My question: Will the worker continue with our time-taking function and only process the newly posted message once finished or will it interrupt its current operation until the new one has been completed?

答:
A Web Worker is backed by a single thread. This means that while the "onmessage" handler is being executed, it will not be able to receive another "onmessage" event until the previous one has finished.

This is quite inconvenient if we want to implement some background computation process that we want to be able to pause and resume, because there is no way to send a "pause" message to a running worker. We are able to stop a web worker via worker.terminate(), but that completely kills the worker.

The only way I can think of is by slicing worker execution into chunks, then post a message from the worker at the end of each chunk, which then triggers a message to the worker to process the next chunk, and so on.


问:
Unable to merge dex after Android Studio Upgrade to 3.0
Did anyone manage to solve  this

Error:Execution failed for task
  ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
  com.android.builder.dexing.DexArchiveMergerException: Unable to merge
  dex

答:
I had same issue, it worked out for me

Clean
 &

Rebuild


问:
Calculate difference between two non-adjacent rows
How can I calculate time difference between two rows in a table, based on a value in another field in the table.
Table (simplified) look like;

```<code>Unit  Date              Status
0001  17.11.2017 09:52  INSPECTED
0001  17.11.2017 09:48  CLEAN
0001  17.11.2017 09:45  CLEANING
0001  17.11.2017 09:43  DIRTY
0001  16.11.2017 14:55  INSPECTED
0001  16.11.2017 14:54  CLEAN
0001  16.11.2017 12:54  CLEANING
0001  16.11.2017 12:22  DIRTY
0001  16.11.2017 12:20  CLEAN
0001  15.11.2017 10:48  CLEAN
0001  15.11.2017 10:27  CLEANING
0001  15.11.2017 09:03  DIRTY
</code>```

Date field is of type DATE, Unit and Status values are from parent tables.

Based on a column Status, I have to calculate difference between status DIRTY and next status CLEAN, for each day and each unit. Example data should produce;

```<code>0001  17.11.2017  00:05
0001  16.11.2017  02:32
0001  15.11.2017  01:45
</code>```

The query is the source for the chart in Oracle APEX.

答:
You do not need a self join - you can use the LEAD analytic function:

```<code>SELECT unit,
       "Date",
       NUMTODSINTERVAL( Clean_date - "Date" =, 'DAY' ) AS difference
FROM   (
  SELECT t.*,
         LEAD( CASE status WHEN 'CLEAN' THEN "Date" END )
           IGNORE NULLS
           OVER ( PARTITION BY unit --, TRUNC( "Date" )
                  ORDER BY "Date" ASC ) AS Clean_date
  FROM   your_table t
)
WHERE status = 'DIRTY';
</code>```

Body:
How can I calculate time difference between two rows in a table, based on a value in another field in the table.
Table (simplified) look like;

Unit  Date              Status
0001  17.11.2017 09:52  INSPECTED
0001  17.11.2017 09:48  CLEAN
0001  17.11.2017 09:45  CLEANING
0001  17.11.2017 09:43  DIRTY
0001  16.11.2017 14:55  INSPECTED
0001  16.11.2017 14:54  CLEAN
0001  16.11.2017 12:54  CLEANING
0001  16.11.2017 12:22  DIRTY
0001  16.11.2017 12:20  CLEAN
0001  15.11.2017 10:48  CLEAN
0001  15.11.2017 10:27  CLEANING
0001  15.11.2017 09:03  DIRTY

Date field is of type DATE, Unit and Status values are from parent tables.

Based on a column Status, I have to calculate difference between status DIRTY and next status CLEAN, for each day and each unit. Example data should produce;

0001  17.11.2017  00:05
0001  16.11.2017  02:32
0001  15.11.2017  01:45

The query is the source for the chart in Oracle APEX.

Body:
You do not need a self join - you can use the LEAD analytic function:

SELECT unit,
       "Date",
       NUMTODSINTERVAL( Clean_date - "Date" =, 'DAY' ) AS difference
FROM   (
  SELECT t.*,
         LEAD( CASE status WHEN 'CLEAN' THEN "Date" END )
           IGNORE NULLS
           OVER ( PARTITION BY unit --, TRUNC( "Date" )
                  ORDER BY "Date" ASC ) AS Clean_date
  FROM   your_table t
)
WHERE status = 'DIRTY';


问:
Simple MySQL Two Table Query
I have two tables

```<code>1st table :-

id name dept
1  John dept1
2  Mary dept2
3  Dave dept3
4  John dept4
5  John dept5

2nd table :-

id submitter dept
1  Rupert    dept3
2  Joe       dept1
3  Lisa      dept2
4  Louise    dept4
5  Tom       dept5
</code>```

what i would like is a query to allow people in the name column in the first table to only show records based on their matching departments eg John in table one will return the 3 records in table 2 (id 2,4 and 5)

So far i have tried SELECT * FROM table1, table2 WHERE table1.dept = table2.dept AND table1.name='John'

答:
If I correctly understand your problem, you need to make a join between the two tables using the field dept and filter your results by the name of the requester, in the first table.

```<code>SELECT t2.submitter, t2.dept
FROM table1 t1
LEFT JOIN table2 t2 ON t1.dept = t2.dept
WHERE t1.name = :person_name
</code>```

Documentation and examples (you can also look at the left menu at Inner, right, full and self join's).

Title: Simple MySQL Two Table Query

Body:
I have two tables

1st table :-

id name dept
1  John dept1
2  Mary dept2
3  Dave dept3
4  John dept4
5  John dept5

2nd table :-

id submitter dept
1  Rupert    dept3
2  Joe       dept1
3  Lisa      dept2
4  Louise    dept4
5  Tom       dept5

what i would like is a query to allow people in the name column in the first table to only show records based on their matching departments eg John in table one will return the 3 records in table 2 (id 2,4 and 5)

So far i have tried SELECT * FROM table1, table2 WHERE table1.dept = table2.dept AND table1.name='John'

Body:
If I correctly understand your problem, you need to make a join between the two tables using the field dept and filter your results by the name of the requester, in the first table.

SELECT t2.submitter, t2.dept
FROM table1 t1
LEFT JOIN table2 t2 ON t1.dept = t2.dept
WHERE t1.name = :person_name

Documentation and examples (you can also look at the left menu at Inner, right, full and self join's).


问:
Bring activity front if it is running or create new one with backpress

Let me explain detailed; I have notification and this notification opens B activity with two cases.

Cases :

If app is closed. (not running on background)

If app is opened. (on background or front)

Case-1

I click to the notification and it opens the B activity with case-1. When i press back i want to go to the A activity and kill B activity. I dont need B activity anymore. Everything easy from here without using flags. When I'm on B activity and press back two times from here, it goes A activity and then closes the app. My trouble here is, if i open the app from navigation buttons of phone (can't remember the name of this button) app is opening from B activity. That's not what i expected. I want to open A activity. Don't want to see B activity anymore.

Case-2

I click to the notification and it opens the B activity with case-2.When i press back i want to bring A activity to the front, without creating anything new. If i press back on B activity, two times and close the app and then again re-open app from navigation button of phone, want to open app from A activity.

So how can i make this correctly, i tried to use flags (i already read docs) but couldn't get work.
What flags should i use when i open the B activity and onBackPress method of B activity to go A activity as i wanted

答:
You can achive this by adding FLAG_ACTIVITY_REORDER_TO_FRONT</p>

```<code>    Intent i = new Intent(context, Activity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(i);
</code>```

Body:
You can achive this by adding FLAG_ACTIVITY_REORDER_TO_FRONT

    Intent i = new Intent(context, Activity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(i);


问:
Destroy PHP Session on closing
I have created a simple login page which is based on the sessions.

```<code>session_start();
</code>```

and added a logout page that contains this

```<code>session_destroy();
</code>```

Now when I close the browser/page and reopen it, the values of the session are still there.

I want to know how to completely destroy the session on page/browser close.

答:
If the session exists, log out by destroying the session and redirecting the user to the home page. A temporary cookie was used to store the session identity. This cookie is also destroyed.</p>

```<code><?php
    // This is the logout page for the site.
    session_start();//access the current session.
    //if no session variable then redirect the user
    if (!isset($_SESSION['user_id'])) {
    header("location:index.php");
    exit();
    }else{ //cancel the session
        $_SESSION = array(); // Destroy the variables
        session_destroy(); // Destroy the session
        setcookie('PHPSESSID', ", time()-3600,'/', ", 0, 0);//Destroy the cookie
        header("location:index.php");
        exit();
    }
    ?>
</code>```

Title: Destroy PHP Session on closing

Body:
I have created a simple login page which is based on the sessions.

session_start();

and added a logout page that contains this

session_destroy();

Now when I close the browser/page and reopen it, the values of the session are still there.

I want to know how to completely destroy the session on page/browser close.

Body:
If the session exists, log out by destroying the session and redirecting the user to the home page. A temporary cookie was used to store the session identity. This cookie is also destroyed.

<?php
    // This is the logout page for the site.
    session_start();//access the current session.
    //if no session variable then redirect the user
    if (!isset($_SESSION['user_id'])) {
    header("location:index.php");
    exit();
    }else{ //cancel the session
        $_SESSION = array(); // Destroy the variables
        session_destroy(); // Destroy the session
        setcookie('PHPSESSID', ", time()-3600,'/', ", 0, 0);//Destroy the cookie
        header("location:index.php");
        exit();
    }
    ?>


问:
OmniAuth & openid: getting certain fields from openid provider
I'm using the rails gem: OmniAuth to login users.

When using an OpenId provider I would like to get certain field, like email and nickname but I don't see any documentation on this.

Any ideas?

thanks

答: request.env['omniauth.auth'] will contain the entire response from the callback. But not all providers return the user email(twitter won't). OpenID via google or yahoo should have email as part of 'user_info' hash.</p>


问:
How do you import a CSV line-by-line in Netlogo?
How do I import data from a CSV file and convert it line-by-line so I can use it in my program? I want it to be a string but I keep getting error messages that it is still a list or a list of lists.

I am trying to copy the example given in the Netlogo User Manual for reading a file one line per tick (see below). I created a simple example.

```<code>extensions [CSV]
globals [date]

to setup
  clear-all
  file-close-all
  file-open "S&PDate.csv"
  set date current-date
  reset-ticks
end

to go
   if file-at-end? [stop]
   set date current-date
   tick
end

to-report current-date
   file-open "S&PDate.csv"
   let result csv:from-row file-read-line
   while [ not file-at-end? ] [
   let row csv:from-row file-read-line
   set result (map result row)
     ]
   file-close
   report result
end
</code>```

From NetLogo User Manual

答:
My idea is to import the CSV data all at once as a list, then extract the value from the list by the number of ticks (i.e. line-by-line).

```<code>extensions [csv]
globals [data variable]

to setup
file-close-all
file-open "S&PDate.csv"
;; read the data all at once by using csv:from-file
set data csv:from-file "S&PDate.csv"
reset-ticks
end

to go
if file-at-end? [stop]
;;extract value from the list, using item 0 to remove the list, and just keep the value
set variable item 0 item ticks data
tick
if ticks = length data [stop]
show variable
end
</code>```

Hope it helps. Please let me know if you need further clarification.

Body:
How do I import data from a CSV file and convert it line-by-line so I can use it in my program? I want it to be a string but I keep getting error messages that it is still a list or a list of lists.

I am trying to copy the example given in the Netlogo User Manual for reading a file one line per tick (see below). I created a simple example.

extensions [CSV]
globals [date]

to setup
  clear-all
  file-close-all
  file-open "S&PDate.csv"
  set date current-date
  reset-ticks
end

to go
   if file-at-end? [stop]
   set date current-date
   tick
end

to-report current-date
   file-open "S&PDate.csv"
   let result csv:from-row file-read-line
   while [ not file-at-end? ] [
   let row csv:from-row file-read-line
   set result (map result row)
     ]
   file-close
   report result
end

From NetLogo User Manual

Body:
My idea is to import the CSV data all at once as a list, then extract the value from the list by the number of ticks (i.e. line-by-line).

extensions [csv]
globals [data variable]

to setup
file-close-all
file-open "S&PDate.csv"
;; read the data all at once by using csv:from-file
set data csv:from-file "S&PDate.csv"
reset-ticks
end

to go
if file-at-end? [stop]
;;extract value from the list, using item 0 to remove the list, and just keep the value
set variable item 0 item ticks data
tick
if ticks = length data [stop]
show variable
end

Hope it helps. Please let me know if you need further clarification.


问:
Unable to open content: Custom Content Provider
I have two app, from another app I want to get all images,
suppose there is StickerProvider and MainActivity different app

StickerProvider is ContentProvider, MainActivity has ContentResolver

StickerProvider App has Asset Folder

Asset----> Stickers  ----------> a.png, b.png

```<code>public class StickerProvider extends ContentProvider {

    private final static String LOG_TAG = StickerProvider.class.getName();

    private static final String[] COLUMNS = {
            OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE};

    @Override
    public boolean onCreate() {
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        /**
         * Source: {@link FileProvider#query(Uri, String[], String, String[], String)} .
         */
        if (projection == null) {
            projection = COLUMNS;
        }

        String[] images = new String[0];
        try {
            images = getContext().getAssets().list("stickers");

            ArrayList<String> listImages = new ArrayList<String>(Arrays.asList(images));

            final MatrixCursor cursor = new MatrixCursor(new String[]{"path"}, 1);
            for (int i = 0; i < listImages.size(); i++) {
                cursor.addRow(new String[]{listImages.get(i)});
            }

            return cursor;

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

    @Override
    public String getType(Uri uri) {
        /**
         * Source: {@link FileProvider#getType(Uri)} .
         */
        final String file_name = uri.getLastPathSegment();
        final int lastDot = file_name.lastIndexOf('.');
        if (lastDot >= 0) {
            final String extension = file_name.substring(lastDot + 1);
            final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            if (mime != null) {
                return mime;
            }
        }

        return "image/png";
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        return 0;
    }

}
</code>```

It's menifest file is

```<code> <provider
            android:name="com.example.StickerProvider"
            android:authorities="com.example"
            android:exported="true"
            android:grantUriPermissions="true"
            android:label="StickerProvider" />
</code>```

Another app is MainActivity ------> From this I want to fetch all images of above apps

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

    int i=0;
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView ivOne = (ImageView)findViewById(R.id.ivOne);
        ImageView ivTwo = (ImageView)findViewById(R.id.ivTwo);

        try {
            ContentResolver resolver = getContentResolver();

            Cursor cursor =
                    resolver.query(Uri.parse("content://com.example/stickers"),
                            null,
                            null,
                            null,
                            null);
            if (cursor.moveToFirst()) {
                do {
                    String word = cursor.getString(0);
                    if(i==0){
                        ivOne.setImageURI(Uri.parse("content://com.example/stickers/"+word));
                    }else if(i==1){
                        ivTwo.setImageURI(Uri.parse("content://com.example/stickers/"+word));
                    }
                    // do something meaningful
                    Log.d(TAG, "onCreate: "+word);
                } while (cursor.moveToNext());
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
</code>```

When ever I start MainActivity App I am getting below exception

```<code>Unable to open content: content://com.example/a.png
             java.io.FileNotFoundException: No files supported by provider at content://com.example/a.png
                 at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:144)
                 at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:692)
                 at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1149)
                 at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:986)
                 at android.content.ContentResolver.openInputStream(ContentResolver.java:706)
                 at android.widget.ImageView.getDrawableFromUri(ImageView.java:900)
                 at android.widget.ImageView.resolveUri(ImageView.java:871)
                 at android.widget.ImageView.setImageURI(ImageView.java:490)
                 at android.support.v7.widget.AppCompatImageView.setImageURI(AppCompatImageView.java:124)
                 at com.pixr.photo.collage.MainActivity.onCreate(MainActivity.java:36)
                 at android.app.Activity.performCreate(Activity.java:6684)
                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2652)
                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2766)
                 at android.app.ActivityThread.-wrap12(ActivityThread.java)
                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1507)
                 at android.os.Handler.dispatchMessage(Handler.java:102)
                 at android.os.Looper.loop(Looper.java:154)
                 at android.app.ActivityThread.main(ActivityThread.java:6236)
                 at java.lang.reflect.Method.invoke(Native Method)
                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)
</code>```

答:
```<code>ivOne.setImageURI(Uri.parse("content://com.example/stickers/"+word));
</code>```

Your ContentProvider does not support this. It does not implement openFile() or any of its variants.

Either:

Use an existing ContentProvider that offers support for serving assets, such as my StreamProvider, or

Augment your provider to support openFile(), such as I do in this sample app

Body:
I have two app, from another app I want to get all images,
suppose there is StickerProvider and MainActivity different app

StickerProvider is ContentProvider, MainActivity has ContentResolver

StickerProvider App has Asset Folder

Asset----> Stickers  ----------> a.png, b.png

public class StickerProvider extends ContentProvider {

    private final static String LOG_TAG = StickerProvider.class.getName();

    private static final String[] COLUMNS = {
            OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE};

    @Override
    public boolean onCreate() {
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        /**
         * Source: {@link FileProvider#query(Uri, String[], String, String[], String)} .
         */
        if (projection == null) {
            projection = COLUMNS;
        }

        String[] images = new String[0];
        try {
            images = getContext().getAssets().list("stickers");

            ArrayList<String> listImages = new ArrayList<String>(Arrays.asList(images));

            final MatrixCursor cursor = new MatrixCursor(new String[]{"path"}, 1);
            for (int i = 0; i < listImages.size(); i++) {
                cursor.addRow(new String[]{listImages.get(i)});
            }

            return cursor;

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

    @Override
    public String getType(Uri uri) {
        /**
         * Source: {@link FileProvider#getType(Uri)} .
         */
        final String file_name = uri.getLastPathSegment();
        final int lastDot = file_name.lastIndexOf('.');
        if (lastDot >= 0) {
            final String extension = file_name.substring(lastDot + 1);
            final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            if (mime != null) {
                return mime;
            }
        }

        return "image/png";
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        return 0;
    }

}

It's menifest file is

 <provider
            android:name="com.example.StickerProvider"
            android:authorities="com.example"
            android:exported="true"
            android:grantUriPermissions="true"
            android:label="StickerProvider" />

Another app is MainActivity ------> From this I want to fetch all images of above apps

public class MainActivity extends AppCompatActivity {

    int i=0;
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView ivOne = (ImageView)findViewById(R.id.ivOne);
        ImageView ivTwo = (ImageView)findViewById(R.id.ivTwo);

        try {
            ContentResolver resolver = getContentResolver();

            Cursor cursor =
                    resolver.query(Uri.parse("content://com.example/stickers"),
                            null,
                            null,
                            null,
                            null);
            if (cursor.moveToFirst()) {
                do {
                    String word = cursor.getString(0);
                    if(i==0){
                        ivOne.setImageURI(Uri.parse("content://com.example/stickers/"+word));
                    }else if(i==1){
                        ivTwo.setImageURI(Uri.parse("content://com.example/stickers/"+word));
                    }
                    // do something meaningful
                    Log.d(TAG, "onCreate: "+word);
                } while (cursor.moveToNext());
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

When ever I start MainActivity App I am getting below exception

Unable to open content: content://com.example/a.png
             java.io.FileNotFoundException: No files supported by provider at content://com.example/a.png
                 at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:144)
                 at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:692)
                 at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1149)
                 at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:986)
                 at android.content.ContentResolver.openInputStream(ContentResolver.java:706)
                 at android.widget.ImageView.getDrawableFromUri(ImageView.java:900)
                 at android.widget.ImageView.resolveUri(ImageView.java:871)
                 at android.widget.ImageView.setImageURI(ImageView.java:490)
                 at android.support.v7.widget.AppCompatImageView.setImageURI(AppCompatImageView.java:124)
                 at com.pixr.photo.collage.MainActivity.onCreate(MainActivity.java:36)
                 at android.app.Activity.performCreate(Activity.java:6684)
                 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2652)
                 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2766)
                 at android.app.ActivityThread.-wrap12(ActivityThread.java)
                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1507)
                 at android.os.Handler.dispatchMessage(Handler.java:102)
                 at android.os.Looper.loop(Looper.java:154)
                 at android.app.ActivityThread.main(ActivityThread.java:6236)
                 at java.lang.reflect.Method.invoke(Native Method)
                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)

Body:
ivOne.setImageURI(Uri.parse("content://com.example/stickers/"+word));

Your ContentProvider does not support this. It does not implement openFile() or any of its variants.

Either:

Use an existing ContentProvider that offers support for serving assets, such as my StreamProvider, or

Augment your provider to support openFile(), such as I do in this sample app


问:
how to pass values jsp page into java using spring mvc?
I am using spring mvc with hibernate database connction,now how to pass values in jsp page into java page  without call controller ,i am getting Error how to pass values jsp to java??

Jsp page

In this page i am using java code but unable to pass values in another java page

```<code><%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@page import="com.sample.utility.AutoIncrement" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>check page</title>
</head>
<body>

       <div id="login_form">
   <form:form action="check" method="post">
        <table>

            <tr>
             <%String val=AutoIncrement.auto("ShopInfo"); System.out.println(" val : "+val);%>
                <td class="f1_label">Shop code :</td>
                <td>
                <input type="text" name="shopcode" value="<%=val%>" />

                </td>
            </tr>
            <tr>
                <td class="f1_label">name  :</td><td><input type="text" name="name" value=""  />
                </td>
            </tr>
            <tr>
                <td>
                    <input type="submit" name="login" value="Submit" style="font-size:18px; " />
                </td>
            </tr>
        </table>
    </form:form>
</div>

</body>
</html>
</code>```

Java Page :

This below code is java here unable to return values in jsp page

```<code> public static String auto(String value)
        {
            String reVal="";
            System.out.println("Inc val : "+value);
            Session session = sessionFactory.openSession();
            try
            {
                session.beginTransaction().begin();
                String SQL_QUERY = "{CALL pro_autoincrement('"+value+"') }";
                query = session.createSQLQuery(SQL_QUERY);
                reVal=query.toString();
                System.out.println("Inc val : "+reVal);
                session.getTransaction().commit();
           }
            catch(Exception ex)
            {
            if ( session.getTransaction().getStatus() == TransactionStatus.ACTIVE
                    || session.getTransaction().getStatus() == TransactionStatus.MARKED_ROLLBACK ) {
                session.getTransaction().rollback();
            }
            }
            finally
            {
                session.close();
            }
            return reVal;
        }
</code>```

Error:

```<code>SEVERE: Servlet.service() for servlet [jsp] in context with path [/annotation-based] threw exception [An exception occurred processing JSP page /welcome.jsp at line 18

15:         <table>
16:
17:             <tr>
18:              <%String val=AutoIncrement.auto("ShopInfo"); System.out.println(" val : "+val);%>
19:                 <td class="f1_label">Shop code :</td>
20:                 <td>
21:                 <input type="text" name="shopcode" value="<%=val%>" />

Stacktrace:] with root cause
java.lang.NullPointerException
    at com.sample.utility.AutoIncrement.auto(AutoIncrement.java:26)
    at org.apache.jsp.welcome_jsp._jspService(welcome_jsp.java:81)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
</code>```

答:
Insted of this.
reVal=query.toString();

you can do like this

reVal=(String)session.createQuery(queryString).UniqueResult();

Above Method Return Object.So we need to type Cast into String Format.

Body:
I am using spring mvc with hibernate database connction,now how to pass values in jsp page into java page  without call controller ,i am getting Error how to pass values jsp to java??

Jsp page

In this page i am using java code but unable to pass values in another java page

<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@page import="com.sample.utility.AutoIncrement" %>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>check page</title>

   <form:form action="check" method="post">

             <%String val=AutoIncrement.auto("ShopInfo"); System.out.println(" val : "+val);%>
                Shop code :

                <input type="text" name="shopcode" value="<%=val%>" />

                name  :	<input type="text" name="name" value=""  />

                    <input type="submit" name="login" value="Submit" style="font-size:18px; " />

    </form:form>

Java Page :

This below code is java here unable to return values in jsp page

 public static String auto(String value)
        {
            String reVal="";
            System.out.println("Inc val : "+value);
            Session session = sessionFactory.openSession();
            try
            {
                session.beginTransaction().begin();
                String SQL_QUERY = "{CALL pro_autoincrement('"+value+"') }";
                query = session.createSQLQuery(SQL_QUERY);
                reVal=query.toString();
                System.out.println("Inc val : "+reVal);
                session.getTransaction().commit();
           }
            catch(Exception ex)
            {
            if ( session.getTransaction().getStatus() == TransactionStatus.ACTIVE
                    || session.getTransaction().getStatus() == TransactionStatus.MARKED_ROLLBACK ) {
                session.getTransaction().rollback();
            }
            }
            finally
            {
                session.close();
            }
            return reVal;
        }

Error:

SEVERE: Servlet.service() for servlet [jsp] in context with path [/annotation-based] threw exception [An exception occurred processing JSP page /welcome.jsp at line 18

15:

16:
17:

18:              <%String val=AutoIncrement.auto("ShopInfo"); System.out.println(" val : "+val);%>
19:                 Shop code :
20:
21:                 <input type="text" name="shopcode" value="<%=val%>" />

Stacktrace:] with root cause
java.lang.NullPointerException
    at com.sample.utility.AutoIncrement.auto(AutoIncrement.java:26)
    at org.apache.jsp.welcome_jsp._jspService(welcome_jsp.java:81)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)


问:
Change item in ViewPager on alarm
I'm trying to make an app that resets every midnight to a default view.

So, I set up an alarm in my MainActivity, and an AlarmReceiver that extends BroadcastReceiver

This is the AlarmReceiver class:

```<code>public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Will be executed when Alarm is fired
        Toast.makeText(context, "HELLO TEST", Toast.LENGTH_SHORT).show();
    }
}
</code>```

And this is my MainActivity

```<code>// VerticalViewPager & adapter
VerticalViewPager verticalViewPager = (VerticalViewPager) findViewById(R.id.verticalViewPager);
adapterViewPager = new CustomPagerAdapter(getSupportFragmentManager());
verticalViewPager.setAdapter(adapterViewPager);
</code>```

In this example, the alarm fires off everyday at midnight, and write the toast message. What I want instead is that the alarm changes the current item displayed in ViewPager:

```<code>// Will set the view I want
verticalViewPager.setCurrentItem(3);
</code>```

But of course, I can't write this under the onReceive method because it doesn't know what verticalViewPager is. I'm new to OOP as well.

答:
There are plenty of ways to link AlarmReceiver with those components which are actually able to fully control verticalViewPager.
E.g EventBus(little bit old), RXjava(Publish subject) , etc.

And if app does not always run in foreground at midnight, it's more like you need to deep link to the target page(MainActivity?), and then get the Viewpager updated.

Title: Change item in ViewPager on alarm

Body:
I'm trying to make an app that resets every midnight to a default view.

So, I set up an alarm in my MainActivity, and an AlarmReceiver that extends BroadcastReceiver

This is the AlarmReceiver class:

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Will be executed when Alarm is fired
        Toast.makeText(context, "HELLO TEST", Toast.LENGTH_SHORT).show();
    }
}

And this is my MainActivity

// VerticalViewPager & adapter
VerticalViewPager verticalViewPager = (VerticalViewPager) findViewById(R.id.verticalViewPager);
adapterViewPager = new CustomPagerAdapter(getSupportFragmentManager());
verticalViewPager.setAdapter(adapterViewPager);

In this example, the alarm fires off everyday at midnight, and write the toast message. What I want instead is that the alarm changes the current item displayed in ViewPager:

// Will set the view I want
verticalViewPager.setCurrentItem(3);

But of course, I can't write this under the onReceive method because it doesn't know what verticalViewPager is. I'm new to OOP as well.