问:
Can't use local annotation processor in Android kotlin project
I have an AS3 / gradle plugin 3 project where we recently introduced a local simple annotation processor. Works fine with gradles annotationProcessor dependancy directive.

I started adding Kotlin code and moved all annotationProcessor directives to kapt ones. Glide and logan-square use annotation processors with Kotlin without a problem, but our local AP project can't be executed by kapt:

```<code>:app:kaptGenerateStubsDebugKotlin
Using Kotlin incremental compilation

e: java.util.ServiceConfigurationError: javax.annotation.processing.Processor: Error reading configuration file
    at java.util.ServiceLoader.fail(ServiceLoader.java:232)
    at java.util.ServiceLoader.parse(ServiceLoader.java:309)
    at java.util.ServiceLoader.access$200(ServiceLoader.java:185)
    at java.util.ServiceLoader$LazyIterator.hasNextService(ServiceLoader.java:357)
    at java.util.ServiceLoader$LazyIterator.hasNext(ServiceLoader.java:393)
    at java.util.ServiceLoader$1.hasNext(ServiceLoader.java:474)
    at kotlin.collections.CollectionsKt___CollectionsKt.toCollection(_Collections.kt:1042)
    at kotlin.collections.CollectionsKt___CollectionsKt.toMutableList(_Collections.kt:1075)
    at kotlin.collections.CollectionsKt___CollectionsKt.toList(_Collections.kt:1066)
    at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.loadProcessors(Kapt3Extension.kt:92)
    at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:160)
    at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:82)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:96)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:106)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:83)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:377)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:68)
    at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:96)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:368)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:133)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:154)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:58)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:103)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:51)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:92)
    at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:303)
    at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:85)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileIncrementally(IncrementalCompilerRunner.kt:213)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.access$compileIncrementally(IncrementalCompilerRunner.kt:37)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner$compile$2.invoke(IncrementalCompilerRunner.kt:74)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compile(IncrementalCompilerRunner.kt:87)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.execIncrementalCompiler(CompileServiceImpl.kt:512)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.access$execIncrementalCompiler(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:399)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:889)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:916)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:888)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:398)
    at sun.reflect.GeneratedMethodAccessor87.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: JAR entry META-INF/services/javax.annotation.processing.Processor not found in /Users/kread/git/bgo/myrmecophaga-2.0/ejecta-v8/v8annotations-compiler/build/libs/v8annotations-compiler.jar
    at sun.net.www.protocol.jar.JarURLConnection.connect(JarURLConnection.java:144)
    at sun.net.www.protocol.jar.JarURLConnection.getInputStream(JarURLConnection.java:152)
    at java.net.URL.openStream(URL.java:1045)
    at java.util.ServiceLoader.parse(ServiceLoader.java:304)
    ... 55 more

:app:kaptGenerateStubsDebugKotlin FAILED
</code>```

The created JAR file has the necessary META-INF JAR entry though:

```<code># jar tf /Users/kread/git/bgo/myrmecophaga-2.0/ejecta-v8/v8annotations-compiler/build/libs/v8annotations-compiler.jar
META-INF/
META-INF/MANIFEST.MF
ag/
ag/boersego/
ag/boersego/v8annotations/
ag/boersego/v8annotations/compiler/
ag/boersego/v8annotations/compiler/V8AnnotationProcessor$1.class
ag/boersego/v8annotations/compiler/V8AnnotationProcessor$AccessorTuple.class
ag/boersego/v8annotations/compiler/V8AnnotationProcessor$AnnotationHolder.class
ag/boersego/v8annotations/compiler/V8AnnotationProcessor.class
META-INF/services/
META-INF/services/javax.annotation.processing.Processor
</code>```

Excerpt from main module build.gradle:

```<code>dependencies {
    // gazillions of compile / api / ...
    api project(':ejecta-v8:v8annotations')
    kapt project(':ejecta-v8:v8annotations-compiler')
}
</code>```

Module v8annotations build.gradle:

```<code>apply plugin: 'java-library'

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {}
</code>```

Module v8annotations-compiler build.gradle:

```<code>apply plugin: 'java'

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile project(':ejecta-v8:v8annotations')
    compile fileTree(dir: 'libs', include: ['*.jar'])
}
</code>```

I'm stumped :(

答:
In my case it was enough to run

```<code>gradlew --stop
</code>```

from AndroidStudio console

Body:
I have an AS3 / gradle plugin 3 project where we recently introduced a local simple annotation processor. Works fine with gradles annotationProcessor dependancy directive.

I started adding Kotlin code and moved all annotationProcessor directives to kapt ones. Glide and logan-square use annotation processors with Kotlin without a problem, but our local AP project can't be executed by kapt:

:app:kaptGenerateStubsDebugKotlin
Using Kotlin incremental compilation

e: java.util.ServiceConfigurationError: javax.annotation.processing.Processor: Error reading configuration file
    at java.util.ServiceLoader.fail(ServiceLoader.java:232)
    at java.util.ServiceLoader.parse(ServiceLoader.java:309)
    at java.util.ServiceLoader.access$200(ServiceLoader.java:185)
    at java.util.ServiceLoader$LazyIterator.hasNextService(ServiceLoader.java:357)
    at java.util.ServiceLoader$LazyIterator.hasNext(ServiceLoader.java:393)
    at java.util.ServiceLoader$1.hasNext(ServiceLoader.java:474)
    at kotlin.collections.CollectionsKt___CollectionsKt.toCollection(_Collections.kt:1042)
    at kotlin.collections.CollectionsKt___CollectionsKt.toMutableList(_Collections.kt:1075)
    at kotlin.collections.CollectionsKt___CollectionsKt.toList(_Collections.kt:1066)
    at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.loadProcessors(Kapt3Extension.kt:92)
    at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:160)
    at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:82)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:96)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:106)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:83)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:377)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:68)
    at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:96)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:368)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:133)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:154)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:58)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:103)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:51)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:92)
    at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:303)
    at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:85)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileIncrementally(IncrementalCompilerRunner.kt:213)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.access$compileIncrementally(IncrementalCompilerRunner.kt:37)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner$compile$2.invoke(IncrementalCompilerRunner.kt:74)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compile(IncrementalCompilerRunner.kt:87)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.execIncrementalCompiler(CompileServiceImpl.kt:512)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.access$execIncrementalCompiler(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:399)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:889)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:916)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:888)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:398)
    at sun.reflect.GeneratedMethodAccessor87.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: JAR entry META-INF/services/javax.annotation.processing.Processor not found in /Users/kread/git/bgo/myrmecophaga-2.0/ejecta-v8/v8annotations-compiler/build/libs/v8annotations-compiler.jar
    at sun.net.www.protocol.jar.JarURLConnection.connect(JarURLConnection.java:144)
    at sun.net.www.protocol.jar.JarURLConnection.getInputStream(JarURLConnection.java:152)
    at java.net.URL.openStream(URL.java:1045)
    at java.util.ServiceLoader.parse(ServiceLoader.java:304)
    ... 55 more

:app:kaptGenerateStubsDebugKotlin FAILED

The created JAR file has the necessary META-INF JAR entry though:

# jar tf /Users/kread/git/bgo/myrmecophaga-2.0/ejecta-v8/v8annotations-compiler/build/libs/v8annotations-compiler.jar
META-INF/
META-INF/MANIFEST.MF
ag/
ag/boersego/
ag/boersego/v8annotations/
ag/boersego/v8annotations/compiler/
ag/boersego/v8annotations/compiler/V8AnnotationProcessor$1.class
ag/boersego/v8annotations/compiler/V8AnnotationProcessor$AccessorTuple.class
ag/boersego/v8annotations/compiler/V8AnnotationProcessor$AnnotationHolder.class
ag/boersego/v8annotations/compiler/V8AnnotationProcessor.class
META-INF/services/
META-INF/services/javax.annotation.processing.Processor

Excerpt from main module build.gradle:

dependencies {
    // gazillions of compile / api / ...
    api project(':ejecta-v8:v8annotations')
    kapt project(':ejecta-v8:v8annotations-compiler')
}

Module v8annotations build.gradle:

apply plugin: 'java-library'

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {}

Module v8annotations-compiler build.gradle:

apply plugin: 'java'

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile project(':ejecta-v8:v8annotations')
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

I'm stumped :(

Body:
In my case it was enough to run

gradlew --stop

from AndroidStudio console


来源: stackexchange

问:
empty message in the mailbox after sending the form
I have problem with send email. When I send a form, I get a blank message in my inbox. It looks like this:

```<code>Mail:
New message from:
E-mail:
Topic:
Sent message:
</code>```

The form has validation, it works correctly. The problem is that I don't know why messages come empty to my inbox.

Here is a php code:

```<code>$name = $_POST['name'];
$mail = $_POST['mail'];
$topic = $_POST['topic'];
$message = $_POST['message'];

$email_to = "example@qmail.com";

$email_subject = "You received a new message";

$email_body = "Mail: \r\n";
$email_body .= "New message from: " .  $name . "\r\n";
$email_body .= "E-mail:"  .  $mail . "\r\n";
$email_body .= "Topic: " . $topic . "\r\n";
$email_body .= "Sent message: " . $message . "\r\n";

$success = mail($email_to, $email_subject, $email_body);

if ($success){
  print "<meta http-equiv=\"refresh\" content=\"0;URL=success-form\index.html\">";
}
else{
  print "<script>console.log('error'); </script>";
}

?>
</code>```

Form in HTML:

```<code> <form method="post" action="../form.php" >
        <input name="name" type="text" placeholder="Name and Surname">
        <label></label>
        <input name="mail" type="email" placeholder="Email address">
        <label></label>
        <input name="topic" type="text" placeholder="Topic">
        <label></label>
        <textarea name="message" placeholder="Message..."></textarea>
        <label></label>
       <input type="submit" class="send-btn" value="Send">
 </form>
</code>```

答:
Have you tried adding a few headers? For example:

```<code>$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=utf-8\r\n";
$headers .= "Content-Transfer-Encoding: 8bit\r\n";
$headers .= "FROM:".$email_from."\r\n"; // Variable to define
</code>```

Then, call you mail command like this:

```<code>$success = mail($email_to, $email_subject, $email_body, $headers);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have problem with send email. When I send a form, I get a blank message in my inbox. It looks like this:

Mail:
New message from:
E-mail:
Topic:
Sent message:

The form has validation, it works correctly. The problem is that I don't know why messages come empty to my inbox.

Here is a php code:

$name = $_POST['name'];
$mail = $_POST['mail'];
$topic = $_POST['topic'];
$message = $_POST['message'];

$email_to = "example@qmail.com";

$email_subject = "You received a new message";

$email_body = "Mail: \r\n";
$email_body .= "New message from: " .  $name . "\r\n";
$email_body .= "E-mail:"  .  $mail . "\r\n";
$email_body .= "Topic: " . $topic . "\r\n";
$email_body .= "Sent message: " . $message . "\r\n";

$success = mail($email_to, $email_subject, $email_body);

if ($success){
  print "<meta http-equiv=\"refresh\" content=\"0;URL=success-form\index.html\">";
}
else{
  print "";
}

?>

Form in HTML:

 <form method="post" action="../form.php" >
        <input name="name" type="text" placeholder="Name and Surname">

        <input name="mail" type="email" placeholder="Email address">

        <input name="topic" type="text" placeholder="Topic">

        <textarea name="message" placeholder="Message..."></textarea>

       <input type="submit" class="send-btn" value="Send">
 </form>

Body:
Have you tried adding a few headers? For example:

$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=utf-8\r\n";
$headers .= "Content-Transfer-Encoding: 8bit\r\n";
$headers .= "FROM:".$email_from."\r\n"; // Variable to define

Then, call you mail command like this:

$success = mail($email_to, $email_subject, $email_body, $headers);


问:
How to load Media Metadata Smoothly in a RecyclerView
I have a Music class that needs to return its cover art as a bitmap in order to use it on a RecylerView. I am using an AsyncTask inner class in the class to perform the retrieval, however, my app freezes once the list is being created from cover arts. Please see the code below for Music.java:

```<code>public class Music {
    private static final String LOG_TAG = Music.class.getSimpleName();
    private String mId;
    private String mTitle;
    private String mUrl;
    private Bitmap mCoverArt;

    public Music(String id, String title, String url) {
        mId = id;
        mTitle = title;
        mUrl = url;
        mCoverArt = null; //Initialize with null
    }

    String getId() {
        return mId;
    }

    String getTitle() {
        return mTitle;
    }

    String getUrl() {
        return mUrl;
    }

    Bitmap getCoverArt() {
        if(mCoverArt != null) {
            return mCoverArt;
        }
        else {
            Bitmap bmp = null;
            try {
                bmp = new GetCoverArt().execute(mUrl).get();
            } catch (InterruptedException e) {
                Log.e(LOG_TAG, "InterruptedException: " + e.getMessage());
            } catch (ExecutionException e) {
                Log.e(LOG_TAG, "ExecutionException: " + e.getMessage());
            }
            return bmp;

        }
    }
    public void setCoverArt(Bitmap bmp) { mCoverArt = bmp; }

    private static class GetCoverArt extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... paths) {
            MediaMetadataRetriever mmr = new MediaMetadataRetriever();
            mmr.setDataSource(paths[0], new HashMap<String,String>());
            byte[] picData = mmr.getEmbeddedPicture();
            return BitmapFactory.decodeByteArray(picData, 0, picData.length);
        }
    }
}
</code>```

I am calling getCoverArt() in onBindViewHolder for my RecyclerView this way:

```<code>@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Music song = mDataset.get(position);
    Bitmap songCoverArt = song.getCoverArt();
    String songTitle = song.getTitle();
    String songId = song.getId();
    String songUrl = song.getUrl();

    if(songCoverArt != null) {
        Glide.with(mContext).load(songCoverArt).into(holder.coverArt);
    }
    else {
        holder.coverArt.setImageResource(R.drawable.coverart_fallback);
    }
    Bitmap bmp = song.getCoverArt();
    if(bmp != null) {
        Glide.with(mContext).load(bmp).into(holder.coverArt);
    }
    else {
        Glide.with(mContext).load(R.drawable.coverart_fallback).into(holder.coverArt);
    }
</code>```

I do not understand why doInBackground in AsyncTask might cause the UI thread to freeze. I thought it all runs in the background, but it seems my RecyclerView is waiting for it to finish the job before it can use the value returned. Currently, as an a bad workaround, I am doing such processing in another AsyncTask in the main activity along with other network operations when I construct Music objects and add them to an ArrayList:

```<code> for( int j = 0 ; j < songs.length() ; j++) {
                            JSONObject song = songs.getJSONObject(j); //get song at index j
                            String songId = song.getString( getString(R.string.json_song_id) );
                            String title = song.getString( getString(R.string.json_song_title));
                            String path = song.getString( getString(R.string.json_filepath) );
                            //Create a temp Music object to extract Music info
                            Music songObj = new Music(songId, title, path);
                            Bitmap bmp = createCoverArtBmp(path);
                            songObj.setCoverArt(bmp);
                            mMusicTrackArray.add(songObj); //Add the music object into array
                        }
</code>```

答:
@Umar Hussain is correct with passing urls, but Glide can also use local files or URI's doing so is covered in:

Glide load local image by Uri.

The benefit here of using local files (I suggest saving to your cache) is that you don't have to pass around bulky bitmaps. Out of memory exceptions make developers sad.

I have noticed you are also using fallbacks from if statements, but Glide has a placeholder method

```<code>Glide.with(getContext())
                    .load(some_bitmap_file_url_or_drawable)
                    .placeholder(some_placeholder_drawable)
                    .into(view_you_want_it_to_appear);
</code>```

This should transition to the image you want when it loads, plus provide a fallback if it doesn't

Body:
I have a Music class that needs to return its cover art as a bitmap in order to use it on a RecylerView. I am using an AsyncTask inner class in the class to perform the retrieval, however, my app freezes once the list is being created from cover arts. Please see the code below for Music.java:

public class Music {
    private static final String LOG_TAG = Music.class.getSimpleName();
    private String mId;
    private String mTitle;
    private String mUrl;
    private Bitmap mCoverArt;

    public Music(String id, String title, String url) {
        mId = id;
        mTitle = title;
        mUrl = url;
        mCoverArt = null; //Initialize with null
    }

    String getId() {
        return mId;
    }

    String getTitle() {
        return mTitle;
    }

    String getUrl() {
        return mUrl;
    }

    Bitmap getCoverArt() {
        if(mCoverArt != null) {
            return mCoverArt;
        }
        else {
            Bitmap bmp = null;
            try {
                bmp = new GetCoverArt().execute(mUrl).get();
            } catch (InterruptedException e) {
                Log.e(LOG_TAG, "InterruptedException: " + e.getMessage());
            } catch (ExecutionException e) {
                Log.e(LOG_TAG, "ExecutionException: " + e.getMessage());
            }
            return bmp;

        }
    }
    public void setCoverArt(Bitmap bmp) { mCoverArt = bmp; }

    private static class GetCoverArt extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... paths) {
            MediaMetadataRetriever mmr = new MediaMetadataRetriever();
            mmr.setDataSource(paths[0], new HashMap<String,String>());
            byte[] picData = mmr.getEmbeddedPicture();
            return BitmapFactory.decodeByteArray(picData, 0, picData.length);
        }
    }
}

I am calling getCoverArt() in onBindViewHolder for my RecyclerView this way:

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Music song = mDataset.get(position);
    Bitmap songCoverArt = song.getCoverArt();
    String songTitle = song.getTitle();
    String songId = song.getId();
    String songUrl = song.getUrl();

    if(songCoverArt != null) {
        Glide.with(mContext).load(songCoverArt).into(holder.coverArt);
    }
    else {
        holder.coverArt.setImageResource(R.drawable.coverart_fallback);
    }
    Bitmap bmp = song.getCoverArt();
    if(bmp != null) {
        Glide.with(mContext).load(bmp).into(holder.coverArt);
    }
    else {
        Glide.with(mContext).load(R.drawable.coverart_fallback).into(holder.coverArt);
    }

I do not understand why doInBackground in AsyncTask might cause the UI thread to freeze. I thought it all runs in the background, but it seems my RecyclerView is waiting for it to finish the job before it can use the value returned. Currently, as an a bad workaround, I am doing such processing in another AsyncTask in the main activity along with other network operations when I construct Music objects and add them to an ArrayList:

 for( int j = 0 ; j < songs.length() ; j++) {
                            JSONObject song = songs.getJSONObject(j); //get song at index j
                            String songId = song.getString( getString(R.string.json_song_id) );
                            String title = song.getString( getString(R.string.json_song_title));
                            String path = song.getString( getString(R.string.json_filepath) );
                            //Create a temp Music object to extract Music info
                            Music songObj = new Music(songId, title, path);
                            Bitmap bmp = createCoverArtBmp(path);
                            songObj.setCoverArt(bmp);
                            mMusicTrackArray.add(songObj); //Add the music object into array
                        }

Body:
@Umar Hussain is correct with passing urls, but Glide can also use local files or URI's doing so is covered in:

Glide load local image by Uri.

The benefit here of using local files (I suggest saving to your cache) is that you don't have to pass around bulky bitmaps. Out of memory exceptions make developers sad.

I have noticed you are also using fallbacks from if statements, but Glide has a placeholder method

Glide.with(getContext())
                    .load(some_bitmap_file_url_or_drawable)
                    .placeholder(some_placeholder_drawable)
                    .into(view_you_want_it_to_appear);

This should transition to the image you want when it loads, plus provide a fallback if it doesn't


问:
c++ csv data importing problems
I am a college student and as part of my final project for a c++ class we are assigned to read a csv file that has distance and force data and then find torque from it.  The problem that I am running into is how to actually get the data out of the csv file into a workable format.  Currently I have been trying to get it into a matrix, to do this though I will need to first determine the size of the csv file as it is supposed to take any size file.  This is the format of the data

Case 1,,,,,x_position (m),y_position (m),z_position (m),F_x (N),F_y (N),F_z (N)16.00,5.00,8.00,394.00,-18.00,396.0022.00,26.00,14.00,-324.00,-420.00,429.0028.00,25.00,21.00,73.00,-396.00,-401.006.00,9.00,12.00,-367.00,-137.00,-143.00

Also obviously the different data pieces (distance and forces) need to be put into different vectors or matrices.
This is what I have so far to try to find the number of lines in the file.

```<code>ifstream myfile("force_measurements.csv");
if(myfile.is_open()){
        string line;
        double num=0;
        getline(myfile, line);
        if(line==""){
            cout<<num<<endl;
            myfile.close();
        }
        else{
            num++;
        }
}
</code>```

After this works how would you go about putting the data into a matrix? or would a different format be easier? vectors was my other though.

答:
```<code>// you need to include the proper headers here
class vec3D:
{
     double m_x, m_y, m_z;
 public:
     void Set(size_t indx, double val)
     {
         switch(indx)
         {
             case 0:
                 m_x = val;
                 break;
             case 1:
                 m_y = val;
                 break;
             case 2:
                 m_z = val;
                 break;
             default:
                 std::cout << "index out of range" << std::endl;
         }
     }
     double magnitude() { return std::sqrt( m_x*m_x + m_y*m_y + m_z*m_y);}
};

int main()
{
     std::ifstream my_data_file ( "your_file_here.csv" );
     std::vector<std::array<vec3D, 2>> Pos_Forz;
     if ( ! my_data_file.is_open())
     {
          std::cout << "failure to open the file" <<std::endl;
          return -1;
     }
     std::string temp_str;
     double arr[6];
     std::array<vec3D,2> temp_3Dvec;
     while(!my_data_file.eof())
     {
         for (int i = 0; i<5 ; i++)
         {
             getline(my_data_file, temp_str, ",");
             arr[i] = std::stod(temp_str);
         }
         getline(my_data_file, temp_str);
         arr[5] = std::stod(temp_str);
         for(int i = 0; i<2; i++)
         {
             for (int j=0; j<3; j++)
             {
                   temp_3Dvec[i].set(j, arr[i*3 + j]);
             }
         }
         Pos_Forz.push_back(temp_3Dvec);
     }
    for(auto e: Pos_Forz)
    {
      std::cout << " toque = " << (e[0].magnitude() * e[1].magnitude()) <<std::endl;
    }
    return 0;
 }
</code>```

Fix what need to be fixed, and inspire yourself from this code, also stop asking this kinda of questions here, you need to read the HOW TO of posting

Title: c++ csv data importing problems

Body:
I am a college student and as part of my final project for a c++ class we are assigned to read a csv file that has distance and force data and then find torque from it.  The problem that I am running into is how to actually get the data out of the csv file into a workable format.  Currently I have been trying to get it into a matrix, to do this though I will need to first determine the size of the csv file as it is supposed to take any size file.  This is the format of the data

Case 1,,,,,x_position (m),y_position (m),z_position (m),F_x (N),F_y (N),F_z (N)16.00,5.00,8.00,394.00,-18.00,396.0022.00,26.00,14.00,-324.00,-420.00,429.0028.00,25.00,21.00,73.00,-396.00,-401.006.00,9.00,12.00,-367.00,-137.00,-143.00

Also obviously the different data pieces (distance and forces) need to be put into different vectors or matrices.
This is what I have so far to try to find the number of lines in the file.

ifstream myfile("force_measurements.csv");
if(myfile.is_open()){
        string line;
        double num=0;
        getline(myfile, line);
        if(line==""){
            cout<<num<<endl;
            myfile.close();
        }
        else{
            num++;
        }
}

After this works how would you go about putting the data into a matrix? or would a different format be easier? vectors was my other though.

Body:
// you need to include the proper headers here
class vec3D:
{
     double m_x, m_y, m_z;
 public:
     void Set(size_t indx, double val)
     {
         switch(indx)
         {
             case 0:
                 m_x = val;
                 break;
             case 1:
                 m_y = val;
                 break;
             case 2:
                 m_z = val;
                 break;
             default:
                 std::cout << "index out of range" << std::endl;
         }
     }
     double magnitude() { return std::sqrt( m_x*m_x + m_y*m_y + m_z*m_y);}
};

int main()
{
     std::ifstream my_data_file ( "your_file_here.csv" );
     std::vector<std::array<vec3D, 2>> Pos_Forz;
     if ( ! my_data_file.is_open())
     {
          std::cout << "failure to open the file" <<std::endl;
          return -1;
     }
     std::string temp_str;
     double arr[6];
     std::array<vec3D,2> temp_3Dvec;
     while(!my_data_file.eof())
     {
         for (int i = 0; i<5 ; i++)
         {
             getline(my_data_file, temp_str, ",");
             arr[i] = std::stod(temp_str);
         }
         getline(my_data_file, temp_str);
         arr[5] = std::stod(temp_str);
         for(int i = 0; i<2; i++)
         {
             for (int j=0; j<3; j++)
             {
                   temp_3Dvec[i].set(j, arr[i*3 + j]);
             }
         }
         Pos_Forz.push_back(temp_3Dvec);
     }
    for(auto e: Pos_Forz)
    {
      std::cout << " toque = " << (e[0].magnitude() * e[1].magnitude()) <<std::endl;
    }
    return 0;
 }

Fix what need to be fixed, and inspire yourself from this code, also stop asking this kinda of questions here, you need to read the HOW TO of posting


问:
Angular 2+ timer function is not working in one of the components
This is very very very strange. I got an timer function which works on all my components except 1. But I just don't know why, I also don't get any errors or something.

What am I missing? The code that I use looks like this:

The HTML

```<code><p>Time in miliseconds: <b id="tick">{{time}}</b></p>
</code>```

and in my protected.component.ts

```<code>timeBegin = new Date();
  starts = null;
  time = '00:00:00.000';

GetUser(): void {
    this.startTime();
    this.dataService.getUser().subscribe(res => {
      if (res !== undefined) {
        this.dataIsReady = true;
        this.imgSrc = 'data:image/png;base64,' + res['image'];
      }
    });
    this.stopTime();
  }

public clockRun() {
const currentTime = new Date();
const timeElapsed = new Date(currentTime.getTime() - this.timeBegin.getTime());
const hour = timeElapsed.getUTCHours();
const min = timeElapsed.getUTCMinutes();
const sec = timeElapsed.getUTCSeconds();
const ms = timeElapsed.getUTCMilliseconds();

this.time =
    (hour > 9 ? hour : '0' + hour) + ':' +
    (min > 9 ? min : '0' + min) + ':' +
    (sec > 9 ? sec : '0' + sec) + '.' +
    (ms > 99 ? ms : ms > 9 ? '0' + ms : '0' + ms);

}

  startTime() {
    this.timeBegin = new Date();

    this.starts = setInterval(this.clockRun.bind(this), 10);
  }

  stopTime() {
    clearInterval(this.starts);
  }
</code>```

答:
I guess you could simplify it a bit. For example:

In HTML better to use DatePipe, like:

```<code>{{ interval | date:'HH:mm:ss SSS':'+0000'}}
</code>```

In Component:

```<code>  timeBegin: Date;
  interval: Date;

  ngOnInit() {
    this.timeBegin = new Date();
    setInterval(this.tick.bind(this), 100);
  }

  tick() {
    let currentTime = new Date();
    this.interval = new Date(currentTime.valueOf() - this.timeBegin.valueOf());
  }
</code>```

Also in your example, you immediate stop the time and as result don't see progress. Try to execute stopTime within subscribe block, for example:

```<code>GetUser(): void {
    this.startTime();
    this.dataService.getUser().subscribe(res => {
      if (res !== undefined) {
        this.dataIsReady = true;
        this.imgSrc = 'data:image/png;base64,' + res['image'];
      }
      this.stopTime();
    });
  }
</code>```

Body:
This is very very very strange. I got an timer function which works on all my components except 1. But I just don't know why, I also don't get any errors or something.

What am I missing? The code that I use looks like this:

The HTML

Time in miliseconds: {{time}}

and in my protected.component.ts

timeBegin = new Date();
  starts = null;
  time = '00:00:00.000';

GetUser(): void {
    this.startTime();
    this.dataService.getUser().subscribe(res => {
      if (res !== undefined) {
        this.dataIsReady = true;
        this.imgSrc = 'data:image/png;base64,' + res['image'];
      }
    });
    this.stopTime();
  }

public clockRun() {
const currentTime = new Date();
const timeElapsed = new Date(currentTime.getTime() - this.timeBegin.getTime());
const hour = timeElapsed.getUTCHours();
const min = timeElapsed.getUTCMinutes();
const sec = timeElapsed.getUTCSeconds();
const ms = timeElapsed.getUTCMilliseconds();

this.time =
    (hour > 9 ? hour : '0' + hour) + ':' +
    (min > 9 ? min : '0' + min) + ':' +
    (sec > 9 ? sec : '0' + sec) + '.' +
    (ms > 99 ? ms : ms > 9 ? '0' + ms : '0' + ms);

}

  startTime() {
    this.timeBegin = new Date();

    this.starts = setInterval(this.clockRun.bind(this), 10);
  }

  stopTime() {
    clearInterval(this.starts);
  }

Body:
I guess you could simplify it a bit. For example:

In HTML better to use DatePipe, like:

{{ interval | date:'HH:mm:ss SSS':'+0000'}}

In Component:

  timeBegin: Date;
  interval: Date;

  ngOnInit() {
    this.timeBegin = new Date();
    setInterval(this.tick.bind(this), 100);
  }

  tick() {
    let currentTime = new Date();
    this.interval = new Date(currentTime.valueOf() - this.timeBegin.valueOf());
  }

Also in your example, you immediate stop the time and as result don't see progress. Try to execute stopTime within subscribe block, for example:

GetUser(): void {
    this.startTime();
    this.dataService.getUser().subscribe(res => {
      if (res !== undefined) {
        this.dataIsReady = true;
        this.imgSrc = 'data:image/png;base64,' + res['image'];
      }
      this.stopTime();
    });
  }


问:
How to do regression as opposed to classification using logistic regression and scikit learn
The target variable that I need to predict are probabilities (as opposed to labels). The corresponding column in my training data are also in this form. I do not want to lose information by thresholding the targets to create a classification problem out of it.

If I train the logistic regression classifier with binary labels, sk-learn logistic regression API allows obtaining the probabilities at prediction time. However, I need to train it with probabilities. Is there a way to do this in scikits-learn, or a suitable Python package that scales to 100K data points of 1K dimension.

答:
Instead of using predict in the scikit learn library use predict_proba function

refer here:
http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression.predict_proba


问:
Assigning object properties (in a loop) and including a setter results in undefined values
This is my first attempt at using Javascript's Object.defineProperty and/or defineProperties and apparently I'm doing it completely incorrectly.  I am passing a cfg object into a Javascript function constructor, then inside that constructor am looping over the config and

Calling Object.defineProperty on each cfg key

Assigning this[key] = cfg[key]

However every this[key] emerges with undefined as it's value.  I've tried a few different things, such as setting the writable attribute to true, but got an error that this conflicts with the set/function.  I've also tried using Object.defineProperties with the same result.  I don't think it's a scoping issue with this and have even used .bind(this) on the setters to be sure, but to no avail.  The code is can be run at https://repl.it/@dexygen/js-define-properties and I am including it below inline.  Expected result of course rather than undefined is that this.foo e.g. will contain the string 'foo' from cfg.foo passed into the object constructor function

```<code>let myObj = new ObjInstance({
    foo: 'foo',
    bar: 'bar',
    baz: 'baz'
});

function ObjInstance(cfg) {
    for (let key in cfg) {
      Object.defineProperty(this, key, {
          configurable: true,
          enumerable: true,
          // writable: true, // throws error in conjunction with set function
          set: (function(val) {
              console.log('this[' + key + ']: ' + this[key]); //undefined :(
          }).bind(this)
      });
      console.log('cfg[key]: ' + cfg[key]);
      this[key] = cfg[key];
    }
    console.log(this);
    console.log('this.foo: ' + this.foo);
    /* // if you comment this in, comment out the above for loop
    let objProperties = {}
    for (let key in cfg) {
        objProperties[key] = {
          configurable: true,
          enumerable: true,
          set: (function(val) {
              console.log('this[' + key + ']: ' + this[key]);
          }).bind(this)
        }
    }
    for (let key in cfg) {
      console.log('cfg[key]: ' + cfg[key]);
      this[key] = cfg[key];
    }
    Object.defineProperties(this, objProperties);
    for (let key in cfg) {
      console.log('cfg[key]: ' + cfg[key]);
      this[key] = cfg[key];
    }
    */
}
</code>```

答:
Here is an alternative JavaScript backward compatible equivalent </p>

```<code>function Handle( O ) {

var arr = [];

   for( var p in O ) {
    arr.push(
    ["get "+p+"(){ return O['"+p+"']; }, set "+p+"(x){ O['"+p+"'] = x; /*your emitter*/ }" ]
    );
   }
    return Function("O", "return {"+arr.join()+"}" )(O);
}
</code>```

Body:
This is my first attempt at using Javascript's Object.defineProperty and/or defineProperties and apparently I'm doing it completely incorrectly.  I am passing a cfg object into a Javascript function constructor, then inside that constructor am looping over the config and

Calling Object.defineProperty on each cfg key

Assigning this[key] = cfg[key]

However every this[key] emerges with undefined as it's value.  I've tried a few different things, such as setting the writable attribute to true, but got an error that this conflicts with the set/function.  I've also tried using Object.defineProperties with the same result.  I don't think it's a scoping issue with this and have even used .bind(this) on the setters to be sure, but to no avail.  The code is can be run at https://repl.it/@dexygen/js-define-properties and I am including it below inline.  Expected result of course rather than undefined is that this.foo e.g. will contain the string 'foo' from cfg.foo passed into the object constructor function

let myObj = new ObjInstance({
    foo: 'foo',
    bar: 'bar',
    baz: 'baz'
});

function ObjInstance(cfg) {
    for (let key in cfg) {
      Object.defineProperty(this, key, {
          configurable: true,
          enumerable: true,
          // writable: true, // throws error in conjunction with set function
          set: (function(val) {
              console.log('this[' + key + ']: ' + this[key]); //undefined :(
          }).bind(this)
      });
      console.log('cfg[key]: ' + cfg[key]);
      this[key] = cfg[key];
    }
    console.log(this);
    console.log('this.foo: ' + this.foo);
    /* // if you comment this in, comment out the above for loop
    let objProperties = {}
    for (let key in cfg) {
        objProperties[key] = {
          configurable: true,
          enumerable: true,
          set: (function(val) {
              console.log('this[' + key + ']: ' + this[key]);
          }).bind(this)
        }
    }
    for (let key in cfg) {
      console.log('cfg[key]: ' + cfg[key]);
      this[key] = cfg[key];
    }
    Object.defineProperties(this, objProperties);
    for (let key in cfg) {
      console.log('cfg[key]: ' + cfg[key]);
      this[key] = cfg[key];
    }
    */
}

Body:
Here is an alternative JavaScript backward compatible equivalent

function Handle( O ) {

var arr = [];

   for( var p in O ) {
    arr.push(
    ["get "+p+"(){ return O['"+p+"']; }, set "+p+"(x){ O['"+p+"'] = x; /*your emitter*/ }" ]
    );
   }
    return Function("O", "return {"+arr.join()+"}" )(O);
}


问:
How do I make on_touch_down widget specific?
I'm trying to create a simple drawing app in kivy but i'm having some issues with the

```<code>on_touch_down
</code>```

function as it regards the entire class and not just a specific widget. So when I use the on touch down and on touch move functions to draw on the canvas it affects and effectively disables the touch down functions bound to buttons. Here's the code where the button doesn't work.

python code:

```<code>from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.graphics import Line
from kivy.graphics import *
from kivy.uix.widget import Widget
class MyScreenManager(ScreenManager):
    pass

class MenuScreen(Screen):
    pass

class DrawScreen(Screen):
    def on_touch_down(self, touch):
        with self.canvas.before:
            Color(1, 0, 0)
            touch.ud["line"] = Line(points=(touch.x, touch.y), width=5)

    def on_touch_move(self, touch):
        touch.ud["line"].points += (touch.x, touch.y)

class DrawApp(App):
    def build(self):
        return MyScreenManager()

DrawApp().run()
</code>```

kivy code:

```<code><MenuButton@Button>:
    font_size: 65
    size_hint: 0.4, 0.25

<MyScreenManager>:
    MenuScreen:
        id: menu
        name: "menu"

    DrawScreen:
        id: draw
        name: "draw"

<MenuScreen>:
    canvas.before:
        Color:
            rgba: 1,1,1,1
        Rectangle:
            size: self.size
            pos: self.pos

    MenuButton:
        text: "Draw"
        on_release: root.manager.current = "draw"
        pos_hint:{"center_x":0.5, "center_y":0.6}
    MenuButton:
        text: "Quit"
        on_release: app.stop()
        pos_hint:{"center_x":0.5, "center_y":0.3}

<DrawScreen>:
    canvas.before:
        Color:
            rgba: 1,1,1,1
        Rectangle:
            size: self.size
            pos: self.pos

    Button:
        id: but
        size_hint: 0.2,0.1
        pos_hint_x: 0 + self.width
        font_size: 30
        text: "Back"
        on_release: root.manager.current = "menu"
</code>```

I managed to find a simple work around by using collide_point, here's my workaround code:

```<code>class DrawScreen(Screen):
    def on_touch_down(self, touch):
        but = self.ids.but
        if but.collide_point(touch.x, touch.y):
            self.manager.current = "menu"

        else:
            with self.canvas.before:
                Color(1, 0, 0)
                touch.ud["line"] = Line(points=(touch.x, touch.y), width=5)

    def on_touch_move(self, touch):
        touch.ud["line"].points += (touch.x, touch.y)
</code>```

But while this works it brings up a whole world of new problems like me having to manually configure every button to change source when held down and the function not running until the button is released. It also means that everything I add to the class has to be added to the if statement.

I'm quite positive that there has to be a simpler way. My first thought was that maybe one could add the on touch down to only affect one widget? My second thought was that maybe if would be better to not draw on the canvas or something?

Any help or pointers are appreciated, thanks!

答:
when you overwrite a method, you must return the same method of the super class

something like this:

```<code>...

class DrawScreen(Screen):
    def on_touch_down(self, touch):
        with self.canvas.before:
            Color(1, 0, 0)
            touch.ud["line"] = Line(points=(touch.x, touch.y), width=5)
        return super(DrawScreen, self).on_touch_down(touch)

    def on_touch_move(self, touch):
        touch.ud["line"].points += (touch.x, touch.y)
        return super(DrawScreen, self).on_touch_move(touch)
</code>```

Body:
I'm trying to create a simple drawing app in kivy but i'm having some issues with the

on_touch_down

function as it regards the entire class and not just a specific widget. So when I use the on touch down and on touch move functions to draw on the canvas it affects and effectively disables the touch down functions bound to buttons. Here's the code where the button doesn't work.

python code:

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.graphics import Line
from kivy.graphics import *
from kivy.uix.widget import Widget
class MyScreenManager(ScreenManager):
    pass

class MenuScreen(Screen):
    pass

class DrawScreen(Screen):
    def on_touch_down(self, touch):
        with self.canvas.before:
            Color(1, 0, 0)
            touch.ud["line"] = Line(points=(touch.x, touch.y), width=5)

    def on_touch_move(self, touch):
        touch.ud["line"].points += (touch.x, touch.y)

class DrawApp(App):
    def build(self):
        return MyScreenManager()

DrawApp().run()

kivy code:

<MenuButton@Button>:
    font_size: 65
    size_hint: 0.4, 0.25

<MyScreenManager>:
    MenuScreen:
        id: menu
        name: "menu"

    DrawScreen:
        id: draw
        name: "draw"

<MenuScreen>:
    canvas.before:
        Color:
            rgba: 1,1,1,1
        Rectangle:
            size: self.size
            pos: self.pos

    MenuButton:
        text: "Draw"
        on_release: root.manager.current = "draw"
        pos_hint:{"center_x":0.5, "center_y":0.6}
    MenuButton:
        text: "Quit"
        on_release: app.stop()
        pos_hint:{"center_x":0.5, "center_y":0.3}

<DrawScreen>:
    canvas.before:
        Color:
            rgba: 1,1,1,1
        Rectangle:
            size: self.size
            pos: self.pos

    Button:
        id: but
        size_hint: 0.2,0.1
        pos_hint_x: 0 + self.width
        font_size: 30
        text: "Back"
        on_release: root.manager.current = "menu"

I managed to find a simple work around by using collide_point, here's my workaround code:

class DrawScreen(Screen):
    def on_touch_down(self, touch):
        but = self.ids.but
        if but.collide_point(touch.x, touch.y):
            self.manager.current = "menu"

        else:
            with self.canvas.before:
                Color(1, 0, 0)
                touch.ud["line"] = Line(points=(touch.x, touch.y), width=5)

    def on_touch_move(self, touch):
        touch.ud["line"].points += (touch.x, touch.y)

But while this works it brings up a whole world of new problems like me having to manually configure every button to change source when held down and the function not running until the button is released. It also means that everything I add to the class has to be added to the if statement.

I'm quite positive that there has to be a simpler way. My first thought was that maybe one could add the on touch down to only affect one widget? My second thought was that maybe if would be better to not draw on the canvas or something?

Any help or pointers are appreciated, thanks!

Body:
when you overwrite a method, you must return the same method of the super class

something like this:

...

class DrawScreen(Screen):
    def on_touch_down(self, touch):
        with self.canvas.before:
            Color(1, 0, 0)
            touch.ud["line"] = Line(points=(touch.x, touch.y), width=5)
        return super(DrawScreen, self).on_touch_down(touch)

    def on_touch_move(self, touch):
        touch.ud["line"].points += (touch.x, touch.y)
        return super(DrawScreen, self).on_touch_move(touch)


问:
Empty string results in "Errors were detected in the command line arguments, please make sure all arguments are set correctly"
On a SQL 2016 Server I have a job that calls an SSIS package.  That package is in a project in the SSISDB and has parameters.   One of those parameters is a string type that is blank as a default.

I ran the job with the blank value for this parameter, and it ran successfully.

I then opened the job properties, went to the step that calls that package and went into the configuration and gave that parameter a value.

I ran the job again and it ran successfully, and the parameter value had the expected effect on the results.

Now I want to modify the job and set the parameter back to a blank string.  Repeating what I did above, I open the configuration and completely delete the value of the parameter.

When I then try to save the Job Step properties, I get an error dialog with the message in my subject line.

If I put a non-empty value back in for that parameter, the job step can be saved.

When I first created the job, I was able to save it with an empty string for that value.  It's just when I change the value to a non-empty string, run the job, and then try to change it back to empty, that I encounter this error.

I'm aware that I can run an alter job script or delete and re-create the job step to work around this.  I'm not interested in knowing how to work around this problem.

My question is:  Is this a known bug, or is there a trick to using the GUI to change the value of a parameter for execution from a string value to an empty string?

Can any of you do it, or is my issue reproducible?  I've found nothing in my searches so far.

EDIT: following Aaron's comment, I tried entering a pair of single-quotes for the value of the parameter. The job accepted it and saved successfully. But then when I ran the job, the pair of single quotes were used literally as the value of the parameter, instead of an empty string.

答:
These problem is posted on the Microsoft Connect website 2 times.

The first time it is marked as fixed because the user chooses to use a workaround, which is to pass a White Space then remove it from within the package. Read more

The Second time it is marked as "Won't fixed" because the Microsoft team is focusing on other issues Read more

Also a similar question is asked on MSDN network and it is solved with a workaround.

SO it seems that this is a software bug, that it is not solved yet. You may use a workaround for that.


问:
PHP MySQL optimal way to perform multiple dependent queries
I need to query (read) some data, and analyze it before performing another query (read) on a different table.

I've looked at mysqli multiple statements but they don't have documentation for situations where the second query depends on the result of the first query.

It seems my current code of doing two queries might not be optimal. Is there a more optimal way to do this?

```<code>//FIRST QUERY
$query1= "SELECT color FROM products WHERE type = '$productType';";
$result = $conn->query($query1);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $colorProduct = $row["color"];
    }
}

//ANALYZE SEARCH RESULT FROM FIRST QUERY
if ($colorProduct == "green") {
    $colorType = "greenColorType";
}
//a lot more analysis

//SECOND QUERY
$query2 = "SELECT price FROM Vendors WHERE color = '$colorType';";
$result2 = $conn->query($query2);

if ($result2->num_rows > 0) {
    while($row = $result2->fetch_assoc()) {
        $priceOfProduct = priceOfProduct . $row["price"];
    }
}

$conn->close();
</code>```

Thank you in advance.

答:
Why don't you join those 2 queries into one and analyse later if you need to. For example:

```<code>"SELECT price FROM products
JOIN Vendors ON Vendors.color = products.color
WHERE type = $productType
AND color = 'green';"
</code>```

MySQL is declarative language so it is usually better to "tell it" what you want and than modify data afterwards (if needed).

Body:
I need to query (read) some data, and analyze it before performing another query (read) on a different table.

I've looked at mysqli multiple statements but they don't have documentation for situations where the second query depends on the result of the first query.

It seems my current code of doing two queries might not be optimal. Is there a more optimal way to do this?

//FIRST QUERY
$query1= "SELECT color FROM products WHERE type = '$productType';";
$result = $conn->query($query1);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $colorProduct = $row["color"];
    }
}

//ANALYZE SEARCH RESULT FROM FIRST QUERY
if ($colorProduct == "green") {
    $colorType = "greenColorType";
}
//a lot more analysis

//SECOND QUERY
$query2 = "SELECT price FROM Vendors WHERE color = '$colorType';";
$result2 = $conn->query($query2);

if ($result2->num_rows > 0) {
    while($row = $result2->fetch_assoc()) {
        $priceOfProduct = priceOfProduct . $row["price"];
    }
}

$conn->close();

Thank you in advance.

Body:
Why don't you join those 2 queries into one and analyse later if you need to. For example:

"SELECT price FROM products
JOIN Vendors ON Vendors.color = products.color
WHERE type = $productType
AND color = 'green';"

MySQL is declarative language so it is usually better to "tell it" what you want and than modify data afterwards (if needed).


问:
Correlation in R - missing values
I want to run correlations on the following dataset. I want correlations among all (V1 with V2, V3, V4, V5; V2 with V1, V3, V4, V5 and so on...). I want the correlation coefficient and the p-values.

mydataset

```<code>   Group    V1        V2          V3         V4       V5
   OH      0.3        5          -3.09      2.5      NA
   OH      0.5        1           NA        1.8      2.5
   ON      2          2.5         NA       -3.11    -7.5
   OH      1.5       -3.35       -0.82       NA     -2.5
   ON      6.5       -2.85        2.5        NA      NA
   OH      3          0.5         1.8      -2.85     NA
</code>```

I ran this code

```<code>    correlations <- corr.test (mydataset, use = "pairwise").
</code>```

I have also run:

```<code>    correlations <- cor(mydataset, use = "complete.obs", method = "pearson")
</code>```

I don't know how to deal with missing values. And I am not getting any output whatsoever. I keep getting this error:

```<code>    Error in cor(x, use = use, method = method) : 'x' must be numeric
</code>```

Any suggestions on what might work?

Thanks!

答:
The problem is not the NA's, but rather that variable Group is not numeric. So try

```<code> cor(mydataset[sapply(mydataset, is.numeric)], use='pairwise')
</code>```

This will only select numeric variables and exclude NA.

```<code>        V1         V2         V3         V4         V5
V1  1.0000000 -0.5917056  0.8907941 -0.9355822 -0.9819805
V2 -0.5917056  1.0000000 -0.6376181  0.4894776 -0.2468321
V3  0.8907941 -0.6376181  1.0000000 -1.0000000         NA
V4 -0.9355822  0.4894776 -1.0000000  1.0000000  1.0000000
V5 -0.9819805 -0.2468321         NA  1.0000000  1.0000000
</code>```

In the correlation matrix we see that we get NA for correlation between V3 and V5, but that is because V3 and V5 are not simultaneously NA only in one observation, and you can't get correlation only on one pair of points.

Title: Correlation in R - missing values

Body:
I want to run correlations on the following dataset. I want correlations among all (V1 with V2, V3, V4, V5; V2 with V1, V3, V4, V5 and so on...). I want the correlation coefficient and the p-values.

mydataset

   Group    V1        V2          V3         V4       V5
   OH      0.3        5          -3.09      2.5      NA
   OH      0.5        1           NA        1.8      2.5
   ON      2          2.5         NA       -3.11    -7.5
   OH      1.5       -3.35       -0.82       NA     -2.5
   ON      6.5       -2.85        2.5        NA      NA
   OH      3          0.5         1.8      -2.85     NA

I ran this code

    correlations <- corr.test (mydataset, use = "pairwise").

I have also run:

    correlations <- cor(mydataset, use = "complete.obs", method = "pearson")

I don't know how to deal with missing values. And I am not getting any output whatsoever. I keep getting this error:

    Error in cor(x, use = use, method = method) : 'x' must be numeric

Any suggestions on what might work?

Thanks!

Body:
The problem is not the NA's, but rather that variable Group is not numeric. So try

 cor(mydataset[sapply(mydataset, is.numeric)], use='pairwise')

This will only select numeric variables and exclude NA.

        V1         V2         V3         V4         V5
V1  1.0000000 -0.5917056  0.8907941 -0.9355822 -0.9819805
V2 -0.5917056  1.0000000 -0.6376181  0.4894776 -0.2468321
V3  0.8907941 -0.6376181  1.0000000 -1.0000000         NA
V4 -0.9355822  0.4894776 -1.0000000  1.0000000  1.0000000
V5 -0.9819805 -0.2468321         NA  1.0000000  1.0000000

In the correlation matrix we see that we get NA for correlation between V3 and V5, but that is because V3 and V5 are not simultaneously NA only in one observation, and you can't get correlation only on one pair of points.


问:
UI pattern for multiple destinations from UITableView
I'm trying to find the right UI pattern for connecting a list of items in a UITableView to a choice of destinations. In a UITableView I have a list of food items. I want the user to be able to select one of them and then either see a list of ingredients or to see nutritional information for that food item.

The best approach I can think of is to use a Tab Bar Controller where the first view is the list of ingredients. If the user has selected one food item, depending on which other tab they tap on they go to either the ingredients or nutritional information for that specific food item. But that doesn't seem like an appropriate use of a Tab Bar Controller, which typically shows different views that are not so directly related.

Another UI approach I can think of is to expose disclosure indicators for the food item cells and somehow make a long-press on the selected UITableView row display a pop-up menu that allows the user to select the desired destination. But A) it won't be obvious to a user that a long-press gesture will do something, B) it's not clear what a simple short press should do (and it would be non-intuitive for it to do nothing), and C) I'm not sure how to implement the pop-up choice in this case anyway. So my conclusion is there must be a better way.

How can this be done in a way that is consistent with iOS UI conventions?

答:
The solution I settled on was to have UITableView that displays the list of food items, where selecting one of the items segues to another UITableView with three sections:

A 'label' view with a summary of the item that was selected. In my case it includes an UIImage of the food. The point is to show the user which item the selected.

A section showing the ingredients

A section showing the nutritional information

The benefit of this approach is that it also works well in a splitViewController.


问:
How do I enter a query with a PREFIX in RDF4J Console?
```<code>sparql> PREFIX ab: <http://learningsparql.com/ns/addressbook#>
Executing update...
Update executed in 160 ms
sparql> SELECT ?craigEmail WHERE { ?person ab:firstName "Craig" }
Malformed query: org.eclipse.rdf4j.query.parser.sparql.ast.VisitorException:
QName 'ab:firstName' uses an undefined prefix

sparql> SELECT ?craigEmail WHERE { ?person
<http://learningsparql.com/ns/addressbook/firstName> "Craig" }
Evaluating SPARQL query...
+-----------------------------------------------------------------------------+
| craigEmail                                                                  |
+-----------------------------------------------------------------------------+
+-----------------------------------------------------------------------------+
0 result(s) (64 ms)
</code>```

答:
The RDF4J console by default only takes a single-line SPARQL query, so like James suggested in his answer: enter the query as a single line.

Alternatively, you can use the sparql command to enter into multiline mode:

```<code>memory> sparql
enter multi-line SPARQL query (terminate with line containing single '.')
PREFIX ab: <http://learningsparql.com/ns/addressbook#>
SELECT ?craigEmail WHERE { ?person ab:firstName "Craig" }
.
Evaluating SPARQL query...
+-----------------------------------------------------------------------------+
| craigEmail                                                                  |
+-----------------------------------------------------------------------------+
+-----------------------------------------------------------------------------+
0 result(s) (93 ms)
memory>
</code>```

This is particularly useful when you're copy-pasting larger queries.

As an aside, the first "query" that you do:

```<code>sparql> PREFIX ab: <http://learningsparql.com/ns/addressbook#>
Executing update...
Update executed in 160 ms
</code>```

The output is misleading, since 'Update executed' suggests you've just added the new namespace prefix. But that's not what's happening. Instead, the console interprets this as a SPARQL update that's missing a "body", and just executes it as an empty update. The prefix is ignored. Arguably this is a fault in the SPARQL parser as just a prefix declaration without a body is, strictly speaking, not a legal query.

There is no "official" way to add a new namespace prefix to an RDF4J store via the Console, but there is a trick you can use (though this will only work if you're executing it on a store or SPARQL endpoint to which you have write access):

```<code>PREFIX ab: <http://learningsparql.com/ns/addressbook#> INSERT DATA {}
</code>```

This will execute a SPARQL update to insert new triples, but with an empty block (so no actual triples are inserted). However, this will add the namespace prefix to the repository, after which you no longer have to declare it for every query you enter into the console:

```<code>memory> show n
--no namespaces found--
memory> PREFIX ab: <http://learningsparql.com/ns/addressbook#> INSERT DATA {}
Executing update...
Update executed in 3 ms
memory> show n
+----------
|ab  http://learningsparql.com/ns/addressbook#
|rdf  http://www.w3.org/1999/02/22-rdf-syntax-ns#
|owl  http://www.w3.org/2002/07/owl#
|xsd  http://www.w3.org/2001/XMLSchema#
|fn  http://www.w3.org/2005/xpath-functions#
|rdfs  http://www.w3.org/2000/01/rdf-schema#
|sesame  http://www.openrdf.org/schema/sesame#
+----------
memory> SELECT ?craigEmail WHERE { ?person ab:firstName "Craig" }
Evaluating SPARQL query...
+-----------------------------------------------------------------------------+
| craigEmail                                                                  |
+-----------------------------------------------------------------------------+
+-----------------------------------------------------------------------------+
0 result(s) (47 ms)
memory>
</code>```

Body:
The RDF4J console by default only takes a single-line SPARQL query, so like James suggested in his answer: enter the query as a single line.

Alternatively, you can use the sparql command to enter into multiline mode:

memory> sparql
enter multi-line SPARQL query (terminate with line containing single '.')
PREFIX ab: <http://learningsparql.com/ns/addressbook#>
SELECT ?craigEmail WHERE { ?person ab:firstName "Craig" }
.
Evaluating SPARQL query...
+-----------------------------------------------------------------------------+
| craigEmail                                                                  |
+-----------------------------------------------------------------------------+
+-----------------------------------------------------------------------------+
0 result(s) (93 ms)
memory>

This is particularly useful when you're copy-pasting larger queries.

As an aside, the first "query" that you do:

sparql> PREFIX ab: <http://learningsparql.com/ns/addressbook#>
Executing update...
Update executed in 160 ms

The output is misleading, since 'Update executed' suggests you've just added the new namespace prefix. But that's not what's happening. Instead, the console interprets this as a SPARQL update that's missing a "body", and just executes it as an empty update. The prefix is ignored. Arguably this is a fault in the SPARQL parser as just a prefix declaration without a body is, strictly speaking, not a legal query.

There is no "official" way to add a new namespace prefix to an RDF4J store via the Console, but there is a trick you can use (though this will only work if you're executing it on a store or SPARQL endpoint to which you have write access):

PREFIX ab: <http://learningsparql.com/ns/addressbook#> INSERT DATA {}

This will execute a SPARQL update to insert new triples, but with an empty block (so no actual triples are inserted). However, this will add the namespace prefix to the repository, after which you no longer have to declare it for every query you enter into the console:

memory> show n
--no namespaces found--
memory> PREFIX ab: <http://learningsparql.com/ns/addressbook#> INSERT DATA {}
Executing update...
Update executed in 3 ms
memory> show n
+----------
|ab  http://learningsparql.com/ns/addressbook#
|rdf  http://www.w3.org/1999/02/22-rdf-syntax-ns#
|owl  http://www.w3.org/2002/07/owl#
|xsd  http://www.w3.org/2001/XMLSchema#
|fn  http://www.w3.org/2005/xpath-functions#
|rdfs  http://www.w3.org/2000/01/rdf-schema#
|sesame  http://www.openrdf.org/schema/sesame#
+----------
memory> SELECT ?craigEmail WHERE { ?person ab:firstName "Craig" }
Evaluating SPARQL query...
+-----------------------------------------------------------------------------+
| craigEmail                                                                  |
+-----------------------------------------------------------------------------+
+-----------------------------------------------------------------------------+
0 result(s) (47 ms)
memory>


问:
SQL - how to query to find if two columes are 1to1 1tomany manytomany relationship?
I want to draw a class diagram to describe the relationship between columes. how to query to find if two columes are 1to1 or 1tomany or manytomany relationship? for example, below table shows that column "name" is 1-to-many with colume "prod".

答:
I found below query works. It will show me any records in 1st column (i.e.name) which have more than one values in the 2nd column (i.e.prod), and vice versa which together could show if the two columns are 1:1 or 1:many or many：1 or many:many</p>

```<code>    select name, count(prod)
from (select name, prod from test.relationship
      group by name, prod) subtable
group by name
having count(prod) > 1
</code>```

Body:
I found below query works. It will show me any records in 1st column (i.e.name) which have more than one values in the 2nd column (i.e.prod), and vice versa which together could show if the two columns are 1:1 or 1:many or many：1 or many:many

    select name, count(prod)
from (select name, prod from test.relationship
      group by name, prod) subtable
group by name
having count(prod) > 1


问:
Run Java Code Online
codepad.org allow you to run C,C++,D etc code online but not Java... is there a site that I can use for Java?</p>

答: I found this online java compiler and runner. It work also with threads and showing results immediately. http://www.browxy.com</p>

ContentLicense: CC BY-SA 2.5

Title: Run Java Code Online


问:
How can I make this PowerShell script more efficient?
I am trying to make a script that takes an XML file, looks for a matching condition, if it finds it adds a new line of asteriks, then when done going through the file to strip it of all its XML tags and leave the data in a plain text file.

The script has been tested on a small input xml file and works fine, but when I pass a large XML file to it takes forever (not actually sure how long as I ran it for over an hour and still no result so I just stopped it).

I'm guessing I must be performing the work in an extremely inefficient manner, hoping you guys can help me make it fast and efficient.

Here is the script below:

```<code># Takes input XML File, cleans up XML elements, outputs plain text file

$FileName = "C:\Users\someguy\Desktop\input.xml"
$Pattern = "ProcessSpecifier = ""true"""
$FileOriginal = Get-Content $FileName

[String[]] $FileModified = @()
Foreach ($Line in $FileOriginal)
{
    $FileModified += $Line
    if ($Line -match $Pattern)
    {
        #Add Lines after the selected pattern
        $FileModified += "*************isActive=true*****************"
    }
}

$FileModified -replace "<[^>]+>", "" | Out-File C:\Users\someguy\Desktop\Output.txt
</code>```

答:
Let's go with a look behind and a bunch of regex to speed things up here. Also, I'm not going to store the whole thing in memory, I'm just going to pass it down the pipeline, which should help. I remove whitespace from the beginning and ends of lines, and filter out blank lines, but you can remove that bit if you want.

```<code># Takes input XML File, cleans up XML elements, outputs plain text file

$FileName = "C:\Users\someguy\Desktop\input.xml"
$Pattern = '(?<=^.*ProcessSpecifier = "true".*$)'
(Get-Content $FileName) -replace $Pattern, "`n*************isActive=true*****************" -replace '<[^>]+?>' -replace '^\s*|\s$' | ?{$_} | Set-Content C:\Users\someguy\Desktop\Output.txt
</code>```

So, the main thing here is that I use a look behind to find your pattern text, and then add a new line and the asterisk line to that line. So that the line

```<code>    <SomeTag>ProcessSpecifier = "true"</SomeTag>
</code>```

becomes:

```<code>    <SomeTag>ProcessSpecifier = "true"</SomeTag>`n*************isActive=true*****************
</code>```

When used inside double quote a backtick ` followed by n creates a new line, so the '*************isActive=true*****************' is on its own line immediately following your search pattern line. Past that I remove the XML tags, and then any leading or trailing whitespace from any line.

After the RegEx replacements I pass the result to a Where statement that removes blank lines, and then pass the remaining lines to Set-Content which I've seen better performance out of than Out-File.

Body:
I am trying to make a script that takes an XML file, looks for a matching condition, if it finds it adds a new line of asteriks, then when done going through the file to strip it of all its XML tags and leave the data in a plain text file.

The script has been tested on a small input xml file and works fine, but when I pass a large XML file to it takes forever (not actually sure how long as I ran it for over an hour and still no result so I just stopped it).

I'm guessing I must be performing the work in an extremely inefficient manner, hoping you guys can help me make it fast and efficient.

Here is the script below:

# Takes input XML File, cleans up XML elements, outputs plain text file

$FileName = "C:\Users\someguy\Desktop\input.xml"
$Pattern = "ProcessSpecifier = ""true"""
$FileOriginal = Get-Content $FileName

[String[]] $FileModified = @()
Foreach ($Line in $FileOriginal)
{
    $FileModified += $Line
    if ($Line -match $Pattern)
    {
        #Add Lines after the selected pattern
        $FileModified += "*************isActive=true*****************"
    }
}

$FileModified -replace "<[^>]+>", "" | Out-File C:\Users\someguy\Desktop\Output.txt

Body:
Let's go with a look behind and a bunch of regex to speed things up here. Also, I'm not going to store the whole thing in memory, I'm just going to pass it down the pipeline, which should help. I remove whitespace from the beginning and ends of lines, and filter out blank lines, but you can remove that bit if you want.

# Takes input XML File, cleans up XML elements, outputs plain text file

$FileName = "C:\Users\someguy\Desktop\input.xml"
$Pattern = '(?<=^.*ProcessSpecifier = "true".*$)'
(Get-Content $FileName) -replace $Pattern, "`n*************isActive=true*****************" -replace '<[^>]+?>' -replace '^\s*|\s$' | ?{$_} | Set-Content C:\Users\someguy\Desktop\Output.txt

So, the main thing here is that I use a look behind to find your pattern text, and then add a new line and the asterisk line to that line. So that the line

    <SomeTag>ProcessSpecifier = "true"</SomeTag>

becomes:

    <SomeTag>ProcessSpecifier = "true"</SomeTag>`n*************isActive=true*****************

When used inside double quote a backtick ` followed by n creates a new line, so the '*************isActive=true*****************' is on its own line immediately following your search pattern line. Past that I remove the XML tags, and then any leading or trailing whitespace from any line.

After the RegEx replacements I pass the result to a Where statement that removes blank lines, and then pass the remaining lines to Set-Content which I've seen better performance out of than Out-File.


问:
SSIS/SSRS-The variable "MyNameSpace::MyVariableName" specified by VariableName property is not a valid variable
Environment: SQL Server 2008 R2

I keep getting this error on a scheduled job running on SQL Server 2008 R2:

```<code>Error: Code: 0xC02020EE     Source: Data Flow Task - Fix Missing this and that Row Count - This Not Fixed [148]     Description: The variable "MyNameSpace::MyVariableName" specified by VariableName property is not a valid variable. Need a valid variable name to write to.  End Error
</code>```

I cannot make out what could be wrong here. The variable is declared in the dtsx like this:

```<code><DTS:Variable>
    <DTS:Property DTS:Name="Expression"/>
    <DTS:Property DTS:Name="EvaluateAsExpression">0</DTS:Property>
    <DTS:Property DTS:Name="NameSpace">MyNameSpace</DTS:Property>
    <DTS:Property DTS:Name="ReadOnly">0</DTS:Property>
    <DTS:Property DTS:Name="RaiseChangedEvent">-1</DTS:Property>
    <DTS:Property DTS:Name="IncludeInDebugDump">6789</DTS:Property>
    <DTS:VariableValue DTS:DataType="3">0</DTS:VariableValue>
    <DTS:Property DTS:Name="ObjectName">MyVariableName</DTS:Property>
    <DTS:Property DTS:Name="DTSID">{F6C30C52-3BDA-45D6-862B-10405215FABC}</DTS:Property>
    <DTS:Property DTS:Name="Description"/>
    <DTS:Property DTS:Name="CreationName"/>
</DTS:Variable>
</code>```

And it is being used like this:

```<code><component id="148" name="Row Count - IDs Not Fixed" componentClassID="{150E6007-7C6A-4CC3-8FF3-FC73783A972E}" description="Counts the rows in a dataset." localeId="-1" usesDispositions="false" validateExternalMetadata="True" version="0" pipelineVersion="0" contactInfo="Row Count;Microsoft Corporation; Microsoft SqlServer v10; (C) Microsoft Corporation; All Rights Reserved; http://www.microsoft.com/sql/support;0">
                    <properties>
                        <property id="149" name="VariableName" dataType="System.String" state="default" isArray="false" description="Specifies the variable to hold the row count." typeConverter="" UITypeEditor="" containsID="false" expressionType="None">MyNameSpace::MyVariableName</property>
                    </properties>
                    <inputs>
                        <input id="150" name="Row Count Input 1" description="" hasSideEffects="true" dangling="false" errorOrTruncationOperation="" errorRowDisposition="NotUsed" truncationRowDisposition="NotUsed">
                            <externalMetadataColumns isUsed="False"/>
                        </input>
                    </inputs>
                    <outputs>
                        <output id="151" name="Row Count Output 1" description="" exclusionGroup="0" synchronousInputId="150" deleteOutputOnPathDetached="false" hasSideEffects="false" dangling="false" isErrorOut="false" isSorted="false" errorOrTruncationOperation="" errorRowDisposition="NotUsed" truncationRowDisposition="NotUsed">
                            <externalMetadataColumns isUsed="False"/>
                        </output>
                    </outputs>
                </component>
</code>```

Can someone help me understand what needs to be corrected to avoid this error? Googling this error has not helped so far.

答:
Your problem is with the namespace "MyNameSpace".  According to books online, only the following two name spaces are allowed:

Namespace

Integration Services provides two namespaces, User and System. By default, custom variables are in the User namespace, and system variables are in the System namespace. You can create additional namespaces for user-defined variables and change the name of the User namespace, but you cannot change the name of the System namespace, add variables to the System namespace, or assign system variables to a different namespace.

Body:
Environment: SQL Server 2008 R2

I keep getting this error on a scheduled job running on SQL Server 2008 R2:

Error: Code: 0xC02020EE     Source: Data Flow Task - Fix Missing this and that Row Count - This Not Fixed [148]     Description: The variable "MyNameSpace::MyVariableName" specified by VariableName property is not a valid variable. Need a valid variable name to write to.  End Error

I cannot make out what could be wrong here. The variable is declared in the dtsx like this:

<DTS:Variable>
    <DTS:Property DTS:Name="Expression"/>
    <DTS:Property DTS:Name="EvaluateAsExpression">0</DTS:Property>
    <DTS:Property DTS:Name="NameSpace">MyNameSpace</DTS:Property>
    <DTS:Property DTS:Name="ReadOnly">0</DTS:Property>
    <DTS:Property DTS:Name="RaiseChangedEvent">-1</DTS:Property>
    <DTS:Property DTS:Name="IncludeInDebugDump">6789</DTS:Property>
    <DTS:VariableValue DTS:DataType="3">0</DTS:VariableValue>
    <DTS:Property DTS:Name="ObjectName">MyVariableName</DTS:Property>
    <DTS:Property DTS:Name="DTSID">{F6C30C52-3BDA-45D6-862B-10405215FABC}</DTS:Property>
    <DTS:Property DTS:Name="Description"/>
    <DTS:Property DTS:Name="CreationName"/>
</DTS:Variable>

And it is being used like this:

<component id="148" name="Row Count - IDs Not Fixed" componentClassID="{150E6007-7C6A-4CC3-8FF3-FC73783A972E}" description="Counts the rows in a dataset." localeId="-1" usesDispositions="false" validateExternalMetadata="True" version="0" pipelineVersion="0" contactInfo="Row Count;Microsoft Corporation; Microsoft SqlServer v10; (C) Microsoft Corporation; All Rights Reserved; http://www.microsoft.com/sql/support;0">
                    <properties>
                        <property id="149" name="VariableName" dataType="System.String" state="default" isArray="false" description="Specifies the variable to hold the row count." typeConverter="" UITypeEditor="" containsID="false" expressionType="None">MyNameSpace::MyVariableName</property>
                    </properties>
                    <inputs>
                        <input id="150" name="Row Count Input 1" description="" hasSideEffects="true" dangling="false" errorOrTruncationOperation="" errorRowDisposition="NotUsed" truncationRowDisposition="NotUsed">
                            <externalMetadataColumns isUsed="False"/>
                        </input>
                    </inputs>
                    <outputs>
                        <output id="151" name="Row Count Output 1" description="" exclusionGroup="0" synchronousInputId="150" deleteOutputOnPathDetached="false" hasSideEffects="false" dangling="false" isErrorOut="false" isSorted="false" errorOrTruncationOperation="" errorRowDisposition="NotUsed" truncationRowDisposition="NotUsed">
                            <externalMetadataColumns isUsed="False"/>
                        </output>
                    </outputs>
                </component>

Can someone help me understand what needs to be corrected to avoid this error? Googling this error has not helped so far.


问:
What code do I need for my Unity character to shoot the bullet correctly?
I am not new to programming, but I am new to C#. I am experienced in Python, Java, and HTML. My game is 2D I have a game where my character currently has to touch the enemy to kill it. Now I added code for shooting a bullet to kill the enemy. I also want the bullet to be shot if the spacebar is pressed. The character is supposed to a shoot bullet in either direction. I have taken my code from an example my professor gave me which was originally Javascript and I converted it to C#. Unity no longer supports Javascript. The example code he gave me was basically a rocket shooting as many bullets as I clicked (clicking the mouse shoots bullets) to eliminate an enemy, however the rocket in that example does not move. In my game, the character moves, so the bullet has to get the position of the character. What is the correct code for getting the character position and shooting a bullet correctly?

I tested my game with my current code. The bullet is being spit out of nowhere (from the bottom of my background wallpaper [smack in the middle of the bottom] to a little below the wallpaper). Not even from the character...
Also, I added the Hit class script to my Bullet category in Unity.

Complete Camera Controller (no issues here at all)

```<code>using UnityEngine;
using System.Collections;

public class CompleteCameraController : MonoBehaviour {

    public GameObject player;       //Public variable to store a reference to the player game object

    private Vector3 offset;         //Private variable to store the offset distance between the player and camera

    // Use this for initialization
    void Start ()
    {
        //Calculate and store the offset value by getting the distance between the player's position and camera's position.
        offset = transform.position - player.transform.position;
    }

    // LateUpdate is called after Update each frame
    void LateUpdate ()
    {
        // Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance.
        transform.position = player.transform.position + offset;
    }
}
</code>```

Complete Player Control Class (If you read the comments in the code that say the "BULLET CODE", that's new code I have placed in the game for the bullets.

```<code>using UnityEngine;
using System.Collections;

//Adding this allows us to access members of the UI namespace including Text.
using UnityEngine.UI;

public class CompletePlayerController : MonoBehaviour
{

    public float speed;             //Floating point variable to store the player's movement speed.
    public Text countText;          //Store a reference to the UI Text component which will display the number of pickups collected.
    public Text winText;            //Store a reference to the UI Text component which will display the 'You win' message.

    private Rigidbody2D rb2d;       //Store a reference to the Rigidbody2D component required to use 2D Physics.
    private int count;              //Integer to store the number of pickups collected so far.
    Rigidbody2D bullet;
    float speed2 = 30f; //BULLET CODE

    // Use this for initialization
    void Start()
    {
        //Get and store a reference to the Rigidbody2D component so that we can access it.
        rb2d = GetComponent<Rigidbody2D> ();

        //Initialize count to zero.
        count = 0;

        //Initialze winText to a blank string since we haven't won yet at beginning.
        winText.text = "";

        //Call our SetCountText function which will update the text with the current value for count.
        SetCountText ();
    }

    //FixedUpdate is called at a fixed interval and is independent of frame rate. Put physics code here.
    void FixedUpdate()
    {
        //Store the current horizontal input in the float moveHorizontal.
        float moveHorizontal = Input.GetAxis ("Horizontal");

        //Store the current vertical input in the float moveVertical.
        float moveVertical = Input.GetAxis ("Vertical");

        Rigidbody2D bulletInstance; //BULLET CODE

        //Use the two store floats to create a new Vector2 variable movement.
        Vector2 movement = new Vector2 (moveHorizontal, moveVertical);

        //Call the AddForce function of our Rigidbody2D rb2d supplying movement multiplied by speed to move our player.
         rb2d.AddForce (movement * speed);

         if(Input.GetKeyDown(KeyCode.Space)&& Hit.hit == false) //BULLET CODE IN HERE
        {
            // ... instantiate the bullet facing right and set it's velocity to the right.
            bulletInstance = Instantiate(bullet, transform.position, Quaternion.Euler(new Vector3(0,0,0)));
            bulletInstance.velocity = new Vector2(speed2, 0);
            bulletInstance.name = "Bullet";
        }

    }

    //OnTriggerEnter2D is called whenever this object overlaps with a trigger collider.
    void OnTriggerEnter2D(Collider2D other)
    {
        //Check the provided Collider2D parameter other to see if it is tagged "PickUp", if it is...
        if (other.gameObject.CompareTag ("PickUp"))
        {
            //... then set the other object we just collided with to inactive.
            other.gameObject.SetActive(false);

            transform.localScale += new Vector3(0.1f, 0.1f, 0);

            //Add one to the current value of our count variable.
            count = count + 1;

            //Update the currently displayed count by calling the SetCountText function.
            SetCountText ();
        }

    }

    //This function updates the text displaying the number of objects we've collected and displays our victory message if we've collected all of them.
    void SetCountText()
    {
        //Set the text property of our our countText object to "Count: " followed by the number stored in our count variable.
        countText.text = "Count: " + count.ToString ();

        //Check if we've collected all 12 pickups. If we have...
        if (count >= 12)
            //... then set the text property of our winText object to "You win!"
            winText.text = "You win!";
    }
}
</code>```

Hit code. All code in this class is made for the bullet.

```<code>using UnityEngine;
using System.Collections;

public class Hit : MonoBehaviour
{

    GameObject[] gameObjects;
    public static bool hit = false;

    void  Removal ()
    {

    gameObjects =  GameObject.FindGameObjectsWithTag("Bullet");

    for(var i= 0 ; i < gameObjects.Length ; i ++)
        Destroy(gameObjects[i]);
    }

    void  OnCollisionEnter2D ( Collision2D other  )
    {
        if(other.gameObject.name=="Bullet")
        {
            Removal();
            Destroy(gameObject);
            hit = true;

        }
    }
}
</code>```

答:
Perhaps the problem has to do with the player's parent transform. You could try something like this to make sure the bullet has the right parent:

```<code>bulletInstance = Instantiate(bullet);
bulletInstance.transform.parent = transform.parent;
bulletInstance.transform.position = transform.position;
bulletInstance.velocity = new Vector2(speed2, 0);
bulletInstance.name = "Bullet";
</code>```

If that doesn't work it may be worthwhile to check the player's Rect Transform to see where the anchors and pivot are. Perhaps the player's actual "position" coordinates aren't where you think they are.

Have you done the Space Shooter tutorial? It has a segment about shooting bullets.

Body:
I am not new to programming, but I am new to C#. I am experienced in Python, Java, and HTML. My game is 2D I have a game where my character currently has to touch the enemy to kill it. Now I added code for shooting a bullet to kill the enemy. I also want the bullet to be shot if the spacebar is pressed. The character is supposed to a shoot bullet in either direction. I have taken my code from an example my professor gave me which was originally Javascript and I converted it to C#. Unity no longer supports Javascript. The example code he gave me was basically a rocket shooting as many bullets as I clicked (clicking the mouse shoots bullets) to eliminate an enemy, however the rocket in that example does not move. In my game, the character moves, so the bullet has to get the position of the character. What is the correct code for getting the character position and shooting a bullet correctly?

I tested my game with my current code. The bullet is being spit out of nowhere (from the bottom of my background wallpaper [smack in the middle of the bottom] to a little below the wallpaper). Not even from the character...
Also, I added the Hit class script to my Bullet category in Unity.

Complete Camera Controller (no issues here at all)

using UnityEngine;
using System.Collections;

public class CompleteCameraController : MonoBehaviour {

    public GameObject player;       //Public variable to store a reference to the player game object

    private Vector3 offset;         //Private variable to store the offset distance between the player and camera

    // Use this for initialization
    void Start ()
    {
        //Calculate and store the offset value by getting the distance between the player's position and camera's position.
        offset = transform.position - player.transform.position;
    }

    // LateUpdate is called after Update each frame
    void LateUpdate ()
    {
        // Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance.
        transform.position = player.transform.position + offset;
    }
}

Complete Player Control Class (If you read the comments in the code that say the "BULLET CODE", that's new code I have placed in the game for the bullets.

using UnityEngine;
using System.Collections;

//Adding this allows us to access members of the UI namespace including Text.
using UnityEngine.UI;

public class CompletePlayerController : MonoBehaviour
{

    public float speed;             //Floating point variable to store the player's movement speed.
    public Text countText;          //Store a reference to the UI Text component which will display the number of pickups collected.
    public Text winText;            //Store a reference to the UI Text component which will display the 'You win' message.

    private Rigidbody2D rb2d;       //Store a reference to the Rigidbody2D component required to use 2D Physics.
    private int count;              //Integer to store the number of pickups collected so far.
    Rigidbody2D bullet;
    float speed2 = 30f; //BULLET CODE

    // Use this for initialization
    void Start()
    {
        //Get and store a reference to the Rigidbody2D component so that we can access it.
        rb2d = GetComponent<Rigidbody2D> ();

        //Initialize count to zero.
        count = 0;

        //Initialze winText to a blank string since we haven't won yet at beginning.
        winText.text = "";

        //Call our SetCountText function which will update the text with the current value for count.
        SetCountText ();
    }

    //FixedUpdate is called at a fixed interval and is independent of frame rate. Put physics code here.
    void FixedUpdate()
    {
        //Store the current horizontal input in the float moveHorizontal.
        float moveHorizontal = Input.GetAxis ("Horizontal");

        //Store the current vertical input in the float moveVertical.
        float moveVertical = Input.GetAxis ("Vertical");

        Rigidbody2D bulletInstance; //BULLET CODE

        //Use the two store floats to create a new Vector2 variable movement.
        Vector2 movement = new Vector2 (moveHorizontal, moveVertical);

        //Call the AddForce function of our Rigidbody2D rb2d supplying movement multiplied by speed to move our player.
         rb2d.AddForce (movement * speed);

         if(Input.GetKeyDown(KeyCode.Space)&& Hit.hit == false) //BULLET CODE IN HERE
        {
            // ... instantiate the bullet facing right and set it's velocity to the right.
            bulletInstance = Instantiate(bullet, transform.position, Quaternion.Euler(new Vector3(0,0,0)));
            bulletInstance.velocity = new Vector2(speed2, 0);
            bulletInstance.name = "Bullet";
        }

    }

    //OnTriggerEnter2D is called whenever this object overlaps with a trigger collider.
    void OnTriggerEnter2D(Collider2D other)
    {
        //Check the provided Collider2D parameter other to see if it is tagged "PickUp", if it is...
        if (other.gameObject.CompareTag ("PickUp"))
        {
            //... then set the other object we just collided with to inactive.
            other.gameObject.SetActive(false);

            transform.localScale += new Vector3(0.1f, 0.1f, 0);

            //Add one to the current value of our count variable.
            count = count + 1;

            //Update the currently displayed count by calling the SetCountText function.
            SetCountText ();
        }

    }

    //This function updates the text displaying the number of objects we've collected and displays our victory message if we've collected all of them.
    void SetCountText()
    {
        //Set the text property of our our countText object to "Count: " followed by the number stored in our count variable.
        countText.text = "Count: " + count.ToString ();

        //Check if we've collected all 12 pickups. If we have...
        if (count >= 12)
            //... then set the text property of our winText object to "You win!"
            winText.text = "You win!";
    }
}

Hit code. All code in this class is made for the bullet.

using UnityEngine;
using System.Collections;

public class Hit : MonoBehaviour
{

    GameObject[] gameObjects;
    public static bool hit = false;

    void  Removal ()
    {

    gameObjects =  GameObject.FindGameObjectsWithTag("Bullet");

    for(var i= 0 ; i < gameObjects.Length ; i ++)
        Destroy(gameObjects[i]);
    }

    void  OnCollisionEnter2D ( Collision2D other  )
    {
        if(other.gameObject.name=="Bullet")
        {
            Removal();
            Destroy(gameObject);
            hit = true;

        }
    }
}

Body:
Perhaps the problem has to do with the player's parent transform. You could try something like this to make sure the bullet has the right parent:

bulletInstance = Instantiate(bullet);
bulletInstance.transform.parent = transform.parent;
bulletInstance.transform.position = transform.position;
bulletInstance.velocity = new Vector2(speed2, 0);
bulletInstance.name = "Bullet";

If that doesn't work it may be worthwhile to check the player's Rect Transform to see where the anchors and pivot are. Perhaps the player's actual "position" coordinates aren't where you think they are.

Have you done the Space Shooter tutorial? It has a segment about shooting bullets.