问:
Could not delete /.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/appname/WEB-INF/lib. May be locked by another process
I am trying to run an web app. In the beginning it was going well, but I had to delete some jars from the project folder. I didn't delete the jars using eclipse. So, I started to get these errors:

```<code>Publishing failed with multiple errors
Could not delete C:/Users/maniceto/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/fj21-tarefas/WEB-INF/lib. May be locked by another process.
Could not delete C:/Users/maniceto/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/fj21-tarefas/WEB-INF. May be locked by another process.
</code>```

I tried to delete my whole project and code it again. But it doesn't work. I also deleted the Tomcat server but again it doesn't work. Then I realized that to "fix" this problem I have to delete this folder:

C:/Users/maniceto/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/fj21-tarefas/WEB-INF.

And clean the server and the project. But when I close eclipse and open again I get the same error, then I have to do this process.

Anyone here knows how to fix this kind of tomcat bug?

答:
there is already a post which answer this question you need to:

Clean Server

Clean Tomcat Work Directory

link to the page:  Why is my publishing failing in Tomcat v7.0 Server because of locks by another process?

ContentLicense: CC BY-SA 4.0

Body:
I am trying to run an web app. In the beginning it was going well, but I had to delete some jars from the project folder. I didn't delete the jars using eclipse. So, I started to get these errors:

Publishing failed with multiple errors
Could not delete C:/Users/maniceto/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/fj21-tarefas/WEB-INF/lib. May be locked by another process.
Could not delete C:/Users/maniceto/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/fj21-tarefas/WEB-INF. May be locked by another process.

I tried to delete my whole project and code it again. But it doesn't work. I also deleted the Tomcat server but again it doesn't work. Then I realized that to "fix" this problem I have to delete this folder:

C:/Users/maniceto/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/fj21-tarefas/WEB-INF.

And clean the server and the project. But when I close eclipse and open again I get the same error, then I have to do this process.

Anyone here knows how to fix this kind of tomcat bug?


来源: stackexchange

问:
Spring can't find a lib and webapp doesn't start up in tomcat 6
I've this problem using STS: I'm building a simple Spring app, just to try out features like MVC and persistence. Now I've created something very simple, out of a bunch of tutorials for Spring 3, that I'm using. The application fails with this, during server startup:

Code:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean] for bean with name 'mySessionFactory' defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean

but I've org.springframework.orm in web-inf/classes folder (I even tried putting it in web-inf/lib). As I copied these libs there, the came out in Web App Libraries folder. Building this project in STS works fine as this dependency is set up in build path throught project properties, but how do I transfer the libs to the web app? (I'm using Tomcat 6 as it is the server I'm going to use sometime in the future for production). Is this a config problem of my XML? Or am I just missing the right way to put this lib? (I encountered the same problem before, but adding the needed lib in classes worked it out). More than this I that if I browse inside my workspace to the folder where the working folder of tomcat should be, I can't find any work directory and any commo

答:
Go to the Servers view and double click on Tomcat Server which will open up a Tomcat Overview page. This will show you the server path and deploy path which Eclipse is using to publish your webapps to.

For example, mine are:

Server path: .metadata\.plugins\org.eclipse.wst.server.core\tmp0

Deploy path: wtpwebapps

Now in a Command Prompt (or Explorer) browse to %ECLIPSE_HOME%\workspaces\default\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps and you should see your webapp. Go into the WEB-INF\lib directory and check if your jar is there.

A few things to try:

If the jar is not in WEB-INF\lib, you might need to republish it. Right-click on the Tomcat in the Servers view and click Publish. Does it appear? If not, Right-click on the Tomcat again and this time select Clean... which will clean out everything and republish. If this doesn't work, the brute force approach would be to delete the files manually and then tell Eclipse to republish them.

Clean your work directory, by right-clicking the webapp under Tomcat in the Servers view and selecting Clean module work directory. Or do it manually by deleting from %ECLIPSE_HOME%\workspaces\default\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost

You should also try closing-reopening/cleaning/rebuilding/refreshing your webapp project just in case Eclipse hasn't picked up the changes.

ContentLicense: CC BY-SA 2.5


问:
compose() vs. transform() vs. as() vs. map() in Flux and Mono
Recently, I decided to try spring 5 with projectreactor.io (io.projectreactor:3.1.1).

Does anyone know what the best case of using this functions? What cons and pros of using each of them and where they should be used?

Good examples will be helpful.

答:
You have two broadly different categories of operators here:

Operators that work on the Flux itself

transform and transformDeferred are for code mutualization

When you compose chains of operators regularly and you have common operator usage patterns in your application, you can mutualize this code or give it a more descriptive name by using transform and transformDeferred.

The difference between the two is when the mutualized operators are applied: transform applies them at instantiation, while transformDeferred applies them at subscription (allowing for dynamic choice of the added operators).

Have a look at the reference documentation for more details and examples.

note: transformDeferred was called compose in versions prior to 3.3.0

as

This is a convenience shortcut to apply a Function to the whole Flux while keeping the whole code in a fluent style.

The major differentiator with transform* operators is that this one doesn't enforce a particular return type. It is all driven by the Function you use, and could for instance be used for testing with a StepVerifier in a fluent style:

```<code>Flux.just("test")
    .map(String::length)
    .as(StepVerifier::create)
    //from there on we're dealing with the StepVerifier API
    .expectNext(4)
    .verifyComplete();
</code>```

The example shown in the javadoc uses this approach to convert to a Mono using Mono::from, which is a bit confusing because the return type is quite close to Flux.

Note that this approach can also helps with external operators that are implemented in a factory method style to "extend" the Flux API

Take reactor-addons MathFlux for example, and compare:

```<code>MathFlux.sumInt(Flux.range(1, 10)
                    .map(i -> i + 2)
                    .map(i -> i * 10))
        .map(isum -> "sum=" + isum);
</code>```

To:

```<code>Flux.range(1, 10)
    .map(i -> i + 2)
    .map(i -> i * 10)
    .as(MathFlux::sumInt)
    .map(isum -> "sum=" + isum)
</code>```

(this can help you deal with the fact that, unlike Kotlin, Java doesn't have extension methods :) )

Operator that works on the data that goes through the Flux

map is all about the data. It applies a 1-1 transformation function to each element in the source, as they become available.

In the MathFlux example above, map is successively used to add 2 to each original integer, then again to multiply each number in the sequence by 10, then a third time at the end to produce a String out of each sum.

Body:
You have two broadly different categories of operators here:

Operators that work on the Flux itself

transform and transformDeferred are for code mutualization

When you compose chains of operators regularly and you have common operator usage patterns in your application, you can mutualize this code or give it a more descriptive name by using transform and transformDeferred.

The difference between the two is when the mutualized operators are applied: transform applies them at instantiation, while transformDeferred applies them at subscription (allowing for dynamic choice of the added operators).

Have a look at the reference documentation for more details and examples.

note: transformDeferred was called compose in versions prior to 3.3.0

as

This is a convenience shortcut to apply a Function to the whole Flux while keeping the whole code in a fluent style.

The major differentiator with transform* operators is that this one doesn't enforce a particular return type. It is all driven by the Function you use, and could for instance be used for testing with a StepVerifier in a fluent style:

Flux.just("test")
    .map(String::length)
    .as(StepVerifier::create)
    //from there on we're dealing with the StepVerifier API
    .expectNext(4)
    .verifyComplete();

The example shown in the javadoc uses this approach to convert to a Mono using Mono::from, which is a bit confusing because the return type is quite close to Flux.

Note that this approach can also helps with external operators that are implemented in a factory method style to "extend" the Flux API

Take reactor-addons MathFlux for example, and compare:

MathFlux.sumInt(Flux.range(1, 10)
                    .map(i -> i + 2)
                    .map(i -> i * 10))
        .map(isum -> "sum=" + isum);

To:

Flux.range(1, 10)
    .map(i -> i + 2)
    .map(i -> i * 10)
    .as(MathFlux::sumInt)
    .map(isum -> "sum=" + isum)

(this can help you deal with the fact that, unlike Kotlin, Java doesn't have extension methods :) )

Operator that works on the data that goes through the Flux

map is all about the data. It applies a 1-1 transformation function to each element in the source, as they become available.

In the MathFlux example above, map is successively used to add 2 to each original integer, then again to multiply each number in the sequence by 10, then a third time at the end to produce a String out of each sum.


问:
regular expression pattern replacement *.xml
I am new to regular expression, and don't deal with it regularly so posting it as a question.

I want to replace

```<code>blah.xml
haha.xml
</code>```

to

```<code>user/home/blah.xml
user/home/haha.xml
</code>```

I would prefer to do it with sed.

Cheers

SK

Body:
I am new to regular expression, and don't deal with it regularly so posting it as a question.

I want to replace

blah.xml
haha.xml

to

user/home/blah.xml
user/home/haha.xml

I would prefer to do it with sed.

Cheers

SK

Body: sed 's=\(.*\.xml\)=user/home/\1=g'


问:
Using a photo as
 in CSS
In my school, they said this was the way to go if we used an image as a title with a special font for ex. Now, I'm trying this but I don't really understand

1) why you should do it

2) it doesn't seem to show up unless it is given a specific height.

Can someone show me a better way to do it, while still doing this

 thing?

.title{
  background-image: url(...);
  background-repeat: no-repeat;
  /*it displays nothing now, only when I add a height here*/
}

.titlespan{
  visibility: hidden;
}
```

<pre class="lang-html prettyprint-override"><code><h1 class="title"><span class="titlespan"></span></h1>
</code>```

答:
If you want display an image instead of the text, that's enough for you:

h1 {
  background-image: url(...);
  background-repeat: no-repeat;
  width: 100px /* Image width */;
  height: 25px /* Image height*/;
  text-indent: -9999px; /* This hide text*/;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Title</h1></code>```

This technique is used to have a "SEO Friendly" text for the search engines, showing the user an image.

ContentLicense: CC BY-SA 3.0

Title: Using a photo as <h1> in CSS

Body:
If you want display an image instead of the text, that's enough for you:

h1 {
  background-image: url(...);
  background-repeat: no-repeat;
  width: 100px /* Image width */;
  height: 25px /* Image height*/;
  text-indent: -9999px; /* This hide text*/;
}

<h1>Title</h1>

This technique is used to have a "SEO Friendly" text for the search engines, showing the user an image.


问:
TypeScript create a class with properties that are known in runtime
I get the following response from a REST-Service:

```<code>[{
  "id": "1",
  "name": "Jon Doe"
  "paymentInformation": {
    "cc": {
      "type": "visa",
      "number": "123456789"
    },
    "btc": {
      "address": "123asdsa12d4as6d54sad23"
    },
    "bank-wire": {
      "bank-name": "Best Bank",
      "IBAN": "123456789987654321",
      "BIC": "47114711123",
      "Owner": "Jon Doe"
    }
  }
},{...}
]
</code>```

Every Object is a customer.

My main problem is to create a class which is should represent the paymentInformation.
I will know the keys at runtime (when I get the json response).

How can I create such a class in TypeScript?

That's what I currently have:

```<code>export class Customer {
  constructor(
    public id: number,
    public name: string,
    public paymentInformation: PaymentInformation)   { }
}
</code>```

答:
If the data you have shown is the correct shape of the data, but where the actual keys are likely to differ, what you have is:

An indexer, that returns... another indexer that returns strings.

On in TypeScript:

```<code>interface PaymentInformation {
    [key: string]: { [key: string]: string };
}
</code>```

This is quite a wide type, it will only check that:

Level 1 keys are strings

Level 1 values are indexers... that match:

Level 2 keys are strings

Level 2 values are strings

For example:

```<code>const paymentInfo: PaymentInformation = {
    "str": {
        "str2": "value",
        "other": "val"
    },
    "another": {
        "so on": "etc"
    }
};
</code>```

Body:
I get the following response from a REST-Service:

[{
  "id": "1",
  "name": "Jon Doe"
  "paymentInformation": {
    "cc": {
      "type": "visa",
      "number": "123456789"
    },
    "btc": {
      "address": "123asdsa12d4as6d54sad23"
    },
    "bank-wire": {
      "bank-name": "Best Bank",
      "IBAN": "123456789987654321",
      "BIC": "47114711123",
      "Owner": "Jon Doe"
    }
  }
},{...}
]

Every Object is a customer.

My main problem is to create a class which is should represent the paymentInformation.
I will know the keys at runtime (when I get the json response).

How can I create such a class in TypeScript?

That's what I currently have:

export class Customer {
  constructor(
    public id: number,
    public name: string,
    public paymentInformation: PaymentInformation)   { }
}

Body:
If the data you have shown is the correct shape of the data, but where the actual keys are likely to differ, what you have is:

An indexer, that returns... another indexer that returns strings.

On in TypeScript:

interface PaymentInformation {
    [key: string]: { [key: string]: string };
}

This is quite a wide type, it will only check that:

Level 1 keys are strings

Level 1 values are indexers... that match:

Level 2 keys are strings

Level 2 values are strings

For example:

const paymentInfo: PaymentInformation = {
    "str": {
        "str2": "value",
        "other": "val"
    },
    "another": {
        "so on": "etc"
    }
};


问:
AccountManager and signature check
Security tips chapter related to AccountManager mentions that:

If credentials are used only by applications that you create, you can
  verify the application that accesses the AccountManager using
  checkSignature().

Where in the code should I check the signature? I've already tried to use Binder.getCallingUid() to obtain the UID of the calling process inside my own implementation of the AbstractAccountAuthenticator, but it returns 1000 as the system process performs IPC. I need to obtain UID/package name of the other app that tries to access the account created by my app as I want to perform the checkSignature check before returning the auth token.

答:
Turns out it's fairly simple. The package name, uid and pid of the real caller is contained in the Bundle passed as a parameter. This code should reside in the implementation of an AbstractAccountAuthenticator.

```<code>public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account,
                           String authTokenType, Bundle bundle) {
    try {
        PackageManager packageManager = context.getPackageManager();
        String callerPackageName = bundle.getString("androidPackageName");
        // Caller app must be signed with the same key to get the auth token
        int signatureResult = packageManager.checkSignatures(BuildConfig.APPLICATION_ID,
                callerPackageName);
        if (signatureResult >= PackageManager.SIGNATURE_MATCH) {
            return [bundle with the auth token];
        } else {
            return Bundle.EMPTY;
        }
}
</code>```

Title: AccountManager and signature check

Body:
Turns out it's fairly simple. The package name, uid and pid of the real caller is contained in the Bundle passed as a parameter. This code should reside in the implementation of an AbstractAccountAuthenticator.

public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account,
                           String authTokenType, Bundle bundle) {
    try {
        PackageManager packageManager = context.getPackageManager();
        String callerPackageName = bundle.getString("androidPackageName");
        // Caller app must be signed with the same key to get the auth token
        int signatureResult = packageManager.checkSignatures(BuildConfig.APPLICATION_ID,
                callerPackageName);
        if (signatureResult >= PackageManager.SIGNATURE_MATCH) {
            return [bundle with the auth token];
        } else {
            return Bundle.EMPTY;
        }
}


问:
android settext for textview from relative weakreference
I have an Activity and an inner class with name InnerClass in it which its updateAfterDelay() method must update a TextView . I want to avoid memory leak. So I changed InnerClass to static and try to use WeakReference like this:

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

    TextView textView;

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

        textView = (TextView) findViewById ( R.id.textView );
    }

    private static class InnerClass {

        private final WeakReference<TextView> targetTextView;

        public InnerClass(TextView targetTextView) {
            this.targetTextView = new WeakReference<TextView> ( targetTextView );
        }

        void updateAfterDelay() {
            targetTextView.setText ( "text" );
        }

    }

}
</code>```

But on targetTextView.setText ( "text" ); I get this compile error:

```<code>cannot resolve method 'setText(java.lang.String)'
</code>```

How I can solve above problem?

答: It must be targetTextView.get().setText("").

Body:
I have an Activity and an inner class with name InnerClass in it which its updateAfterDelay() method must update a TextView . I want to avoid memory leak. So I changed InnerClass to static and try to use WeakReference like this:

public class MainActivity extends Activity {

    TextView textView;

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

        textView = (TextView) findViewById ( R.id.textView );
    }

    private static class InnerClass {

        private final WeakReference<TextView> targetTextView;

        public InnerClass(TextView targetTextView) {
            this.targetTextView = new WeakReference<TextView> ( targetTextView );
        }

        void updateAfterDelay() {
            targetTextView.setText ( "text" );
        }

    }

}

But on targetTextView.setText ( "text" ); I get this compile error:

cannot resolve method 'setText(java.lang.String)'

How I can solve above problem?


答:
As long as there is content it will work, or you will have to give a height/width

.title{
  background-image: url(https://media-exp1.licdn.com/media/AAEAAQAAAAAAAANbAAAAJDE5NjBkNDk1LTY3ZGQtNDA0NS04YTJiLTdkNmU3NjZiNjI3Mg.png);
  background-repeat: no-repeat;
  /*it displays nothing now, only when I add a height here*/
}

.titlespan{
  visibility: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="title"><span class="spantitle">a</br>a</br>a</br>a</br>a</br>a</br>a</br></span></h1></code>```

Title: Using a photo as <h1> in CSS

Body:
In my school, they said this was the way to go if we used an image as a title with a special font for ex. Now, I'm trying this but I don't really understand

1) why you should do it

2) it doesn't seem to show up unless it is given a specific height.

Can someone show me a better way to do it, while still doing this

 thing?

.title{
  background-image: url(...);
  background-repeat: no-repeat;
  /*it displays nothing now, only when I add a height here*/
}

.titlespan{
  visibility: hidden;
}

Body:
As long as there is content it will work, or you will have to give a height/width

.title{
  background-image: url(https://media-exp1.licdn.com/media/AAEAAQAAAAAAAANbAAAAJDE5NjBkNDk1LTY3ZGQtNDA0NS04YTJiLTdkNmU3NjZiNjI3Mg.png);
  background-repeat: no-repeat;
  /*it displays nothing now, only when I add a height here*/
}

.titlespan{
  visibility: hidden;
}

<h1 class="title"><span class="spantitle">a</br>a</br>a</br>a</br>a</br>a</br>a</br></span></h1>


问:
Randomly selecting one episode per ID in long dataset
I have a long format dataset where each ID has multiple episodes, and multiple rows per episode. I would like to select at random just one episode per ID, and all its associated rows.

For example:

```<code>df <- data.frame(id = c(1,1,1,2,2,2,2),
    episode = c(1,2,2,1,1,1,2))
df
  id episode
 1  1       1
 2  1       2
 3  1       2
 4  2       1
 5  2       1
 6  2       1
 7  2       2
</code>```

... And I want to be left with this dataset:

```<code>df2
  id episode
1  1       2
2  1       2
3  2       1
4  2       1
5  2       1
</code>```

答:
Here's an option using base R:

1) sample the original data

```<code>dfsampled <- df[sample(seq_len(nrow(df))),]
</code>```

2) merge non-duplicated sample data with original data:

```<code>merge(dfsampled[!duplicated(dfsampled$id),], df, all.x = TRUE)

#  id episode
#1  1       2
#2  1       2
#3  2       1
#4  2       1
#5  2       1
</code>```

And a dplyr-approach:

```<code>library(dplyr)
df %>% group_by(id) %>% filter(episode == sample(unique(episode), 1))
# A tibble: 5 x 2
# Groups:   id [2]
     id episode
  <dbl>   <dbl>
1     1       2
2     1       2
3     2       1
4     2       1
5     2       1
</code>```

Body:
I have a long format dataset where each ID has multiple episodes, and multiple rows per episode. I would like to select at random just one episode per ID, and all its associated rows.

For example:

df <- data.frame(id = c(1,1,1,2,2,2,2),
    episode = c(1,2,2,1,1,1,2))
df
  id episode
 1  1       1
 2  1       2
 3  1       2
 4  2       1
 5  2       1
 6  2       1
 7  2       2

... And I want to be left with this dataset:

df2
  id episode
1  1       2
2  1       2
3  2       1
4  2       1
5  2       1

Body:
Here's an option using base R:

1) sample the original data

dfsampled <- df[sample(seq_len(nrow(df))),]

2) merge non-duplicated sample data with original data:

merge(dfsampled[!duplicated(dfsampled$id),], df, all.x = TRUE)

#  id episode
#1  1       2
#2  1       2
#3  2       1
#4  2       1
#5  2       1

And a dplyr-approach:

library(dplyr)
df %>% group_by(id) %>% filter(episode == sample(unique(episode), 1))
# A tibble: 5 x 2
# Groups:   id [2]
     id episode
  <dbl>   <dbl>
1     1       2
2     1       2
3     2       1
4     2       1
5     2       1


问:
How do I set the background color of my main screen in Flutter?
I'm learning Flutter, and I'm starting from the very basics. I'm not using MaterialApp. What's a good way to set the background color of the whole screen?

Here's what I have so far:

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new Center(child: new Text("Hello, World!"));
  }
}
</code>```

Some of my questions are:

What's a basic way to set the background color?

What exactly am I looking at, on the screen? Which code "is" the background? Is there a thing to set the background color on? If not, what's a simple and appropriate "simple background" (in order to paint a background color).

Thanks for the help!

The code above generates a black screen with white text:

答:
I think you need to use MaterialApp widget and use theme and set  primarySwatch with color that you want. look like below code,

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
</code>```

Body:
I'm learning Flutter, and I'm starting from the very basics. I'm not using MaterialApp. What's a good way to set the background color of the whole screen?

Here's what I have so far:

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new Center(child: new Text("Hello, World!"));
  }
}

Some of my questions are:

What's a basic way to set the background color?

What exactly am I looking at, on the screen? Which code "is" the background? Is there a thing to set the background color on? If not, what's a simple and appropriate "simple background" (in order to paint a background color).

Thanks for the help!

The code above generates a black screen with white text:

Body:
I think you need to use MaterialApp widget and use theme and set  primarySwatch with color that you want. look like below code,

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}


问:
Process the result of C++ .dll call in C#
I would like to ask your guidance of how to call a C++ .dll from C# and process/share the result with C#.

Let's say I have a call e.g processFile which returns a struct called ResultDetails. How can I share/use this object in C# given that I use CMake and preferrably mingw-gcc.

(Probably I won't be able to share the object as it is, but is it possible to somehow serialize it to a C# compatible format and desirialize it in C#.(I would not prefer to serialize the result to JSON write it to a file and read it from C#.))

Sample c++ header

```<code>ResultDetails* processFile(char *filePath);

struct ResultDetails {
    std::vector<std:Exception> exceptions;
    Geometry geometry;
    std::vector<Surfaces> surfaces;
}
</code>```

Any idea is appreciated,
Thank you for your time and patient

答:
Actually, it looks like a .NET matter. If you turn your library into a CLR project (i.e. compile it as a mixed assembly), you can easily (more or less) wrap your struct inside a .NET one, which in turn will be available to whatever C# client that would use it.

I think you can start from here: https://learn.microsoft.com/en-us/cpp/dotnet/mixed-native-and-managed-assemblies

Body:
I would like to ask your guidance of how to call a C++ .dll from C# and process/share the result with C#.

Let's say I have a call e.g processFile which returns a struct called ResultDetails. How can I share/use this object in C# given that I use CMake and preferrably mingw-gcc.

(Probably I won't be able to share the object as it is, but is it possible to somehow serialize it to a C# compatible format and desirialize it in C#.(I would not prefer to serialize the result to JSON write it to a file and read it from C#.))

Sample c++ header

ResultDetails* processFile(char *filePath);

struct ResultDetails {
    std::vector<std:Exception> exceptions;
    Geometry geometry;
    std::vector<Surfaces> surfaces;
}

Any idea is appreciated,
Thank you for your time and patient


问:
Hover dosnt fit in my navigation because every icon has a different size
I'm looking for a solution to this problem: I have a vertical navigation and in this the icons I've used have different sizes but I "fixed" that by resizing them with different IDs. Now I want a :hover effect on them. But because of the different sizes of the icons the hover dosnt fit my navigation border. I want them do behave like this: https://www.w3schools.com/w3css/tryw3css_templates_dark_portfolio.htm
Can somebody help me with this?

```<code>  <nav class="hidden-mobile" id="menue">
  <div class="navItem">
  <img src="./img/home_website.png" class="icon" class="current" id="homeicon"><br>
  <a class="icontitle" href="./fotowand.html">HOME</a>
  <div class="after"></div>
</div>
  <div class="navItem">
  <img src="./img/studieninteressierte.png"class="icon"><br>
   <a class="icontitle" href="">STUDIEN-<br>INTERESSIERTE</a>
   <div class="after"></div>
 </div>
  <div class="navItem">
   <img src="./img/studierende.png" class="icon" id="studierendeicon"><br>
   <a class="icontitle" href="">STUDIERENDE</a>
   <div class="after"></div>
 </div>
 <div class="navItem">
  <img src="./img/unternehmen.png" class="icon" id="unternehmenicon"><br>
   <a class="icontitle" href="">UNTERNEHMEN</a>
   <div class="after"></div>
 </div>
   <div class="navItem">
   <img src="./img/kontakt.png" class="icon"><br>
   <a class="icontitle" href="">KONTAKT</a>
   <div class="after"></div>
 </div>
</nav>
</code>```

This is my CSS

```<code>  .navItem {
  text-align: center;
  display: inline-block;
  position: relative;
  margin-right: 1em;
  margin-bottom: 1em;
}

.icon {
  width:80px;
}

.after {
  position: absolute;
  top: 0;
  left: 0;
  width:200px;
  height: 100px;
  display: none;
  text-align: center;

  color: white;

}

.navItem:hover .after {
 background-color: rgba(0, 0, 0, .6);
 display: block;
 left:0px;
}
</code>```

Navigation Screenshot

Navigation Screenshot

答:
Try this:

You need to remove the width and height which you have specified after class.

You can directly give :hover of navItem.

Attached working copy.

.navItem {
  text-align: center;
  display: inline-block;
  position: relative;
  margin-right: 1em;
  margin-bottom: 1em;
}

.icon {
  width:80px;
}

.after {
  position: absolute;
  top: 0;
  left: 0;

  display: none;
  text-align: center;

  color: white;

}

.navItem:hover {
    background: rgba(0, 0, 0, .6);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="hidden-mobile" id="menue">
  <div class="navItem">
  <img src="./img/home_website.png" class="icon" class="current" id="homeicon"><br>
  HOME
  <div class="after"></div>
</div>
  <div class="navItem">
  <img src="./img/studieninteressierte.png"class="icon"><br>
   STUDIEN-<br>INTERESSIERTE
   <div class="after"></div>
 </div>
  <div class="navItem">
   <img src="./img/studierende.png" class="icon" id="studierendeicon"><br>
   STUDIERENDE
   <div class="after"></div>
 </div>
 <div class="navItem">
  <img src="./img/unternehmen.png" class="icon" id="unternehmenicon"><br>
   UNTERNEHMEN
   <div class="after"></div>
 </div>
   <div class="navItem">
   <img src="./img/kontakt.png" class="icon"><br>
   KONTAKT
   <div class="after"></div>
 </div>
</nav></code>```

I hope this will be helpful to you. Good luck!

Body:
I'm looking for a solution to this problem: I have a vertical navigation and in this the icons I've used have different sizes but I "fixed" that by resizing them with different IDs. Now I want a :hover effect on them. But because of the different sizes of the icons the hover dosnt fit my navigation border. I want them do behave like this: https://www.w3schools.com/w3css/tryw3css_templates_dark_portfolio.htm
Can somebody help me with this?

  HOME

   STUDIEN-
INTERESSIERTE

   STUDIERENDE

   UNTERNEHMEN

   KONTAKT

This is my CSS

  .navItem {
  text-align: center;
  display: inline-block;
  position: relative;
  margin-right: 1em;
  margin-bottom: 1em;
}

.icon {
  width:80px;
}

.after {
  position: absolute;
  top: 0;
  left: 0;
  width:200px;
  height: 100px;
  display: none;
  text-align: center;

  color: white;

}

.navItem:hover .after {
 background-color: rgba(0, 0, 0, .6);
 display: block;
 left:0px;
}

Navigation Screenshot

Navigation Screenshot

Body:
Try this:

You need to remove the width and height which you have specified after class.

You can directly give :hover of navItem.

Attached working copy.

.navItem {
  text-align: center;
  display: inline-block;
  position: relative;
  margin-right: 1em;
  margin-bottom: 1em;
}

.icon {
  width:80px;
}

.after {
  position: absolute;
  top: 0;
  left: 0;

  display: none;
  text-align: center;

  color: white;

}

.navItem:hover {
    background: rgba(0, 0, 0, .6);
}

<nav class="hidden-mobile" id="menue">
  <div class="navItem">
  <img src="./img/home_website.png" class="icon" class="current" id="homeicon"><br>
  <a class="icontitle" href="./fotowand.html">HOME</a>
  <div class="after"></div>
</div>
  <div class="navItem">
  <img src="./img/studieninteressierte.png"class="icon"><br>
   <a class="icontitle" href="">STUDIEN-<br>INTERESSIERTE</a>
   <div class="after"></div>
 </div>
  <div class="navItem">
   <img src="./img/studierende.png" class="icon" id="studierendeicon"><br>
   <a class="icontitle" href="">STUDIERENDE</a>
   <div class="after"></div>
 </div>
 <div class="navItem">
  <img src="./img/unternehmen.png" class="icon" id="unternehmenicon"><br>
   <a class="icontitle" href="">UNTERNEHMEN</a>
   <div class="after"></div>
 </div>
   <div class="navItem">
   <img src="./img/kontakt.png" class="icon"><br>
   <a class="icontitle" href="">KONTAKT</a>
   <div class="after"></div>
 </div>
</nav>

I hope this will be helpful to you. Good luck!


答:
Here is a base R method with ave and subsetting.

```<code>set.seed(1234)
df[df$episode == ave(df$episode, df$id, FUN=function(x) sample(x, size=1)),]
</code>```

Here, ave applies sample to each id, selecting a single episode and returns a vector the length of the number of rows of the data.frame with a single episode per id. The data.frame is subset by comparing the episodes in each id to the returned vector.

This instance returns

```<code>  id episode
1  1       1
4  2       1
5  2       1
6  2       1
</code>```

In data.table, you might do

```<code>library(data.table)
set.seed(1234)
setDT(df)[df[, sample(episode, 1), by=id], on=.(id, "episode"=V1)]
</code>```

This will return the same result as above (except it will be a data.table rather than a data.frame.

Title: Randomly selecting one episode per ID in long dataset

Body:
Here is a base R method with ave and subsetting.

set.seed(1234)
df[df$episode == ave(df$episode, df$id, FUN=function(x) sample(x, size=1)),]

Here, ave applies sample to each id, selecting a single episode and returns a vector the length of the number of rows of the data.frame with a single episode per id. The data.frame is subset by comparing the episodes in each id to the returned vector.

This instance returns

  id episode
1  1       1
4  2       1
5  2       1
6  2       1

In data.table, you might do

library(data.table)
set.seed(1234)
setDT(df)[df[, sample(episode, 1), by=id], on=.(id, "episode"=V1)]

This will return the same result as above (except it will be a data.table rather than a data.frame.


问:
How to add values/names of checkbox to a variable on form submit?
I have a set of checkboxes in a form that has a submit button.

```<code><form name="form" method="POST">
    <input type="checkbox" name="3" value="3">
    <input type="checkbox" name="7" value="7">
    <input type="checkbox" name="5" value="5">
    <input type="checkbox" name="12" value="12">
    <input type="submit" name="submit-form">
</form>

<?php
if (isset($_REQUEST['submit-form'])) {

}
?>
...
</code>```

The names/values that are currently in the code are dynamically generated and need to be kept (either in name or value will do).

When the form is submitted, I want to add the values or names of the checked checkboxes to a PHP variable, separated by commas, as a string.

Any help with the code that I should put in the if brackets would be much appreciated.

Thanks in advance.

答:
If possible, use name="myValues[]", after POST, your $_POST['myValues'] will contain the array of all values that were selected. You can then do implode(",", $_POST['myValues']) to join them into 1 string.

Example:

```<code><form name="form" method="POST">
    <input type="checkbox" name="options[]" value="3">
    <input type="checkbox" name="options[]" value="7">
    <input type="checkbox" name="options[]" value="5">
    <input type="checkbox" name="options[]" value="12">
    <input type="submit" name="submit-form">
</form>
...
<?php
if (isset($_REQUEST['submit-form']) && !empty($_POST['options'])) {
    $myOptions = implode(", ", $_POST['options']);
}
</code>```

?>

Body:
I have a set of checkboxes in a form that has a submit button.

<form name="form" method="POST">
    <input type="checkbox" name="3" value="3">
    <input type="checkbox" name="7" value="7">
    <input type="checkbox" name="5" value="5">
    <input type="checkbox" name="12" value="12">
    <input type="submit" name="submit-form">
</form>

<?php
if (isset($_REQUEST['submit-form'])) {

}
?>
...

The names/values that are currently in the code are dynamically generated and need to be kept (either in name or value will do).

When the form is submitted, I want to add the values or names of the checked checkboxes to a PHP variable, separated by commas, as a string.

Any help with the code that I should put in the if brackets would be much appreciated.

Thanks in advance.

Body:
If possible, use name="myValues[]", after POST, your $_POST['myValues'] will contain the array of all values that were selected. You can then do implode(",", $_POST['myValues']) to join them into 1 string.

Example:

<form name="form" method="POST">
    <input type="checkbox" name="options[]" value="3">
    <input type="checkbox" name="options[]" value="7">
    <input type="checkbox" name="options[]" value="5">
    <input type="checkbox" name="options[]" value="12">
    <input type="submit" name="submit-form">
</form>
...
<?php
if (isset($_REQUEST['submit-form']) && !empty($_POST['options'])) {
    $myOptions = implode(", ", $_POST['options']);
}

?>


问:
Ionic - Error: Cannot find module 'android-versions'
When a try to run

```<code>ionic run android --device
</code>```

I'm getting an error of module:

```<code>Error: Cannot find module 'android-versions'
</code>```

Versions:

```<code>java -version
  java version "1.8.0_144"
Android studio Version 2.3.3
ionic -v
2.2.1
cordova -v
6.5.0
</code>```

答:
If anyone is having this issue while using yarn and even after adding android-versions... it seems that there are differences in yarn/npm files which break...

I ended up removing my node_modules folder, then installing it with npm instead of yarn. It worked!

Body:
When a try to run

ionic run android --device

I'm getting an error of module:

Error: Cannot find module 'android-versions'

Versions:

java -version
  java version "1.8.0_144"
Android studio Version 2.3.3
ionic -v
2.2.1
cordova -v
6.5.0


问:
What's the difference between window.location and document.location?
What's the difference between window.location and document.location? Should both of them reference the same object?</p>

答: Actually I notice a difference in chrome between both , For example if you want to do a navigation to a sandboxed frame from a child frame then you can do this just with document.location but not with window.location</p>


问:
Codeigniter Query: Mysql query convert into codeigniter query format
Please help me How to convert this query into codeigniter query format</p>

```<code>SELECT *
FROM `table1`
LEFT JOIN `table2`
    ON table1.permission_key = table2.permission_key AND
       (table2.role_id is null || table2.role_id="1")
WHERE
    table1.section  ='abc' AND
    table1.sub_section = 'xzy';
</code>```

答:
Hi please try the following</p>

```<code>$this->db->select('table1.*')
    ->from('table1')
    ->join('table2', 'table1.permission_key=table2.permission_key AND (table2.role_id is null OR table2.role_id="1")', 'left')
    ->where('table1.section', 'abc')
    ->where('table1.sub_section', 'xzy')
    ->result_array();
</code>```

Body:
Please help me How to convert this query into codeigniter query format

SELECT *
FROM `table1`
LEFT JOIN `table2`
    ON table1.permission_key = table2.permission_key AND
       (table2.role_id is null || table2.role_id="1")
WHERE
    table1.section  ='abc' AND
    table1.sub_section = 'xzy';

Body:
Hi please try the following

$this->db->select('table1.*')
    ->from('table1')
    ->join('table2', 'table1.permission_key=table2.permission_key AND (table2.role_id is null OR table2.role_id="1")', 'left')
    ->where('table1.section', 'abc')
    ->where('table1.sub_section', 'xzy')
    ->result_array();


问:
Laravel: Eloquent 'more than' and 'lesser than'
I want a Database Query like this in query builder:

SELECT * FROM posts WHERE active = 1 AND published <= '{$now}' LIMIT 5

What I made:

```<code>$now = new Carbon;
$feed = Post::where([
        ['active' => 1],
        ['published' => $now]
    ])
    -> take(5)
    -> get()
    -> toArray();
</code>```

But it's like:

SELECT * FROM posts WHERE active = 1 AND published = '{$now}' LIMIT 5

How to make <, <=, >, >=, <> and LIKE statements with ::where method?

答:
Use like this ['published','>=',$now]

```<code>$now = new Carbon;
$feed = Post::where([
    ['active', '=', '1'],
    ['published','>=',$now]
])
->take(5)
->get()
->toArray();
</code>```

OR use separate where function

```<code>$now = new Carbon;
$feed = Post::where('active', 1)->where('published','>=', $now)
->take(5)
->get()
->toArray();
</code>```

Body:
I want a Database Query like this in query builder:

SELECT * FROM posts WHERE active = 1 AND published <= '{$now}' LIMIT 5

What I made:

$now = new Carbon;
$feed = Post::where([
        ['active' => 1],
        ['published' => $now]
    ])
    -> take(5)
    -> get()
    -> toArray();

But it's like:

SELECT * FROM posts WHERE active = 1 AND published = '{$now}' LIMIT 5

How to make <, <=, >, >=, <> and LIKE statements with ::where method?

Body:
Use like this ['published','>=',$now]

$now = new Carbon;
$feed = Post::where([
    ['active', '=', '1'],
    ['published','>=',$now]
])
->take(5)
->get()
->toArray();

OR use separate where function

$now = new Carbon;
$feed = Post::where('active', 1)->where('published','>=', $now)
->take(5)
->get()
->toArray();


问:
Android AccountManager - limit access to getAuthToken
AccountManager allows apps with the same signature as your Account Authenticator to access Accounts and tokens without granting permissions. If the signature differs, the system will prompt the User to grant the GET_ACCOUNTS permission to the app.

What if you don't want to allow this? Is it possible to limit access to only your apps?

I was hopeful when I read the following, but I am not sure what they mean by this statement or how you would implement the suggestion:

If credentials are to be used only by applications that you create, then you can verify the application which accesses the AccountManager using checkSignature()

https://developer.android.com/training/id-auth/custom_auth.html#Security

答:
Original answer here: AccountManager and signature check

In short:

```<code>public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account,
                       String authTokenType, Bundle bundle) {
try {
    PackageManager packageManager = context.getPackageManager();
    String callerPackageName = bundle.getString("androidPackageName");
    // Caller app must be signed with the same key to get the auth token
    int signatureResult = packageManager.checkSignatures(BuildConfig.APPLICATION_ID,
            callerPackageName);
    if (signatureResult >= PackageManager.SIGNATURE_MATCH) {
        return [bundle with the auth token];
    } else {
        return Bundle.EMPTY;
    }
}
</code>```

Body:
Original answer here: AccountManager and signature check

In short:

public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account,
                       String authTokenType, Bundle bundle) {
try {
    PackageManager packageManager = context.getPackageManager();
    String callerPackageName = bundle.getString("androidPackageName");
    // Caller app must be signed with the same key to get the auth token
    int signatureResult = packageManager.checkSignatures(BuildConfig.APPLICATION_ID,
            callerPackageName);
    if (signatureResult >= PackageManager.SIGNATURE_MATCH) {
        return [bundle with the auth token];
    } else {
        return Bundle.EMPTY;
    }
}


问:
Add params to array request
I have a pretty large array that I would need to parse, but the request changes depending on enabled/disabled parameters.

For example:

```<code>$array['a'][1]['b'][1]['c'][1] = 'asd';
$str = $array['a'][1];

dd($str);
</code>```

This would give me:

```<code>Array
(
    [b] => Array
    (
        [1] => Array
        (
            [c] => Array
            (
                [1] => asd
            )

        )

    )

)
</code>```

Which, of course, is correct. But now, if I know, that I need also the next parameter, I would need to add that like $str = $array['a'][1]['b'];.

But since there are way too many combinations, I wondered, if I can construct the call manually, something like this":

```<code>$str = $array['a'][1];
if ($b) {
    $str .= ['b'][1];
}
if ($c) {
    $str .= ['c'][1];
}

dd($str);
</code>```

Any hints will be appreciated.

PS: I know I can do this with eval, but was really looking for a better solution:

```<code>eval("\$str = \$array$str;");
dd($str);
</code>```

答:
It can be done with Reference

```<code>$string = "['a'][1]['b'][1]";
// Maybe, not optimal, but it's not the point of the code
preg_match_all('/\[\'?([^\]\']+)\'?\]/', $string, $steps);

// "Root" of the array
$p = &$array;

foreach($steps[1] as $s) {
     // Next step with current key
     if (isset($p[$s]) && is_array($p)) $p = &$p[$s];
     else throw new Exception("No such item");
}
// Target value
$str = $p;
</code>```

demo

Title: Add params to array request

Body:
I have a pretty large array that I would need to parse, but the request changes depending on enabled/disabled parameters.

For example:

$array['a'][1]['b'][1]['c'][1] = 'asd';
$str = $array['a'][1];

dd($str);

This would give me:

Array
(
    [b] => Array
    (
        [1] => Array
        (
            [c] => Array
            (
                [1] => asd
            )

        )

    )

)

Which, of course, is correct. But now, if I know, that I need also the next parameter, I would need to add that like $str = $array['a'][1]['b'];.

But since there are way too many combinations, I wondered, if I can construct the call manually, something like this":

$str = $array['a'][1];
if ($b) {
    $str .= ['b'][1];
}
if ($c) {
    $str .= ['c'][1];
}

dd($str);

Any hints will be appreciated.

PS: I know I can do this with eval, but was really looking for a better solution:

eval("\$str = \$array$str;");
dd($str);

Body:
It can be done with Reference

$string = "['a'][1]['b'][1]";
// Maybe, not optimal, but it's not the point of the code
preg_match_all('/\[\'?([^\]\']+)\'?\]/', $string, $steps);

// "Root" of the array
$p = &$array;

foreach($steps[1] as $s) {
     // Next step with current key
     if (isset($p[$s]) && is_array($p)) $p = &$p[$s];
     else throw new Exception("No such item");
}
// Target value
$str = $p;

demo


问:
How to draw bounding box in same aspect ratio with dlib imglab
I use dlib for my project. Basically it detects car in video stream. I use fhog_object_detector of dlib. When do training, it's hard to draw all object with same aspect ratio with dlib imglab tool. I have to draw object in all images, and manually change the object size in created xml file. Am I doing the right way, or it has a better way to do that work? I know dlib have just release a good CNN object detector for multi scale object detection, but because my computer doesn't have a GPU, so I can't use that.
Hope some one have a problem like me, and have found a solution. </p>

答: Draw all the boxes as accurately around each object as you can. You want to have a well annotated dataset.  That is useful in and of itself.  Then, when you load the data for training, adjust the aspect ratios of the loaded boxes in your code before training.  That is also a good time to look for outliers like really small boxes or boxes with extreme aspect ratios as you would probably want to exclude them.</p>


问:
how can i install the packages in r properly and correctly using Rstudio app?
I tried to install "xlsx" package using Rstudio, and i couldn't install it.

I am trying to install my packages using install.packages("xlsxjars").  I already tried doing that from Tools window in Rstudio app, and I tried using the console.

I am using Linux (Gnome 17.04).  I get this error:

input

```<code>install.packages("xlsxjars")
</code>```

output

```<code>Installing package into ‘/home/aim/R/x86_64-pc-linux-gnu-library/3.3’
(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/src/contrib/xlsxjars_0.6.1.tar.gz'
Error in install.packages : error reading from connection
</code>```

答:
I totally agree with the answer of @kissi salim yahia

Just want to add . When you tape in R

```<code>install.packages("your_package")
</code>```

you got some dependencies below.

these one may have troubles sometimes. So just need to install them manually from the SHELL like:

```<code>sudo apt-get install r-cran-your_dependencie
</code>```

Body:
I tried to install "xlsx" package using Rstudio, and i couldn't install it.

I am trying to install my packages using install.packages("xlsxjars").  I already tried doing that from Tools window in Rstudio app, and I tried using the console.

I am using Linux (Gnome 17.04).  I get this error:

input

install.packages("xlsxjars")

output

Installing package into ‘/home/aim/R/x86_64-pc-linux-gnu-library/3.3’
(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/src/contrib/xlsxjars_0.6.1.tar.gz'
Error in install.packages : error reading from connection

Body:
I totally agree with the answer of @kissi salim yahia

Just want to add . When you tape in R

install.packages("your_package")

you got some dependencies below.

these one may have troubles sometimes. So just need to install them manually from the SHELL like:

sudo apt-get install r-cran-your_dependencie


问:
I would like to use Loader manager and its call backs inside broadcast receiver when broadcast fire?
I m not able to get getSupportLoaderManger or getLoaderManager

I m confuse how to resolve this,

```<code>public class MyBroadCastReceiver extends BroadcastReceiver implements LoaderManager.LoaderCallbacks<Cursor> {
    int cpValue;
    private CursorLoader cursorLoader;
    private Context mContext;

    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        mContext.getSupportLoaderManager().initLoader(1, null, context);
    }

    private void doTheTask(MyAsync task, Intent intent) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // Android 4.4 (API 19) and above
            task.execute(intent);
        } else {
            // Android 3.0 to Android 4.3
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, intent);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
        cursorLoader = new CursorLoader(mContext, Uri.parse("content://com.MyApplication.Provider/cte"), null, null, null, null);
        return cursorLoader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
        if (cursor != null) {
            cursor.moveToFirst();
            String res = "0";
            while (!cursor.isAfterLast()) {
                res = cursor.getString(cursor.getColumnIndex("present"));
                cursor.moveToNext();
            }
            cpValue = Integer.valueOf(res);
        } else {
            cpValue = 0;
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> arg0) {
    }
}
</code>```

My Question is So how can i use loaderManager in broadCast it is working fine in activity and fragment.

How Can I use LoaderManager inside the broadCast Receiver?

答:
Please, look at https://developer.android.com/reference/android/app/LoaderManager.html </p>

<p>LoaderManager is only used for Activity and Fragment </p>

Body:
I m not able to get getSupportLoaderManger or getLoaderManager

I m confuse how to resolve this,

public class MyBroadCastReceiver extends BroadcastReceiver implements LoaderManager.LoaderCallbacks<Cursor> {
    int cpValue;
    private CursorLoader cursorLoader;
    private Context mContext;

    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        mContext.getSupportLoaderManager().initLoader(1, null, context);
    }

    private void doTheTask(MyAsync task, Intent intent) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // Android 4.4 (API 19) and above
            task.execute(intent);
        } else {
            // Android 3.0 to Android 4.3
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, intent);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
        cursorLoader = new CursorLoader(mContext, Uri.parse("content://com.MyApplication.Provider/cte"), null, null, null, null);
        return cursorLoader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
        if (cursor != null) {
            cursor.moveToFirst();
            String res = "0";
            while (!cursor.isAfterLast()) {
                res = cursor.getString(cursor.getColumnIndex("present"));
                cursor.moveToNext();
            }
            cpValue = Integer.valueOf(res);
        } else {
            cpValue = 0;
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> arg0) {
    }
}

My Question is So how can i use loaderManager in broadCast it is working fine in activity and fragment.

How Can I use LoaderManager inside the broadCast Receiver?

Body:
Please, look at https://developer.android.com/reference/android/app/LoaderManager.html

LoaderManager is only used for Activity and Fragment


问:
regular expression pattern replacement *.xml
I am new to regular expression, and don't deal with it regularly so posting it as a question.

I want to replace

```<code>blah.xml
haha.xml
</code>```

to

```<code>user/home/blah.xml
user/home/haha.xml
</code>```

I would prefer to do it with sed.

Cheers

SK

答:
You can use sed as:

```<code>$ cat file
foo
blah.xml
haha.xml
bar
$ sed -r 's#([^.]*\.xml)#user/home/\1#g' file
foo
user/home/blah.xml
user/home/haha.xml
bar
</code>```

To answer your question in the comments, try:

```<code>$ echo "file is blah.xml" | sed -r 's#(\w+\.xml)#user/home/\1#'
file is user/home/blah.xml
</code>```

Body:
I am new to regular expression, and don't deal with it regularly so posting it as a question.

I want to replace

blah.xml
haha.xml

to

user/home/blah.xml
user/home/haha.xml

I would prefer to do it with sed.

Cheers

SK

Body:
You can use sed as:

$ cat file
foo
blah.xml
haha.xml
bar
$ sed -r 's#([^.]*\.xml)#user/home/\1#g' file
foo
user/home/blah.xml
user/home/haha.xml
bar

To answer your question in the comments, try:

$ echo "file is blah.xml" | sed -r 's#(\w+\.xml)#user/home/\1#'
file is user/home/blah.xml


问:
How can I change the color of the road in Google maps?
I'm looking for a way to change the color of roads (yellow) in MapView for Android. I thought of overriding the onDraw method, and then to go over each pixel and change it, but the method is final.

I also thought of wrapping the MapView with a ViewGroup and then try overriding its onDraw, but I'm not sure of how to do it.

Does anyone have an idea?

Thanks.

答:
Now (I'm don't know from what exactly moment, seems from Google Maps API V3.0) its easy with Styled Map feature of Maps Android API. For map style JSON preparing you can use Styling Withard. Also you can add only necessary parts to JSON style object, not for all map elements. For example for yellow roads (with blue labels) JSON (/res/raw/map_style.json) can be:

```<code>[
  {
    "featureType": "road",
    "elementType": "geometry.fill",
    "stylers": [
      {
        "color": "#ffff00"
      }
    ]
  },
  {
    "featureType": "road",
    "elementType": "labels.text.fill",
    "stylers": [
      {
        "color": "#0000ff"
      }
    ]
  }
</code>```

]

and MainActyvity.java with map Fragment:

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

    private GoogleMap mGoogleMap;
    private MapFragment mapFragment;

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

        mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map_fragment);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;

        try {
            // Customise the styling of the base map using a JSON object defined
            // in a raw resource file.
            boolean success = mGoogleMap.setMapStyle(
                    MapStyleOptions.loadRawResourceStyle(
                            this, R.raw.map_style));

            if (!success) {
                Log.e(TAG, "Style parsing failed.");
            }
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Can't find style. Error: ", e);
        }
        // Position the map's camera near Sydney, Australia.
        mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(50.4501,30.5234), 16.0f));

    }

}
</code>```

and activity_main.xls:

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

    <fragment
        android:id="@+id/map_fragment"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>
</code>```

As a result you should got:

You can also add style parameters for static map:
for

https://maps.googleapis.com/maps/api/staticmap?&key=[your_MAPS_API_KEY]&center=50.4501,30.5234&zoom=16&size=640x640&style=feature:road|element:geometry|color:0xFFFF00

request you got:

Please see Official Blog for more details.

Body:
Now (I'm don't know from what exactly moment, seems from Google Maps API V3.0) its easy with Styled Map feature of Maps Android API. For map style JSON preparing you can use Styling Withard. Also you can add only necessary parts to JSON style object, not for all map elements. For example for yellow roads (with blue labels) JSON (/res/raw/map_style.json) can be:

[
  {
    "featureType": "road",
    "elementType": "geometry.fill",
    "stylers": [
      {
        "color": "#ffff00"
      }
    ]
  },
  {
    "featureType": "road",
    "elementType": "labels.text.fill",
    "stylers": [
      {
        "color": "#0000ff"
      }
    ]
  }

]

and MainActyvity.java with map Fragment:

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mGoogleMap;
    private MapFragment mapFragment;

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

        mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map_fragment);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;

        try {
            // Customise the styling of the base map using a JSON object defined
            // in a raw resource file.
            boolean success = mGoogleMap.setMapStyle(
                    MapStyleOptions.loadRawResourceStyle(
                            this, R.raw.map_style));

            if (!success) {
                Log.e(TAG, "Style parsing failed.");
            }
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Can't find style. Error: ", e);
        }
        // Position the map's camera near Sydney, Australia.
        mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(50.4501,30.5234), 16.0f));

    }

}

and activity_main.xls:

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

    <fragment
        android:id="@+id/map_fragment"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

As a result you should got:

You can also add style parameters for static map:
for

https://maps.googleapis.com/maps/api/staticmap?&key=[your_MAPS_API_KEY]&center=50.4501,30.5234&zoom=16&size=640x640&style=feature:road|element:geometry|color:0xFFFF00

request you got:

Please see Official Blog for more details.


问:
Unexpected token < in JSON at position 0 tinymce
This question is asked many times and all of them in a different way that's why I doubt my problem was addressed in them.

I use TinyMCE with a file uploader. If I use an URL it works because it can get it back from the internet. When I want to use an image in a folder it will upload it's image in TinyMCE with on top the box saying "Image uploading: 100%". But this message stays on top and when I post the content everything but the image will be sent. Looking back I noticed no content in the file directory where I want to place all the uploaded images. Also, it gave back an error.

Unexpected token < in JSON at position 0:
Looked up at the error and found something funny. It showed the path where the content goes.

```<code>move_uploaded_file(this_is_the_path/this_is_the_image.jpg)
</code>```

Well in this example it looks fine but in dev tools, the path is indicated as orange which is a string but the file is in black. Does here lies the problem?
I wrapped it in a string and obvious result was:

```<code>move_uploaded_file(this_is_the_path/'this_is_the_image.jpg')
</code>```

Which is obviously wrong.

2 side problems which are related but aren't important at the moment to count as a problem.

If I change certain parts. Not sure which. It goes from error located to VM'random number' to frontpage where the action is happening.

files who start with numbers doesn't get uploaded at all and will be messaged as error: 500.

After the main problem is solved I will look into that.

My PHP code for handling the path.

```<code><?php
    $accepted_origins = array("http://localhost:8080");
    $imageFolder = "uploaded_content_frontpage/";
    reset ($_FILES);
    $temp = current($_FILES);
    if (is_uploaded_file($temp['tmp_name'])){
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) {
                header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
            } else {
                header("HTTP/1.0 403 Origin Denied");
                return;
            }
        }

// Sanitize input
        if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) {
            header("HTTP/1.0 500 Invalid file name.");
            return;
        }

// Verify extension
        if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) {
            header("HTTP/1.0 500 Invalid extension.");
            return;
        }

      // Accept upload if there was no origin, or if it is an accepted origin
        $filetowrite = 'uploaded_content_frontpage/'.$temp['name'];
        move_uploaded_file($temp['tmp_name'], $filetowrite);

        echo json_encode(array('location' => $filetowrite));
   } else {
        // Notify editor that the upload failed
        header("HTTP/1.0 500 Server Error");
   }
?>
</code>```

Is the pathing wrong or is it a typo or is it something else?

```<code>$(document).ready(function() {
tinymce.init ({
        theme: 'modern',
        selector: '.add_body_structure',
        height: 1000,
        menubar: true,
        branding: false,
        toolbar: 'undo redo | styleselect bold italic forecolor backcolor fontselect fontsizeselect | link paste | alignleft aligncenter alignright alignjustify | outdent indent bullist numlist | removeformat | insert',
        plugins: ' contextmenu print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media mediaembed template table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists textcolor wordcount imagetools contextmenu colorpicker textpattern help autoresize noneditable',
        contextmenu: 'paste link image inserttable cell row column deletetable',
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'lower-alpha,lower-roman,upper-alpha,upper-roman',
        statusbar: false,
        browser_spellcheck: true,
        image_title: true,
        automatic_uploads: true,
        media_live_embeds: true,
        contextmenu: true,
        relative_urls: false,
        remove_script_host: false,
        paste_data_images: true,
        encoding: 'xml',
        invalid_elements: 'script, input, textarea, textfield, col, colgroup, caption, dir, meta, object, select, option, source, title',
        fontsize_formats: '8pt 10pt 12pt 14pt 16pt 18pt 20pt 22pt 24pt 26pt 28pt 30pt 32pt 34pt 36pt 38pt 40pt',
        images_upload_url: '/wysiwyg/tinymce_main/wysiwyg_one_page_version2.1/views/home/code_for_images/image_uploader.php',

        file_picker_callback: function(cb, value, meta) {
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*, audio/*, video/*');

            input.onchange = function() {
                var file = this.files[0];

                var reader = new FileReader();
                reader.onload = function () {

                    var id = 'blobid' + (new Date()).getTime();
                    var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
                    var base64 = reader.result.split(',')[1];
                    var blobInfo = blobCache.create(id, file, base64);
                    blobCache.add(blobInfo);
                    // call the callback and populate the Title field with the file name
                    cb(blobInfo.blobUri(), { title: file.name });
                };
                reader.readAsDataURL(file);
            };
        input.click();
        }

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

Warning: move_uploaded_file(uploaded_content_frontpage/blobid1510920245387.jpg): failed to open stream: No such file or directory in C:\wamp\www\wysiwyg\tinymce_main\wysiwyg_one_page_version2.1\views\home\code_for_images\image_uploader.php on line 45

Line 45 indicates to move_uploaded_file($temp['tmp_name'], $filetowrite);

As you can see I can't open stream because no such file is in my directory.

答:
Comment out

```<code>echo $filetowrite;
</code>```

and check, because the filepath is being echoed out before your json, and that is what is causing the JSON parsing error.
Also there is an extra '.' in your

```<code>$filetowrite = 'uploaded_content_frontpage/'.$temp['name'].(see here);
</code>```

Body:
This question is asked many times and all of them in a different way that's why I doubt my problem was addressed in them.

I use TinyMCE with a file uploader. If I use an URL it works because it can get it back from the internet. When I want to use an image in a folder it will upload it's image in TinyMCE with on top the box saying "Image uploading: 100%". But this message stays on top and when I post the content everything but the image will be sent. Looking back I noticed no content in the file directory where I want to place all the uploaded images. Also, it gave back an error.

Unexpected token < in JSON at position 0:
Looked up at the error and found something funny. It showed the path where the content goes.

move_uploaded_file(this_is_the_path/this_is_the_image.jpg)

Well in this example it looks fine but in dev tools, the path is indicated as orange which is a string but the file is in black. Does here lies the problem?
I wrapped it in a string and obvious result was:

move_uploaded_file(this_is_the_path/'this_is_the_image.jpg')

Which is obviously wrong.

2 side problems which are related but aren't important at the moment to count as a problem.

If I change certain parts. Not sure which. It goes from error located to VM'random number' to frontpage where the action is happening.

files who start with numbers doesn't get uploaded at all and will be messaged as error: 500.

After the main problem is solved I will look into that.

My PHP code for handling the path.

<?php
    $accepted_origins = array("http://localhost:8080");
    $imageFolder = "uploaded_content_frontpage/";
    reset ($_FILES);
    $temp = current($_FILES);
    if (is_uploaded_file($temp['tmp_name'])){
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) {
                header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
            } else {
                header("HTTP/1.0 403 Origin Denied");
                return;
            }
        }

// Sanitize input
        if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) {
            header("HTTP/1.0 500 Invalid file name.");
            return;
        }

// Verify extension
        if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) {
            header("HTTP/1.0 500 Invalid extension.");
            return;
        }

      // Accept upload if there was no origin, or if it is an accepted origin
        $filetowrite = 'uploaded_content_frontpage/'.$temp['name'];
        move_uploaded_file($temp['tmp_name'], $filetowrite);

        echo json_encode(array('location' => $filetowrite));
   } else {
        // Notify editor that the upload failed
        header("HTTP/1.0 500 Server Error");
   }
?>

Is the pathing wrong or is it a typo or is it something else?

$(document).ready(function() {
tinymce.init ({
        theme: 'modern',
        selector: '.add_body_structure',
        height: 1000,
        menubar: true,
        branding: false,
        toolbar: 'undo redo | styleselect bold italic forecolor backcolor fontselect fontsizeselect | link paste | alignleft aligncenter alignright alignjustify | outdent indent bullist numlist | removeformat | insert',
        plugins: ' contextmenu print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media mediaembed template table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists textcolor wordcount imagetools contextmenu colorpicker textpattern help autoresize noneditable',
        contextmenu: 'paste link image inserttable cell row column deletetable',
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'lower-alpha,lower-roman,upper-alpha,upper-roman',
        statusbar: false,
        browser_spellcheck: true,
        image_title: true,
        automatic_uploads: true,
        media_live_embeds: true,
        contextmenu: true,
        relative_urls: false,
        remove_script_host: false,
        paste_data_images: true,
        encoding: 'xml',
        invalid_elements: 'script, input, textarea, textfield, col, colgroup, caption, dir, meta, object, select, option, source, title',
        fontsize_formats: '8pt 10pt 12pt 14pt 16pt 18pt 20pt 22pt 24pt 26pt 28pt 30pt 32pt 34pt 36pt 38pt 40pt',
        images_upload_url: '/wysiwyg/tinymce_main/wysiwyg_one_page_version2.1/views/home/code_for_images/image_uploader.php',

        file_picker_callback: function(cb, value, meta) {
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*, audio/*, video/*');

            input.onchange = function() {
                var file = this.files[0];

                var reader = new FileReader();
                reader.onload = function () {

                    var id = 'blobid' + (new Date()).getTime();
                    var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
                    var base64 = reader.result.split(',')[1];
                    var blobInfo = blobCache.create(id, file, base64);
                    blobCache.add(blobInfo);
                    // call the callback and populate the Title field with the file name
                    cb(blobInfo.blobUri(), { title: file.name });
                };
                reader.readAsDataURL(file);
            };
        input.click();
        }

});
});

Warning: move_uploaded_file(uploaded_content_frontpage/blobid1510920245387.jpg): failed to open stream: No such file or directory in C:\wamp\www\wysiwyg\tinymce_main\wysiwyg_one_page_version2.1\views\home\code_for_images\image_uploader.php on line 45

Line 45 indicates to move_uploaded_file($temp['tmp_name'], $filetowrite);

As you can see I can't open stream because no such file is in my directory.

Body:
Comment out

echo $filetowrite;

and check, because the filepath is being echoed out before your json, and that is what is causing the JSON parsing error.
Also there is an extra '.' in your

$filetowrite = 'uploaded_content_frontpage/'.$temp['name'].(see here);