问:
How to use FirebaseApp.initializeApp for FirebaseRemoteConfig
I am trying to use FirebaseApp.initializeApp, but its not working. I have the right library, but I cannot use the JSON file to initialize the app

This is my code:

Imports

```<code>import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings;
</code>```

Variables

```<code>private FirebaseRemoteConfig mFirebaseRemoteConfig;

private String projectID;
private String apiKey;
private String appID;
</code>```

How I initialize the app

```<code>public void Initialize() {
    FirebaseOptions mFirebaseOptions = new FirebaseOptions.Builder()
        .setApplicationId(this.appID)
        .setApiKey(this.apiKey)
        .build();
    FirebaseApp.initializeApp(this.context, mFirebaseOptions, this.projectID);
    mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
}
</code>```

The app crashed on startup this is the logcat error:

```<code>12-04 22:11:42.217 12566 12566 E AndroidRuntime: FATAL EXCEPTION: main
12-04 22:11:42.217 12566 12566 E AndroidRuntime: Process: com.makeroid.sanderjochems.FirebaseRemoteConfig, PID: 12566
12-04 22:11:42.217 12566 12566 E AndroidRuntime: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/internal/zzby;
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.FirebaseRemoteConfiguration.<init>(FirebaseRemoteConfiguration.java:67)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Constructor.newInstance0(Native Method)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.expr.PrimProcedure.apply(PrimProcedure.java:272)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.CallContext.runUntilDone(CallContext.java:234)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.CallContext.runUntilValue(CallContext.java:298)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.kawa.reflect.Invoke.applyN(Invoke.java:209)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.ProcedureN.apply2(ProcedureN.java:39)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.makeroid.sanderjochems.FirebaseRemoteConfig.Screen1.$define(Screen1.yail:10182)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.Form.onCreateFinish(Form.java:389)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.Form.onCreate(Form.java:336)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.Activity.performCreate(Activity.java:6942)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2880)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.-wrap14(ActivityThread.java)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:102)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.os.Looper.loop(Looper.java:154)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.main(ActivityThread.java:6682)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Method.invoke(Native Method)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
12-04 22:11:42.217 12566 12566 E AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.internal.zzby" on path: DexPathList[[zip file "/data/app/com.makeroid.sanderjochems.FirebaseRemoteConfig-1/base.apk"],nativeLibraryDirectories=[/data/app/com.makeroid.sanderjochems.FirebaseRemoteConfig-1/lib/arm64, /system/lib64, /vendor/lib64]]
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        ... 25 more
</code>```

答:
Hey I am suggesting some solutions -

Build.gradle file

```<code>multiDexEnabled true
</code>```

Add this in your proguard-rules.pro file

-keep public class com.google.android.gms.* { public *; }

Body:
I am trying to use FirebaseApp.initializeApp, but its not working. I have the right library, but I cannot use the JSON file to initialize the app

This is my code:

Imports

import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings;

Variables

private FirebaseRemoteConfig mFirebaseRemoteConfig;

private String projectID;
private String apiKey;
private String appID;

How I initialize the app

public void Initialize() {
    FirebaseOptions mFirebaseOptions = new FirebaseOptions.Builder()
        .setApplicationId(this.appID)
        .setApiKey(this.apiKey)
        .build();
    FirebaseApp.initializeApp(this.context, mFirebaseOptions, this.projectID);
    mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
}

The app crashed on startup this is the logcat error:

12-04 22:11:42.217 12566 12566 E AndroidRuntime: FATAL EXCEPTION: main
12-04 22:11:42.217 12566 12566 E AndroidRuntime: Process: com.makeroid.sanderjochems.FirebaseRemoteConfig, PID: 12566
12-04 22:11:42.217 12566 12566 E AndroidRuntime: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/internal/zzby;
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.FirebaseRemoteConfiguration.<init>(FirebaseRemoteConfiguration.java:67)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Constructor.newInstance0(Native Method)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.expr.PrimProcedure.apply(PrimProcedure.java:272)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.CallContext.runUntilDone(CallContext.java:234)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.CallContext.runUntilValue(CallContext.java:298)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.kawa.reflect.Invoke.applyN(Invoke.java:209)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at gnu.mapping.ProcedureN.apply2(ProcedureN.java:39)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.makeroid.sanderjochems.FirebaseRemoteConfig.Screen1.$define(Screen1.yail:10182)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.Form.onCreateFinish(Form.java:389)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.google.appinventor.components.runtime.Form.onCreate(Form.java:336)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.Activity.performCreate(Activity.java:6942)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2880)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.-wrap14(ActivityThread.java)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:102)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.os.Looper.loop(Looper.java:154)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at android.app.ActivityThread.main(ActivityThread.java:6682)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.reflect.Method.invoke(Native Method)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
12-04 22:11:42.217 12566 12566 E AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.common.internal.zzby" on path: DexPathList[[zip file "/data/app/com.makeroid.sanderjochems.FirebaseRemoteConfig-1/base.apk"],nativeLibraryDirectories=[/data/app/com.makeroid.sanderjochems.FirebaseRemoteConfig-1/lib/arm64, /system/lib64, /vendor/lib64]]
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
12-04 22:11:42.217 12566 12566 E AndroidRuntime:        ... 25 more

Body:
Hey I am suggesting some solutions -

Build.gradle file

multiDexEnabled true

Add this in your proguard-rules.pro file

-keep public class com.google.android.gms.* { public *; }


来源: stackexchange

问:
Wordpress local site switching to live URL
I am trying to install an existing wordpress site on my local machine
Ive set up database and site, but the issue Im having is when I hit the site on my local machine at url mysite.local it resolves to the live site mysite.com

What IVe done:

changed the URL of site_url and home in the options table in db
turned off all plugins
searched and replaced any hardcoded url in code (there were many!) and replaced with site_url()

Ive even noticed that when I call the site and it resolves to live URL the site_url and home values in options table are getting re-written with the live URL

Im not at all familiar with WP so Im wondering if Im missing something obvious or if anyone has run into similar issues

when the page is called IVe noticed that it sets a 302 permanently moved header

any ideas?

答:
I would start with htaccess to see if the live url is encoded in to redirect to that when you hit the directory to resolve anything like index.php or index.html. This usually is the first culprit in redirection.

Check if there is a cache plugin installed which i think you would have done already.

I think the next steps you have done are alright and options table would be one to confirm that it has written data to table.

ContentLicense: CC BY-SA 3.0


问:
Why i can not set image style height 100% for height as same as div container?
Why i can not set image style height 100% for height as same as div container ?

When i tried to test code it's will be show like this.

https://i.imgur.com/Q1MGP0Z.png

I want to show image like this.

https://i.imgur.com/GeLUUCo.png

with class name img_look style height: 100%; How can i do ?

.li_look{
    padding: 0px;
    margin: 0;
    position: relative;
    width: 25%;
    border-right: 3px solid #fff;
    margin-right: -3px;
    z-index: 11;
    float: left;
    list-style: none;
    color: #333;
    font-size: 19px;
    background: #fff;
}
.div_1{
    float: none;
    margin: 0;
    width: 100%;
    height: 197.207px;
    display: block;
    position: relative;
}
.a_tag{
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    height: 100%;
    margin-left: auto;
    margin-right: auto;
    overflow: hidden;
    display: block;
    cursor: pointer;
}
.div_2{
    transform: translateX(-50%);
    left: 50%;
    top: 0;
    background-color: transparent;
    display: block;
    position: absolute;
}
.img_look{
    height: 100%;
    display: block;
    margin-left: auto;
    margin-right: auto;
    max-width: unset;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li class="li_look">
    <div class="div_1">

        <div class="div_2">
          <img src="https://i2.wp.com/www.thisblogrules.com/wp-content/uploads/2010/02/man-and-bear-bath.jpg?resize=550%2C356" class="img_look">
        </div>

    </div>
  </li>
</ul></code>```

答:
Your image IS the same size as your div, but your div ISN'T the same size as the a tag that hold it. since your a has overflow:hidden; you can't see that your div is actually bigger.

you cant just add height:100%; or width:100%; to your div, but keep your image dimensions the same.

Also : that feels really wrong don't you think ?

```<code>height: 197.207px;
</code>```

Body:
Your image IS the same size as your div, but your div ISN'T the same size as the a tag that hold it. since your a has overflow:hidden; you can't see that your div is actually bigger.

you cant just add height:100%; or width:100%; to your div, but keep your image dimensions the same.

Also : that feels really wrong don't you think ?

height: 197.207px;


问:
How to move specific item in array list to the first item
For example : A list

A B C D E

Given C , Switch to

C A B D E

Notice that the array size will change, some items may removed in run times

```<code>Collections.swap(url, url.indexOf(itemToMove), 0);
</code>```

This statement is not working because it output C B A D E not C A B D E , how to fix it?

Thanks.

答:
Another solution, just keep swaping from 0 to indexOf(itemToMove).

This is my Kotlin version:

```<code>val list = mutableListOf('A', 'B', 'C', 'D', 'E')
(0..list.indexOf('C')).forEach {
    Collections.swap(list, 0, it)
}
</code>```

Sorry I am unfamiliar with Java but learned a little Kotlin. But the algorithm is the same.

Body:
For example : A list

A B C D E

Given C , Switch to

C A B D E

Notice that the array size will change, some items may removed in run times

Collections.swap(url, url.indexOf(itemToMove), 0);

This statement is not working because it output C B A D E not C A B D E , how to fix it?

Thanks.

Body:
Another solution, just keep swaping from 0 to indexOf(itemToMove).

This is my Kotlin version:

val list = mutableListOf('A', 'B', 'C', 'D', 'E')
(0..list.indexOf('C')).forEach {
    Collections.swap(list, 0, it)
}

Sorry I am unfamiliar with Java but learned a little Kotlin. But the algorithm is the same.


问:
Can a type know when a mutable borrow to itself has ended?
I have a struct and I want to call one of the struct's methods every time a mutable borrow to it has ended. To do so, I would need to know when the mutable borrow to it has been dropped. How can this be done? </p>

答:
Basically the same thing is done in RefCell. There you want to reduce the runtime borrow-count when a borrow ends. Here you want to perform an arbitrary action.

So let's re-use the concept of writing a function that returns a wrapped reference:

```<code>struct Data {
    content: i32,
}

impl Data {
    fn borrow_mut(&mut self) -> DataRef {
        println!("borrowing");
        DataRef { data: self }
    }

    fn check_after_borrow(&self) {
        if self.content > 50 {
            println!("Hey, content should be <= {:?}!", 50);
        }
    }
}

struct DataRef<'a> {
    data: &'a mut Data
}

impl<'a> Drop for DataRef<'a> {
    fn drop(&mut self) {
        println!("borrow ends");
        self.data.check_after_borrow()
    }
}

fn main() {
    let mut d = Data { content: 42 };
    println!("content is {}", d.content);
    {
        let b = d.borrow_mut();
        //let c = &d;  // Compiler won't let you have another borrow at the same time
        b.data.content = 123;
        println!("content set to {}", b.data.content);
    }  // borrow ends here
    println!("content is now {}", d.content);
}
</code>```

This results in the following output:

content is 42
borrowing
content set to 123
borrow ends
Hey, content should be <= 50!
content is now 123
```

Be aware that you can still obtain an unchecked mutable borrow with e.g. let c = &mut d;. This will be silently dropped without calling check_after_borrow.

Body:
Basically the same thing is done in RefCell. There you want to reduce the runtime borrow-count when a borrow ends. Here you want to perform an arbitrary action.

So let's re-use the concept of writing a function that returns a wrapped reference:

struct Data {
    content: i32,
}

impl Data {
    fn borrow_mut(&mut self) -> DataRef {
        println!("borrowing");
        DataRef { data: self }
    }

    fn check_after_borrow(&self) {
        if self.content > 50 {
            println!("Hey, content should be <= {:?}!", 50);
        }
    }
}

struct DataRef<'a> {
    data: &'a mut Data
}

impl<'a> Drop for DataRef<'a> {
    fn drop(&mut self) {
        println!("borrow ends");
        self.data.check_after_borrow()
    }
}

fn main() {
    let mut d = Data { content: 42 };
    println!("content is {}", d.content);
    {
        let b = d.borrow_mut();
        //let c = &d;  // Compiler won't let you have another borrow at the same time
        b.data.content = 123;
        println!("content set to {}", b.data.content);
    }  // borrow ends here
    println!("content is now {}", d.content);
}

This results in the following output:

content is 42
borrowing
content set to 123
borrow ends
Hey, content should be <= 50!
content is now 123

Be aware that you can still obtain an unchecked mutable borrow with e.g. let c = &mut d;. This will be silently dropped without calling check_after_borrow.


问:
How to configure Orika classMap for class hierarchies?
I'm trying to understand how to configure Orika class mapping correctly in case I have inheriting classes.

I've set up a simple example to ba able to understand what is working and what is not working, but I do not get it.

```<code>public class Source {
    private final String alpha;

    public Source(final String alpha) {
        this.alpha = alpha;
    }

    public String getAlpha() {
        return alpha;
    }
}

public final class SourceExtended extends Source {
    private final String beta;

    public SourceExtended(final String alpha, final String beta) {
        super(alpha);
        this.beta = beta;
    }

    public String getBeta() {
        return beta;
    }
}

public final class Target {
    private final String alpha;
    private final String beta;

    public Target (final String alpha) {
        this(alpha, null);
    }

    public Target(final String alpha, final String beta) {
        this.alpha = alpha;
        this.beta = beta;
    }

    public String getAlpha() {
        return alpha;
    }

    public String getBeta() {
        return beta;
    }
}
</code>```

I'm doing the mapping as follows

```<code>    Source s = new Source("alpha");
    Target t = this.mapper.map(s, Target.class);

    SourceExtended s = new SourceExtended("alpha", "beta");
    Target t = this.mapper.map(s, Target.class);
</code>```

And I have tried the following configurations...

```<code>factory.classMap(SourceExtended.class, Target.class)
    .byDefault()
    .register();

factory.classMap(Source.class, Target.class)
    .byDefault()
    .register();
</code>```

Result: Both mappings compile and run, but beta is not set in the target for the SourceExtended object, so the mapping for SourceExtended is not working.

So I thought that if I explicitly state the constructor to be used, then beta should be mapped too:

```<code>factory.classMap(SourceExtended.class, Target.class)
    .byDefault()
    .constructorA("alpha", "beta")
    .constructorB("alpha", "beta")
    .register();

factory.classMap(Source.class, Target.class)
    .byDefault()
    .register();
</code>```

But it the result is the same. beta is not mapped. And it does not change if I replace the default mapping by specifying the fields or by adding also the constructor to the mapping configuration of Source.class.

Can anyone give me a hint how to configure such a mapping? Thanks!

Kind regards,
jose

答:
```<code>factory.classMap(Parent.class, Parent.class).byDefault().register();
factory.classMap(ChildA.class, ChildA.class).byDefault().register();
factory.classMap(ChildB.class, ChildB.class).byDefault().register();
</code>```

Body:
I'm trying to understand how to configure Orika class mapping correctly in case I have inheriting classes.

I've set up a simple example to ba able to understand what is working and what is not working, but I do not get it.

public class Source {
    private final String alpha;

    public Source(final String alpha) {
        this.alpha = alpha;
    }

    public String getAlpha() {
        return alpha;
    }
}

public final class SourceExtended extends Source {
    private final String beta;

    public SourceExtended(final String alpha, final String beta) {
        super(alpha);
        this.beta = beta;
    }

    public String getBeta() {
        return beta;
    }
}

public final class Target {
    private final String alpha;
    private final String beta;

    public Target (final String alpha) {
        this(alpha, null);
    }

    public Target(final String alpha, final String beta) {
        this.alpha = alpha;
        this.beta = beta;
    }

    public String getAlpha() {
        return alpha;
    }

    public String getBeta() {
        return beta;
    }
}

I'm doing the mapping as follows

    Source s = new Source("alpha");
    Target t = this.mapper.map(s, Target.class);

    SourceExtended s = new SourceExtended("alpha", "beta");
    Target t = this.mapper.map(s, Target.class);

And I have tried the following configurations...

factory.classMap(SourceExtended.class, Target.class)
    .byDefault()
    .register();

factory.classMap(Source.class, Target.class)
    .byDefault()
    .register();

Result: Both mappings compile and run, but beta is not set in the target for the SourceExtended object, so the mapping for SourceExtended is not working.

So I thought that if I explicitly state the constructor to be used, then beta should be mapped too:

factory.classMap(SourceExtended.class, Target.class)
    .byDefault()
    .constructorA("alpha", "beta")
    .constructorB("alpha", "beta")
    .register();

factory.classMap(Source.class, Target.class)
    .byDefault()
    .register();

But it the result is the same. beta is not mapped. And it does not change if I replace the default mapping by specifying the fields or by adding also the constructor to the mapping configuration of Source.class.

Can anyone give me a hint how to configure such a mapping? Thanks!

Kind regards,
jose


问:
Newtonsoft.Json.Linq.JArray' to type 'System.Collections.Generic.IEnumerable
I am calling my web api from my C# desktop client.

This is my code on the client:

```<code>public IEnumerable<Model.Print> Get()
{
    var print = new List<Model.Print>();

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(Shared.URL);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Shared.HeaderType));
        var response = client.GetAsync(route + "?" + GeneralTags.CUSTOMER_REF + "=" + new Guid().ToString()).Result;

        if (response.IsSuccessStatusCode)
        {
            string strJson = response.Content.ReadAsStringAsync().Result;
            var jObj2 = (IEnumerable<Model.Print>)JsonConvert.DeserializeObject(strJson);
        }
        else
        {
            evError(new Exception(String.Format("{0}: {1}", (int)response.StatusCode, response.ReasonPhrase)), ErrorTags.PRINT_GET);
        }
    }
    return print;
}
</code>```

But I get an error on this line:

```<code>var jObj2 = (IEnumerable<Model.Print>)JsonConvert.DeserializeObject(strJson);
</code>```

The error is:

```<code>'Newtonsoft.Json.Linq.JArray' to type 'System.Collections.Generic.IEnumerable`1[InformedWorkerServer.Model.Print]'.
</code>```

The strJson contains a value:

```<code>[
  {"PrintId":1,"PrintRef":"00000000-0000-0000-0000-000000000000","Header":"header","TC":"tc","CompanyRef":"00000000-0000-0000-0000-000000000000"},
  {"PrintId":2,"PrintRef":"39a10cee-7cb3-4ed3-aec2-293761eed96d","Header":"header","TC":"tc","CompanyRef":"00000000-0000-0000-0000-000000000000"}]
</code>```

What am i missing?

答:
If you would like to format the nested json structure as represented in the image below. you can make use of the below formatter in Newtonsoft.Json.

Solution :
var _addressDetails = JsonConvert.DeserializeObject>(Convert.ToString(data.addressDetails));

Body:
I am calling my web api from my C# desktop client.

This is my code on the client:

public IEnumerable<Model.Print> Get()
{
    var print = new List<Model.Print>();

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(Shared.URL);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Shared.HeaderType));
        var response = client.GetAsync(route + "?" + GeneralTags.CUSTOMER_REF + "=" + new Guid().ToString()).Result;

        if (response.IsSuccessStatusCode)
        {
            string strJson = response.Content.ReadAsStringAsync().Result;
            var jObj2 = (IEnumerable<Model.Print>)JsonConvert.DeserializeObject(strJson);
        }
        else
        {
            evError(new Exception(String.Format("{0}: {1}", (int)response.StatusCode, response.ReasonPhrase)), ErrorTags.PRINT_GET);
        }
    }
    return print;
}

But I get an error on this line:

var jObj2 = (IEnumerable<Model.Print>)JsonConvert.DeserializeObject(strJson);

The error is:

'Newtonsoft.Json.Linq.JArray' to type 'System.Collections.Generic.IEnumerable`1[InformedWorkerServer.Model.Print]'.

The strJson contains a value:

[
  {"PrintId":1,"PrintRef":"00000000-0000-0000-0000-000000000000","Header":"header","TC":"tc","CompanyRef":"00000000-0000-0000-0000-000000000000"},
  {"PrintId":2,"PrintRef":"39a10cee-7cb3-4ed3-aec2-293761eed96d","Header":"header","TC":"tc","CompanyRef":"00000000-0000-0000-0000-000000000000"}]

What am i missing?


问:
Unable to parse multiple files in a directory

I have html files on my local harddrive that I am trying to open in a webpage by sending a http request.

Once the http request is created, I am trying to parse the stored html file by passing the url:(parsing is successful when passing one file at a time but I want to do it dynamically for all the files in a directory so used for loop. This doesn't workout)

once the parsing is done, I am saving the data to json file.(works fine)
I have pasted the code here:

```<code>import json
import os
from newspaper import Article
import newspaper

# initiating the server
server_start = os.system('start "HTTP Server on port 8000" cmd.exe /c {python -m http.server}')
http_server = 'http://localhost:8000/'
links = ''
path = "<path>"
for f in os.listdir(path):
    if f.endswith('.html'):
        links = http_server + path + f

    blog_post = newspaper.build(links)

    for article in blog_post.articles:
        print(article.url)

    article = Article(links)
    article.download('')
    article.parse()
    data = {"HTML": article.html, "author": article.authors, "title": article.title, "text": article.text, "date": str(article.publish_date)}

    json_data = json.dumps(data)
    with open('data.json', 'w') as outfile:
        json.dump(data, outfile)
</code>```

Error message:

...\newspaper\Scripts\python.exe ".../parsing_newspaper/test1.py"
  [Source parse ERR] http://localhost:8000/.../cnnpolitics-russian.html
  Traceback (most recent call last):

File"...\newspaper\lib\site-packages\newspaper\parsers.py", line 68,
  in  fromstring cls.doc = lxml.html.fromstring(html)

File "...\newspaper\lib\site-packages\lxml\html__init__.py", line
  876, in  fromstring doc = document_fromstring(html, parser=parser,
  base_url=base_url, **kw)

File "...\newspaper\lib\site-packages\lxml\html__init__.py", line
  762, in  document_fromstring value = etree.fromstring(html, parser,
  **kw)

File "src\lxml\lxml.etree.pyx", line 3213, in lxml.etree.fromstring
  (src\lxml\lxml.etree.c:78994)

File "src\lxml\parser.pxi", line 1848,  in
  lxml.etree._parseMemoryDocument (src\lxml\lxml.etree.c:118325)

File "src\lxml\parser.pxi", line 1729, in lxml.etree._parseDoc
  (src\lxml\lxml.etree.c:116883)

File "src\lxml\parser.pxi", line 1063,  in
  lxml.etree._BaseParser._parseUnicodeDoc
  (src\lxml\lxml.etree.c:110870)

File "src\lxml\parser.pxi", line 595, in
  lxml.etree._ParserContext._handleParseResultDoc
  (src\lxml\lxml.etree.c:105093)

File "src\lxml\parser.pxi", line 706,  in
  lxml.etree._handleParseResult (src\lxml\lxml.etree.c:106801)

File "src\lxml\parser.pxi", line 646, in lxml.etree._raiseParseError
  (src\lxml\lxml.etree.c:105947)

File "", line 0 lxml.etree.XMLSyntaxError:

You must download()an article before calling parse() on it!

Traceback (most recent call last): File ".../test1.py", line 26, in
   article.parse()

File "...\newspaper\lib\site-packages\newspaper\article.py", line 168,
  in  parse raise ArticleException() newspaper.article.ArticleException

答:
Don't know if this helps but try this:

```<code>import json
import os
from newspaper import Article
import newspaper

# initiating the server
server_start = os.system('start "HTTP Server on port 8000" cmd.exe /c {python -m http.server}')
http_server = 'http://localhost:8000/'
links = ''
path = "<path>"
for f in os.listdir(path):
    if f.endswith('.html'):
       links = http_server + path + f

       blog_post = newspaper.build(links)

       for article in blog_post.articles:
       print(article.url)

       article = Article(links)
       article.download('')
       article.parse()
       data = {"HTML": article.html, "author": article.authors, "title": article.title, "text": article.text, "date": str(article.publish_date)}

       json_data = json.dumps(data)
       with open('data.json', 'w') as outfile:
       json.dump(data, outfile)
</code>```

Because otherwise if the first file is not a file with html extension, then you try to build an empty string.

or
if the first one is a file with html extension but second one is not than you are going to build the same file (at least) twice

Body:
I have html files on my local harddrive that I am trying to open in a webpage by sending a http request.

Once the http request is created, I am trying to parse the stored html file by passing the url:(parsing is successful when passing one file at a time but I want to do it dynamically for all the files in a directory so used for loop. This doesn't workout)

once the parsing is done, I am saving the data to json file.(works fine)
I have pasted the code here:

import json
import os
from newspaper import Article
import newspaper

# initiating the server
server_start = os.system('start "HTTP Server on port 8000" cmd.exe /c {python -m http.server}')
http_server = 'http://localhost:8000/'
links = ''
path = "<path>"
for f in os.listdir(path):
    if f.endswith('.html'):
        links = http_server + path + f

    blog_post = newspaper.build(links)

    for article in blog_post.articles:
        print(article.url)

    article = Article(links)
    article.download('')
    article.parse()
    data = {"HTML": article.html, "author": article.authors, "title": article.title, "text": article.text, "date": str(article.publish_date)}

    json_data = json.dumps(data)
    with open('data.json', 'w') as outfile:
        json.dump(data, outfile)

Error message:

...\newspaper\Scripts\python.exe ".../parsing_newspaper/test1.py"
  [Source parse ERR] http://localhost:8000/.../cnnpolitics-russian.html
  Traceback (most recent call last):

File"...\newspaper\lib\site-packages\newspaper\parsers.py", line 68,
  in  fromstring cls.doc = lxml.html.fromstring(html)

File "...\newspaper\lib\site-packages\lxml\html__init__.py", line
  876, in  fromstring doc = document_fromstring(html, parser=parser,
  base_url=base_url, **kw)

File "...\newspaper\lib\site-packages\lxml\html__init__.py", line
  762, in  document_fromstring value = etree.fromstring(html, parser,
  **kw)

File "src\lxml\lxml.etree.pyx", line 3213, in lxml.etree.fromstring
  (src\lxml\lxml.etree.c:78994)

File "src\lxml\parser.pxi", line 1848,  in
  lxml.etree._parseMemoryDocument (src\lxml\lxml.etree.c:118325)

File "src\lxml\parser.pxi", line 1729, in lxml.etree._parseDoc
  (src\lxml\lxml.etree.c:116883)

File "src\lxml\parser.pxi", line 1063,  in
  lxml.etree._BaseParser._parseUnicodeDoc
  (src\lxml\lxml.etree.c:110870)

File "src\lxml\parser.pxi", line 595, in
  lxml.etree._ParserContext._handleParseResultDoc
  (src\lxml\lxml.etree.c:105093)

File "src\lxml\parser.pxi", line 706,  in
  lxml.etree._handleParseResult (src\lxml\lxml.etree.c:106801)

File "src\lxml\parser.pxi", line 646, in lxml.etree._raiseParseError
  (src\lxml\lxml.etree.c:105947)

File "", line 0 lxml.etree.XMLSyntaxError:

You must download()an article before calling parse() on it!

Traceback (most recent call last): File ".../test1.py", line 26, in
   article.parse()

File "...\newspaper\lib\site-packages\newspaper\article.py", line 168,
  in  parse raise ArticleException() newspaper.article.ArticleException

Body:
Don't know if this helps but try this:

import json
import os
from newspaper import Article
import newspaper

# initiating the server
server_start = os.system('start "HTTP Server on port 8000" cmd.exe /c {python -m http.server}')
http_server = 'http://localhost:8000/'
links = ''
path = "<path>"
for f in os.listdir(path):
    if f.endswith('.html'):
       links = http_server + path + f

       blog_post = newspaper.build(links)

       for article in blog_post.articles:
       print(article.url)

       article = Article(links)
       article.download('')
       article.parse()
       data = {"HTML": article.html, "author": article.authors, "title": article.title, "text": article.text, "date": str(article.publish_date)}

       json_data = json.dumps(data)
       with open('data.json', 'w') as outfile:
       json.dump(data, outfile)

Because otherwise if the first file is not a file with html extension, then you try to build an empty string.

or
if the first one is a file with html extension but second one is not than you are going to build the same file (at least) twice


问:
SQL Server Get only Date form column with Date and Time
I have been trying to get only date from a column with date and time.

Here is a sample:

```<code>Select BDATE
from PersonData
</code>```

Current output:

```<code>1977-12-05 15:40:54.000
</code>```

Desired output:

```<code>1977-12-05
</code>```

How can I use the CONVERT date from datetime?

Thanks in advance

答:
You can use this.

```<code>SELECT CONVERT(VARCHAR(10), BDATE , 120) from PersonData
</code>```

style : 120  for ODBC canonical yyyy-mm-dd hh:mi:ss(24h)

Body:
I have been trying to get only date from a column with date and time.

Here is a sample:

Select BDATE
from PersonData

Current output:

1977-12-05 15:40:54.000

Desired output:

1977-12-05

How can I use the CONVERT date from datetime?

Thanks in advance

Body:
You can use this.

SELECT CONVERT(VARCHAR(10), BDATE , 120) from PersonData

style : 120  for ODBC canonical yyyy-mm-dd hh:mi:ss(24h)


答:
Disclaimer: The answer that follows describes a possible solution, but it's not a very good one, as described by this comment from Sebastien Redl:

[T]his is a bad way of trying to maintain invariants. Mostly because dropping the reference can be suppressed with mem::forget. This is fine for RefCell, where if you don't drop the ref, you will simply eventually panic because you didn't release the dynamic borrow, but it is bad if violating the "fraction is in shortest form" invariant leads to weird results or subtle performance issues down the line, and it is catastrophic if you need to maintain the "thread doesn't outlive variables in the current scope" invariant.

Nevertheless, it's possible to use a temporary struct as a "staging area" that updates the referent when it's dropped, and thus maintain the invariant correctly; however, that version basically amounts to making a proper wrapper type and a kind of weird way to use it. The best way to solve this problem is through an opaque wrapper struct that doesn't expose its internals except through methods that definitely maintain the invariant.

Without further ado, the original answer:

Not exactly... but pretty close. We can use RefCell<T> as a model for how this can be done. It's a bit of an abstract question, but I'll use a concrete example to demonstrate. (This won't be a complete example, but something to show the general principles.)

Let's say you want to make a Fraction struct that is always in simplest form (fully reduced, e.g. 3/5 instead of 6/10).  You write a struct RawFraction that will contain the bare data. RawFraction instances are not always in simplest form, but they have a method fn reduce(&mut self) that reduces them.

Now you need a smart pointer type that you will always use to mutate the RawFraction, which calls .reduce() on the pointed-to struct when it's dropped. Let's call it RefMut, because that's the naming scheme RefCell uses. You implement Deref<Target = RawFraction>, DerefMut, and Drop on it, something like this:

```<code>pub struct RefMut<'a>(&'a mut RawFraction);

impl<'a> Deref for RefMut<'a> {
    type Target = RawFraction;
    fn deref(&self) -> &RawFraction {
        self.0
    }
}

impl<'a> DerefMut for RefMut<'a> {
    fn deref_mut(&mut self) -> &mut RawFraction {
        self.0
    }
}

impl<'a> Drop for RefMut<'a> {
    fn drop(&mut self) {
        self.0.reduce();
    }
}
</code>```

Now, whenever you have a RefMut to a RawFraction and drop it, you know the RawFraction will be in simplest form afterwards. All you need to do at this point is ensure that RefMut is the only way to get &mut access to the RawFraction part of a Fraction.

```<code>pub struct Fraction(RawFraction);

impl Fraction {
    pub fn new(numerator: i32, denominator: i32) -> Self {
        // create a RawFraction, reduce it and wrap it up
    }

    pub fn borrow_mut(&mut self) -> RefMut {
        RefMut(&mut self.0)
    }
}
</code>```

Pay attention to the pub markings (and lack thereof): I'm using those to ensure the soundness of the exposed interface. All three types should be placed in a module by themselves. It would be incorrect to mark the RawFraction field pub inside Fraction, since then it would be possible (for code outside the module) to create an unreduced Fraction without using new or get a &mut RawFraction without going through RefMut.

Supposing all this code is placed in a module named frac, you can use it something like this (assuming Fraction implements Display):

```<code>let f = frac::Fraction::new(3, 10);
println!("{}", f); // prints 3/10
f.borrow_mut().numerator += 3;
println!("{}", f); // prints 3/5
</code>```

The types encode the invariant: Wherever you have Fraction, you can know that it's fully reduced. When you have a RawFraction, &RawFraction, etc., you can't be sure. If you want, you may also make RawFraction's fields non-pub, so that you can't get an unreduced fraction at all except by calling borrow_mut on a Fraction.

Title: Can a type know when a mutable borrow to itself has ended?

Body: I have a struct and I want to call one of the struct's methods every time a mutable borrow to it has ended. To do so, I would need to know when the mutable borrow to it has been dropped. How can this be done?

Body:
Disclaimer: The answer that follows describes a possible solution, but it's not a very good one, as described by this comment from Sebastien Redl:

[T]his is a bad way of trying to maintain invariants. Mostly because dropping the reference can be suppressed with mem::forget. This is fine for RefCell, where if you don't drop the ref, you will simply eventually panic because you didn't release the dynamic borrow, but it is bad if violating the "fraction is in shortest form" invariant leads to weird results or subtle performance issues down the line, and it is catastrophic if you need to maintain the "thread doesn't outlive variables in the current scope" invariant.

Nevertheless, it's possible to use a temporary struct as a "staging area" that updates the referent when it's dropped, and thus maintain the invariant correctly; however, that version basically amounts to making a proper wrapper type and a kind of weird way to use it. The best way to solve this problem is through an opaque wrapper struct that doesn't expose its internals except through methods that definitely maintain the invariant.

Without further ado, the original answer:

Not exactly... but pretty close. We can use RefCell<T> as a model for how this can be done. It's a bit of an abstract question, but I'll use a concrete example to demonstrate. (This won't be a complete example, but something to show the general principles.)

Let's say you want to make a Fraction struct that is always in simplest form (fully reduced, e.g. 3/5 instead of 6/10).  You write a struct RawFraction that will contain the bare data. RawFraction instances are not always in simplest form, but they have a method fn reduce(&mut self) that reduces them.

Now you need a smart pointer type that you will always use to mutate the RawFraction, which calls .reduce() on the pointed-to struct when it's dropped. Let's call it RefMut, because that's the naming scheme RefCell uses. You implement Deref<Target = RawFraction>, DerefMut, and Drop on it, something like this:

pub struct RefMut<'a>(&'a mut RawFraction);

impl<'a> Deref for RefMut<'a> {
    type Target = RawFraction;
    fn deref(&self) -> &RawFraction {
        self.0
    }
}

impl<'a> DerefMut for RefMut<'a> {
    fn deref_mut(&mut self) -> &mut RawFraction {
        self.0
    }
}

impl<'a> Drop for RefMut<'a> {
    fn drop(&mut self) {
        self.0.reduce();
    }
}

Now, whenever you have a RefMut to a RawFraction and drop it, you know the RawFraction will be in simplest form afterwards. All you need to do at this point is ensure that RefMut is the only way to get &mut access to the RawFraction part of a Fraction.

pub struct Fraction(RawFraction);

impl Fraction {
    pub fn new(numerator: i32, denominator: i32) -> Self {
        // create a RawFraction, reduce it and wrap it up
    }

    pub fn borrow_mut(&mut self) -> RefMut {
        RefMut(&mut self.0)
    }
}

Pay attention to the pub markings (and lack thereof): I'm using those to ensure the soundness of the exposed interface. All three types should be placed in a module by themselves. It would be incorrect to mark the RawFraction field pub inside Fraction, since then it would be possible (for code outside the module) to create an unreduced Fraction without using new or get a &mut RawFraction without going through RefMut.

Supposing all this code is placed in a module named frac, you can use it something like this (assuming Fraction implements Display):

let f = frac::Fraction::new(3, 10);
println!("{}", f); // prints 3/10
f.borrow_mut().numerator += 3;
println!("{}", f); // prints 3/5

The types encode the invariant: Wherever you have Fraction, you can know that it's fully reduced. When you have a RawFraction, &RawFraction, etc., you can't be sure. If you want, you may also make RawFraction's fields non-pub, so that you can't get an unreduced fraction at all except by calling borrow_mut on a Fraction.


问:
Split an array into 2 based on objects property AngularJS
I'm having an array of objects These objects are coming from two different input fields on my form. They are identified by ids.

Field one is id:1 and field two is id:2. How can I split them into two arrays based on their ids. For example id:1 objects to be stored in array1 and id:2 in array2. I don't want to hardcode as if more input fields were created this would make some mess.

```<code>"values":[{"id":"1","description":"123"},
          {"id":"1","description":"456"},
          {"id":"2","description":"456"}]
</code>```

答:
You can generate a list of uniques id by using Set . Then, with array.prototype.reduce along with array.prototype.filter,  you can dynamically build an object that wraps all the generated arrays for each id:

var values = [
 {"id":"1","description":"123"},
 {"id":"1","description":"456"},
 {"id":"2","description":"456"}
];

var ids = [...new Set(values.map(v => v.id))];
var res = ids.reduce((m, o) => (m[`array${o}`] = values.filter(v => v.id === o), m), {});

console.log(res);```

Body:
I'm having an array of objects These objects are coming from two different input fields on my form. They are identified by ids.

Field one is id:1 and field two is id:2. How can I split them into two arrays based on their ids. For example id:1 objects to be stored in array1 and id:2 in array2. I don't want to hardcode as if more input fields were created this would make some mess.

"values":[{"id":"1","description":"123"},
          {"id":"1","description":"456"},
          {"id":"2","description":"456"}]


问:
How can objective C classes be encrypted
I would like to encrypt a few of my obj c classes in my iphone game which handle openfeint data and classes which handle scores.

I have heard there is a way to encrypt this data to act as another level of security, at least enough to discourage some from cracking it and forging scores on a jailbroken iphone and then spam the leaderboards.

How is this done, what are good techniques to secure this data and discourage some from attempting to spoof data?

Thanks

答:
To truly encrypt compiled code is probably more trouble than it is worth.  You have to isolate the code that will be decrypted into a dynamic library and load the library manually after decrypting it in memory.  Dynamic libraries, and the other methods you might use to modify code at runtime, are frowned on by Apple when used with iOS.

With Objective-C you essentially ship with the headers build into your code.  That makes it much easier to dig around in your application.  Anything you can do in C, where symbols may be stripped, will be slightly harder to read.  You can also use #define to obfuscate your class and method names a little.  This is nowhere near encryption, but is much easier to implement and less likely to introduce wacky bugs.

```<code>#define MyNicelyNamedClass somegarblegarble
#define myNicelyNamedMethod othergarblegarble

@interface MyNicelyNamedClass

-(id) myNicelyNamedMethod;

@end
</code>```

This is a relatively painless way for a developer to make their Objective-C code less obvious to others.  It is about as effective as javascript obfuscation, which is to say it is one more little hurdle that will dissuade many casual attackers.

If you choose meaningful but misleading names instead of straight garbage you may even trick someone into spending hours digging through the wrong code.  Not that you would ever know, but it is a satisfying thought.

ContentLicense: CC BY-SA 2.5

Body:
To truly encrypt compiled code is probably more trouble than it is worth.  You have to isolate the code that will be decrypted into a dynamic library and load the library manually after decrypting it in memory.  Dynamic libraries, and the other methods you might use to modify code at runtime, are frowned on by Apple when used with iOS.

With Objective-C you essentially ship with the headers build into your code.  That makes it much easier to dig around in your application.  Anything you can do in C, where symbols may be stripped, will be slightly harder to read.  You can also use #define to obfuscate your class and method names a little.  This is nowhere near encryption, but is much easier to implement and less likely to introduce wacky bugs.

#define MyNicelyNamedClass somegarblegarble
#define myNicelyNamedMethod othergarblegarble

@interface MyNicelyNamedClass

-(id) myNicelyNamedMethod;

@end

This is a relatively painless way for a developer to make their Objective-C code less obvious to others.  It is about as effective as javascript obfuscation, which is to say it is one more little hurdle that will dissuade many casual attackers.

If you choose meaningful but misleading names instead of straight garbage you may even trick someone into spending hours digging through the wrong code.  Not that you would ever know, but it is a satisfying thought.


问:
How to pass parameters for method call in controller from gsp?
I am calling a method located in the controller from my gsp file. The method in question has a parameter that need be filled.

The following is currently how I have it and does not work.

```<code><g:each in="${msdsLinkList}" status="i" var="msdsLink">
  <div id="msdsBox${i}" class="msdsBox">
    <g:link class="word-button" action="exportAttachment(msdsLink${i})"></g:link>
  </div>
</g:each>
</code>```

How can I pass msdsLink${i} in to the exportAttachment method?

答:
In addition to elixir's answer, you can use params in your g:link tag:

```<code><g:each in="${msdsLinkList}" status="i" var="msdsLink">
  <div id="msdsBox${i}" class="msdsBox">
    <g:link class="word-button" action="exportAttachment" id="${msdsLink.id}"
            params="[foo: 'bar', bar: 'foo', value: msdsLink.value]"></g:link>
  </div>
</g:each>
</code>```

In your controller's method, you can simply use the params map :

```<code>params.id
params.foo
params.bar
params.value
</code>```

Body:
I am calling a method located in the controller from my gsp file. The method in question has a parameter that need be filled.

The following is currently how I have it and does not work.

<g:each in="${msdsLinkList}" status="i" var="msdsLink">

    <g:link class="word-button" action="exportAttachment(msdsLink${i})"></g:link>

</g:each>

How can I pass msdsLink${i} in to the exportAttachment method?

Body:
In addition to elixir's answer, you can use params in your g:link tag:

<g:each in="${msdsLinkList}" status="i" var="msdsLink">
  <div id="msdsBox${i}" class="msdsBox">
    <g:link class="word-button" action="exportAttachment" id="${msdsLink.id}"
            params="[foo: 'bar', bar: 'foo', value: msdsLink.value]"></g:link>
  </div>
</g:each>

In your controller's method, you can simply use the params map :

params.id
params.foo
params.bar
params.value


问:
Two Django projects with same database - permission denied for relation django_migrations
I have two django projects that are not connected in any way, both on localhost. I want to have them both use the same database.

I am trying to create migrations on the second project after the first one succeeded but, I am getting an exception:

```<code>django.db.utils.ProgrammingError: permission denied for relation django_migrations
</code>```

My setup is as follows:

```<code>//First project
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'srt_side_by_side',
        'USER': 'srt_side_by_side_admin',
        'PASSWORD': '******************',
        'HOST': 'localhost',
        'PORT': '',
    }
}
//Second project
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'srt_side_by_side',
        'USER': 'srt_side_by_side_admin_2',
        'PASSWORD': '**************',
        'HOST': 'localhost',
        'PORT': '',
    }
}
</code>```

I have granted SUPERUSER privileges to both users.
I have tried to set individual privileges while being connected as the corresponding user in the psql shell.

```<code>GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public to srt_side_by_side_admin_2;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public to srt_side_by_side_admin_2;
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public to srt_side_by_side_admin_2;
</code>```

The DB access privileges in the psql shell:

```<code>=Tc/simeonparvanov
simeonparvanov=CTc/simeonparvanov
srt_side_by_side_admin=CTc/simeonparvanov
srt_side_by_side_admin_2=CTc/simeonparvanov
</code>```

Any idea what am I doing wrong?

答:
Are your projects does not have any relation and you just want to run only one instance of postgres server?
If so, than you just need to create two separate databases in postgres, set your user to own both of them, and then set their names in field name of config.

Something like:

CREATE DATABASE srt_side_by_side_2 OWNER srt_side_by_side_admin;

And then for the second project config:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'srt_side_by_side_2',
        'USER': 'srt_side_by_side_admin',
        'PASSWORD': '**************',
        'HOST': 'localhost',
        'PORT': '',
    }
}
</code>```

Body:
I have two django projects that are not connected in any way, both on localhost. I want to have them both use the same database.

I am trying to create migrations on the second project after the first one succeeded but, I am getting an exception:

django.db.utils.ProgrammingError: permission denied for relation django_migrations

My setup is as follows:

//First project
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'srt_side_by_side',
        'USER': 'srt_side_by_side_admin',
        'PASSWORD': '******************',
        'HOST': 'localhost',
        'PORT': '',
    }
}
//Second project
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'srt_side_by_side',
        'USER': 'srt_side_by_side_admin_2',
        'PASSWORD': '**************',
        'HOST': 'localhost',
        'PORT': '',
    }
}

I have granted SUPERUSER privileges to both users.
I have tried to set individual privileges while being connected as the corresponding user in the psql shell.

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public to srt_side_by_side_admin_2;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public to srt_side_by_side_admin_2;
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public to srt_side_by_side_admin_2;

The DB access privileges in the psql shell:

=Tc/simeonparvanov
simeonparvanov=CTc/simeonparvanov
srt_side_by_side_admin=CTc/simeonparvanov
srt_side_by_side_admin_2=CTc/simeonparvanov

Any idea what am I doing wrong?

Body:
Are your projects does not have any relation and you just want to run only one instance of postgres server?
If so, than you just need to create two separate databases in postgres, set your user to own both of them, and then set their names in field name of config.

Something like:

CREATE DATABASE srt_side_by_side_2 OWNER srt_side_by_side_admin;

And then for the second project config:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'srt_side_by_side_2',
        'USER': 'srt_side_by_side_admin',
        'PASSWORD': '**************',
        'HOST': 'localhost',
        'PORT': '',
    }
}


问:
awk : extracting a data which is on several lines
so I have a file that looks like this :

```<code>/translation="MDGVTQQNAALVQEATTAAASLEEQARNLTAAVAAFDLGDKQTV
                 LITPRAAVPALKRPALKASLPASSSHGNWETF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
 CDS             complement(471..590)
                 /db_xref="SEED:fig|1240086.14.peg.2"
                 /translation="MHQYQSAILAKICRYGGIEKPEITPASVYKLDSHWRYVI"
                 /product="hypothetical protein"
 CDS             717..2354
                 /db_xref="SEED:fig|1240086.14.peg.3"
                 /translation="MGFFVVLWGGASGFSLYSLKQVTTLLHDNSTQGRTYTYLVYGND
                 QYFRSVTRMARVMDYSQFSDAAIASLEEQAQQLTKAVEVFHLGSEYQTAAS
                 RTRPAGNMALKRPALSGMAPALPPARTASDEGSWEKF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
                 /product="macromolecule metabolism; macromolecule
                 degradation; degradation of proteins, peptides,
                 glycopeptides"
</code>```

I need to extract the text that is between quotes after a "/product=", so I need this :

```<code>Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
hypothetical protein
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
macromolecule metabolism; macromolecule degradation; degradation of proteins, peptides, glycopeptides
</code>```

I have to use awk, so I wrote this :

```<code>awk '/\/product/ {split($0, a, "\""); printf a[2] "\n"}'
</code>```

but this only takes the info on the same line as "/product", and some times the info is on two or three lines.. I'm out of ideas as to how to get the entire info between the quotes, anyone can help?

答:
can be done with GNU grep, output separated by \0 0 byte

```<code>grep -Pzo '/product="\K[^"]*'  | tr -s '\0\t\n' '\n '
</code>```

or perl replacing multiple (spaces, newlines or tabs) by a single space, separated with newlines

```<code>perl -0777 -ne 'print s/\s+/ /gr."\n" for /\/product="\K[^"]*/g'
</code>```

Body:
so I have a file that looks like this :

/translation="MDGVTQQNAALVQEATTAAASLEEQARNLTAAVAAFDLGDKQTV
                 LITPRAAVPALKRPALKASLPASSSHGNWETF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
 CDS             complement(471..590)
                 /db_xref="SEED:fig|1240086.14.peg.2"
                 /translation="MHQYQSAILAKICRYGGIEKPEITPASVYKLDSHWRYVI"
                 /product="hypothetical protein"
 CDS             717..2354
                 /db_xref="SEED:fig|1240086.14.peg.3"
                 /translation="MGFFVVLWGGASGFSLYSLKQVTTLLHDNSTQGRTYTYLVYGND
                 QYFRSVTRMARVMDYSQFSDAAIASLEEQAQQLTKAVEVFHLGSEYQTAAS
                 RTRPAGNMALKRPALSGMAPALPPARTASDEGSWEKF"
                 /product="Methyl-accepting chemotaxis protein I (serine
                 chemoreceptor protein)"
                 /product="macromolecule metabolism; macromolecule
                 degradation; degradation of proteins, peptides,
                 glycopeptides"

I need to extract the text that is between quotes after a "/product=", so I need this :

Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
hypothetical protein
Methyl-accepting chemotaxis protein I (serine chemoreceptor protein)
macromolecule metabolism; macromolecule degradation; degradation of proteins, peptides, glycopeptides

I have to use awk, so I wrote this :

awk '/\/product/ {split($0, a, "\""); printf a[2] "\n"}'

but this only takes the info on the same line as "/product", and some times the info is on two or three lines.. I'm out of ideas as to how to get the entire info between the quotes, anyone can help?

Body:
can be done with GNU grep, output separated by \0 0 byte

grep -Pzo '/product="\K[^"]*'  | tr -s '\0\t\n' '\n '

or perl replacing multiple (spaces, newlines or tabs) by a single space, separated with newlines

perl -0777 -ne 'print s/\s+/ /gr."\n" for /\/product="\K[^"]*/g'


问:
AsyncFileUpload in Repeater in UpdatePanel
The AsyncFileUpload works. Only issue is the file name disappears when the LinkButton to repeat the AsyncFileUpload control is pressed. Is there a way to get and store the file name? FileName does not work. Not really keen on sharing code-behind but may do so if it is necessary to solve this issue.</p>

```<code><asp:UpdatePanel ID="LibraryResourceUpdatePanel" runat="server">
        <ContentTemplate>
            <div class="field-group list-of-resource">
                <asp:Repeater ID="RptRequest" runat="server" OnItemDataBound="RptRequest_ItemDataBound">
                    <ItemTemplate>
                        <div class="resource">
                            <div class="remove-input">
                                <asp:LinkButton ID="LbRemoveRequest" CssClass="ic fa fa-minus-circle" runat="server" OnClick="LbRemoveRequest_Click" CausesValidation="false"></asp:LinkButton>
                                <span>Remove</span>
                            </div>
                            <h2>Details of Resources
                        <span class="counter">
                            <asp:Literal ID="LitCount" runat="server"></asp:Literal>
                        </span>
                            </h2>
                            <ul>
                                <li>
                                    <fieldset class="form-group">
                                        <legend>Accession No.</legend>
                                        <asp:TextBox ID="TxbAccessionNumber" CssClass="form-control" runat="server" />
                                        <asp:RequiredFieldValidator runat="server" ControlToValidate="TxbAccessionNumber" ErrorMessage="Email is required" ForeColor="Red" Display="Dynamic" />
                                    </fieldset>
                                </li>
                                <li>
                                    <fieldset class="form-group">
                                        <legend>Details</legend>
                                        <asp:TextBox ID="TxbDetails" runat="server" Rows="4" TextMode="MultiLine" />
                                        <asp:RequiredFieldValidator runat="server" ControlToValidate="TxbDetails" ErrorMessage="Details are required" ForeColor="Red" Display="Dynamic" />
                                    </fieldset>
                                </li>
                                <li>
                                    <fieldset class="form-group">
                                        <legend>Image</legend>
                                        <ajaxToolkit:AsyncFileUpload runat="server"
                                            ID="FileUpload" OnUploadedComplete="FileUpload_UploadedComplete" ClientIDMode="AutoID" PersistFile="true"/>
                                        <asp:RequiredFieldValidator runat="server" ControlToValidate="FileUpload" ErrorMessage="File Upload required" ForeColor="Red" Display="Dynamic" />
                                    </fieldset>
                                </li>
                            </ul>
                        </div>
                    </ItemTemplate>
                </asp:Repeater>
            </div>
            <div class="add-input">
                <asp:LinkButton ID="LbAddRequest" CssClass="ic fa fa-plus-circle" runat="server" OnClick="LbAddRequest_Click" CausesValidation="false" ></asp:LinkButton>
                <span>Add another request</span>
            </div>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="LbAddRequest" EventName="click" />
        </Triggers>
    </asp:UpdatePanel>
</code>```

答:
First add command name to linkbutton and remove click event:

```<code><asp:LinkButton ID="LbAddRequest" runat="server"
    CommandName="AddRequest"></asp:LinkButton>
<span>Add another request</span>
</code>```

And try this ItemCommand event in code-behind to get in work:

```<code>protected void RptRequest_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    if (e.CommandName == "AddRequest")
    {
        FileUpload myFileUpload = (FileUpload)e.Item.FindControl("FileUpload");
        if (myFileUpload.HasFile)
        {
            try
            {
                string filename = Path.GetFileName(myFileUpload.FileName);
                myFileUpload.SaveAs(Server.MapPath("~/") + filename);
                myStatusLabel.Text = "Upload Success";
            }
            catch (Exception ex)
            {

                myStatusLabel.Text = "Upload Fail" + ex.Message;
            }
        }
        else
        {

            myStatusLabel.Text = "myFileUpload Has No File";
        }
    }
}
</code>```

Read detail here : https://forums.asp.net/t/1904302.aspx?FileUpload+Inside+a+Repeater+Can+t+Find+File

Body:
The AsyncFileUpload works. Only issue is the file name disappears when the LinkButton to repeat the AsyncFileUpload control is pressed. Is there a way to get and store the file name? FileName does not work. Not really keen on sharing code-behind but may do so if it is necessary to solve this issue.

<asp:UpdatePanel ID="LibraryResourceUpdatePanel" runat="server">
        <ContentTemplate>

                <asp:Repeater ID="RptRequest" runat="server" OnItemDataBound="RptRequest_ItemDataBound">
                    <ItemTemplate>

                                <asp:LinkButton ID="LbRemoveRequest" CssClass="ic fa fa-minus-circle" runat="server" OnClick="LbRemoveRequest_Click" CausesValidation="false"></asp:LinkButton>
                                Remove

Details of Resources

                            <asp:Literal ID="LitCount" runat="server"></asp:Literal>

                                    <fieldset class="form-group">
                                        <legend>Accession No.</legend>
                                        <asp:TextBox ID="TxbAccessionNumber" CssClass="form-control" runat="server" />
                                        <asp:RequiredFieldValidator runat="server" ControlToValidate="TxbAccessionNumber" ErrorMessage="Email is required" ForeColor="Red" Display="Dynamic" />
                                    </fieldset>

                                    <fieldset class="form-group">
                                        <legend>Details</legend>
                                        <asp:TextBox ID="TxbDetails" runat="server" Rows="4" TextMode="MultiLine" />
                                        <asp:RequiredFieldValidator runat="server" ControlToValidate="TxbDetails" ErrorMessage="Details are required" ForeColor="Red" Display="Dynamic" />
                                    </fieldset>

                                    <fieldset class="form-group">
                                        <legend>Image</legend>
                                        <ajaxToolkit:AsyncFileUpload runat="server"
                                            ID="FileUpload" OnUploadedComplete="FileUpload_UploadedComplete" ClientIDMode="AutoID" PersistFile="true"/>
                                        <asp:RequiredFieldValidator runat="server" ControlToValidate="FileUpload" ErrorMessage="File Upload required" ForeColor="Red" Display="Dynamic" />
                                    </fieldset>

                    </ItemTemplate>
                </asp:Repeater>

                <asp:LinkButton ID="LbAddRequest" CssClass="ic fa fa-plus-circle" runat="server" OnClick="LbAddRequest_Click" CausesValidation="false" ></asp:LinkButton>
                Add another request

        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="LbAddRequest" EventName="click" />
        </Triggers>
    </asp:UpdatePanel>

Body:
First add command name to linkbutton and remove click event:

<asp:LinkButton ID="LbAddRequest" runat="server"
    CommandName="AddRequest"></asp:LinkButton>
<span>Add another request</span>

And try this ItemCommand event in code-behind to get in work:

protected void RptRequest_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    if (e.CommandName == "AddRequest")
    {
        FileUpload myFileUpload = (FileUpload)e.Item.FindControl("FileUpload");
        if (myFileUpload.HasFile)
        {
            try
            {
                string filename = Path.GetFileName(myFileUpload.FileName);
                myFileUpload.SaveAs(Server.MapPath("~/") + filename);
                myStatusLabel.Text = "Upload Success";
            }
            catch (Exception ex)
            {

                myStatusLabel.Text = "Upload Fail" + ex.Message;
            }
        }
        else
        {

            myStatusLabel.Text = "myFileUpload Has No File";
        }
    }
}

Read detail here : https://forums.asp.net/t/1904302.aspx?FileUpload+Inside+a+Repeater+Can+t+Find+File


问:
Trigger two Javascript actions with onclick
I have a button that need to trigger a div and a Google Analytics event. I can't get this to work. Right now, the div triggers fine, but the GA event does not trigger.

This is the HTML:

```<code><a class="knappmedium knappfeedbackyes" href="#" onclick="showFeedback('yes');ga('send', 'event', 'Feedback', 'Feedback positive', 'PAGEURL');">YES</a>
</code>```

Edit:
This button will be on multiple pages, with the GA tacking parameters unique for each instance it is used.

Help would be very much appreciated!

Kind regards,
Pete

答:
Your code is correct, verify that:

You are using google analytics.js instead of gtag.js. You can follow the instructions here.

Verify that you have added correctly analitycs js here

The analitycs.js should be added before the events that you want to call.

Verify that you have the correct GA api key.

Body:
I have a button that need to trigger a div and a Google Analytics event. I can't get this to work. Right now, the div triggers fine, but the GA event does not trigger.

This is the HTML:

YES

Edit:
This button will be on multiple pages, with the GA tacking parameters unique for each instance it is used.

Help would be very much appreciated!

Kind regards,
Pete


问:
Scale background image to wrap content of layout
I have a layout that contains some text fields and has a background image that's displayed at the top of my activity.  I'd like the background image to scale to wrap the content (don't care about aspect ratio).  However, the image is larger than content, so the layout instead wraps the background image.  Here's my original code:

```<code><RelativeLayout
    android:layout_width="fill_parent"
    android:id="@+id/HeaderList"
    android:layout_gravity="top"
    android:layout_height="wrap_content"
    android:background="@drawable/header">
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:id="@+id/NameText"
        android:text="Jhn Doe"
        android:textColor="#FFFFFF"
        android:textSize="30sp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:paddingLeft="4dp"
        android:paddingTop="4dp"
    />
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:textColor="#FFFFFF"
        android:layout_alignParentLeft="true"
        android:id="@+id/HoursText"
        android:text="170 hours"
        android:textSize="23sp"
        android:layout_below="@+id/NameText"
        android:paddingLeft="4dp"
    />
</RelativeLayout>
</code>```

After searching through some other questions, I found these two:

How to wrap content views rather than background drawable?

Scale a Drawable or background image?

Based on this, I created a FrameLayout w/ an ImageView showing the background.  Unfortunately, I still can't get it to work.  I want the height of the background image to shrink/expand w/ the size of the text views, but with the FrameLayout, the ImageView fits to the size of it's parent, and I can't find a way to make the parent fit to the size the text view layout.  Here's my updated code:

```<code><FrameLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <ImageView android:src="@drawable/header"
        android:layout_width="fill_parent"
        android:scaleType="fitXY"
        android:layout_height="fill_parent"
        />
    <RelativeLayout
        android:layout_width="fill_parent"
        android:id="@+id/HeaderList"
        android:layout_gravity="top"
        android:layout_height="wrap_content"
        >
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:id="@+id/NameText"
            android:text="John Doe"
            android:textColor="#FFFFFF"
            android:textSize="30sp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:paddingLeft="4dp"
            android:paddingTop="4dp"
            />
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:textColor="#FFFFFF"
            android:layout_alignParentLeft="true"
            android:id="@+id/HoursText"
            android:text="170 hours"
            android:textSize="23sp"
            android:layout_below="@+id/NameText"
            android:paddingLeft="4dp"
            />
    </RelativeLayout>
</FrameLayout>
</code>```

Does anybody have any suggestions for how best to make an image scale to the size of the contents of some layout?  I'm not concerned with the aspect ratio of the image, as it won't matter, I just want it to fill the background.

Thanks!

答: I think I've done something similar to this in the past, try playing with the gravity setting in your image view, I think one of them should do what you're after.</p>

Body:
I have a layout that contains some text fields and has a background image that's displayed at the top of my activity.  I'd like the background image to scale to wrap the content (don't care about aspect ratio).  However, the image is larger than content, so the layout instead wraps the background image.  Here's my original code:

<RelativeLayout
    android:layout_width="fill_parent"
    android:id="@+id/HeaderList"
    android:layout_gravity="top"
    android:layout_height="wrap_content"
    android:background="@drawable/header">
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:id="@+id/NameText"
        android:text="Jhn Doe"
        android:textColor="#FFFFFF"
        android:textSize="30sp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:paddingLeft="4dp"
        android:paddingTop="4dp"
    />
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:textColor="#FFFFFF"
        android:layout_alignParentLeft="true"
        android:id="@+id/HoursText"
        android:text="170 hours"
        android:textSize="23sp"
        android:layout_below="@+id/NameText"
        android:paddingLeft="4dp"
    />
</RelativeLayout>

After searching through some other questions, I found these two:

How to wrap content views rather than background drawable?

Scale a Drawable or background image?

Based on this, I created a FrameLayout w/ an ImageView showing the background.  Unfortunately, I still can't get it to work.  I want the height of the background image to shrink/expand w/ the size of the text views, but with the FrameLayout, the ImageView fits to the size of it's parent, and I can't find a way to make the parent fit to the size the text view layout.  Here's my updated code:

<FrameLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <ImageView android:src="@drawable/header"
        android:layout_width="fill_parent"
        android:scaleType="fitXY"
        android:layout_height="fill_parent"
        />
    <RelativeLayout
        android:layout_width="fill_parent"
        android:id="@+id/HeaderList"
        android:layout_gravity="top"
        android:layout_height="wrap_content"
        >
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:id="@+id/NameText"
            android:text="John Doe"
            android:textColor="#FFFFFF"
            android:textSize="30sp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:paddingLeft="4dp"
            android:paddingTop="4dp"
            />
        <TextView
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:textColor="#FFFFFF"
            android:layout_alignParentLeft="true"
            android:id="@+id/HoursText"
            android:text="170 hours"
            android:textSize="23sp"
            android:layout_below="@+id/NameText"
            android:paddingLeft="4dp"
            />
    </RelativeLayout>
</FrameLayout>

Does anybody have any suggestions for how best to make an image scale to the size of the contents of some layout?  I'm not concerned with the aspect ratio of the image, as it won't matter, I just want it to fill the background.

Thanks!


问:
Check if electron app is launched with admin privileges on windows
Is there a way to check if an electron app is launched with the admin rights?

I only found electron-sudo lib to execute commands with admin privileges.

But I have multiple commands to execute and I do not want to prompt the user every time.

So how can I check if the app is started with admin privileges using electron ?

The best thing would be just to execute a command inside the software ex: .isAdminPrivilegesUsed (can be a script that is executed on Windows) that return true or false, and if false :

I will prompt the user that he has to restart the software with admin rights and close it

答:
If you are using electron-packager, just add --win32metadata.requested-execution-level=requireAdministrator. Eg:

electron-packager app --asar=true --platform=win32 --arch=ia32 --win32metadata.requested-execution-level=requireAdministrator --overwrite

ContentLicense: CC BY-SA 4.0


问:
Java / Scala math library with elliptic integrals and bessel functions?
I am looking for a math library for scientific computing to use in Java / Scala. Especially I need complete elliptic integrals und modified Bessel functions. I would be nice if it is open source, but I guess I will have to take whatever is out there. A scipy (python lib for scientific computing) replacment would be great :-)</p>

答:
As far as I'm aware, the most widely used Java math libraries are:

The Apache Commons Math library, and

The Colt project (developed by CERN)

You'll have to investigate their respective APIs though to determine if they provide exactly the functionality you require.


问:
How to set variable to for each items
I have the below code
c:set var = "device" value = "{a.sortList}"

Now i neeed to iterate the loop with device

Like below

```<code>c: forEach items = "device"
</code>```

this will throw error.

So Please help me , I want to declare the variable globally and use that list inside foreach with that variable , how to achieve. Sorry for any syntax mistakes as I am typing from a mobile

答:
Try this:</p>

```<code><c:set var = "devices" value = "{a.sortList}"/>
<c:forEach items="${devices}" var="device">
    ${device}
</c:forEach>
</code>```

Title: How to set variable to for each items

Body:
I have the below code
c:set var = "device" value = "{a.sortList}"

Now i neeed to iterate the loop with device

Like below

c: forEach items = "device"

this will throw error.

So Please help me , I want to declare the variable globally and use that list inside foreach with that variable , how to achieve. Sorry for any syntax mistakes as I am typing from a mobile

Body:
Try this:

<c:set var = "devices" value = "{a.sortList}"/>
<c:forEach items="${devices}" var="device">
    ${device}
</c:forEach>


问:
Why i can not set image style height 100% for height as same as div container?
Why i can not set image style height 100% for height as same as div container ?

When i tried to test code it's will be show like this.

https://i.imgur.com/Q1MGP0Z.png

I want to show image like this.

https://i.imgur.com/GeLUUCo.png

with class name img_look style height: 100%; How can i do ?

.li_look{
    padding: 0px;
    margin: 0;
    position: relative;
    width: 25%;
    border-right: 3px solid #fff;
    margin-right: -3px;
    z-index: 11;
    float: left;
    list-style: none;
    color: #333;
    font-size: 19px;
    background: #fff;
}
.div_1{
    float: none;
    margin: 0;
    width: 100%;
    height: 197.207px;
    display: block;
    position: relative;
}
.a_tag{
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    height: 100%;
    margin-left: auto;
    margin-right: auto;
    overflow: hidden;
    display: block;
    cursor: pointer;
}
.div_2{
    transform: translateX(-50%);
    left: 50%;
    top: 0;
    background-color: transparent;
    display: block;
    position: absolute;
}
.img_look{
    height: 100%;
    display: block;
    margin-left: auto;
    margin-right: auto;
    max-width: unset;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li class="li_look">
    <div class="div_1">

        <div class="div_2">
          <img src="https://i2.wp.com/www.thisblogrules.com/wp-content/uploads/2010/02/man-and-bear-bath.jpg?resize=550%2C356" class="img_look">
        </div>

    </div>
  </li>
</ul></code>```

答:
The problem lies with the parent container of the img tag. Since, there is no height defined for it, you cannot use 100% in relation to the parent container. Define a height as shown below in my code for .div_2. And it will work fine.

.li_look{
    padding: 0px;
    margin: 0;
    position: relative;
    width: 25%;
    border-right: 3px solid #fff;
    margin-right: -3px;
    z-index: 11;
    float: left;
    list-style: none;
    color: #333;
    font-size: 19px;
    background: #fff;
}
.div_1{
    float: none;
    margin: 0;
    width: 100%;
    height: 197.207px;
    display: block;
    position: relative;
}
.a_tag{
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    height: 100%;
    width:100%;
    margin-left: auto;
    margin-right: auto;
    overflow: hidden;
    display: block;
    cursor: pointer;
}
.div_2{
    transform: translateX(-50%);
    left: 50%;
    top: 0;
    background-color: transparent;
    display: block;
    position: absolute;
    height:100%;
}
.img_look{
    height: 100%;
    display: block;
    margin-left: auto;
    margin-right: auto;
    max-width: unset;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li class="li_look">
    <div class="div_1">

        <div class="div_2">
          <img src="https://i2.wp.com/www.thisblogrules.com/wp-content/uploads/2010/02/man-and-bear-bath.jpg?resize=550%2C356" class="img_look">
        </div>

    </div>
  </li>
</ul></code>```

Body:
The problem lies with the parent container of the img tag. Since, there is no height defined for it, you cannot use 100% in relation to the parent container. Define a height as shown below in my code for .div_2. And it will work fine.

.li_look{
    padding: 0px;
    margin: 0;
    position: relative;
    width: 25%;
    border-right: 3px solid #fff;
    margin-right: -3px;
    z-index: 11;
    float: left;
    list-style: none;
    color: #333;
    font-size: 19px;
    background: #fff;
}
.div_1{
    float: none;
    margin: 0;
    width: 100%;
    height: 197.207px;
    display: block;
    position: relative;
}
.a_tag{
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    height: 100%;
    width:100%;
    margin-left: auto;
    margin-right: auto;
    overflow: hidden;
    display: block;
    cursor: pointer;
}
.div_2{
    transform: translateX(-50%);
    left: 50%;
    top: 0;
    background-color: transparent;
    display: block;
    position: absolute;
    height:100%;
}
.img_look{
    height: 100%;
    display: block;
    margin-left: auto;
    margin-right: auto;
    max-width: unset;

}

<ul>
  <li class="li_look">
    <div class="div_1">
      <a href="#" class="a_tag">
        <div class="div_2">
          <img src="https://i2.wp.com/www.thisblogrules.com/wp-content/uploads/2010/02/man-and-bear-bath.jpg?resize=550%2C356" class="img_look">
        </div>
      </a>
    </div>
  </li>
</ul>


问:
How do I get a RaycastHit to work with an HMD in Unity?
I wrote a script that allows the user to teleport between two spots by looking at designated objects. Specifically, it uses a ray to check whether one of the two objects is in the center of the screen. It works with the standard FPSController (placed under Main Camera) and mouse controls. When I enable VR support, the detection stops working (not just for the center point, but for the whole display). What should I add to my script to make it work with Oculus the same way it works with the mouse?

This code works by detecting objects by name and then teleporting to assigned objects by tag:

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

public class lookTeleport : MonoBehaviour
{
    public GameObject destination;
    public Transform target;
    RaycastHit hit;
    Ray ray;

    void Start ()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update ()
    {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition); //mouse control
        if (Physics.Raycast(ray, out hit))
        {
            if (hit.collider.gameObject.name == "teleporterA")
            {
                //Debug.Log("teleporter A detected");
                destination = GameObject.FindWithTag("teleportY");
                transform.position = destination.transform.position;
            }
            if (hit.collider.gameObject.name == "teleporterB")
            {
                //Debug.Log("teleporter B detected");
                destination = GameObject.FindWithTag("teleportX");
                transform.position = destination.transform.position;
            }
        }
    }
}
</code>```

I think I will have to look into replacing Input.MousePosition with the VR equivalent.

答:
You should replace ray = Camera.main.ScreenPointToRay(Input.mousePosition);

 with ray = Camera.main.ScreenPointToRay(new Vector2(Screen.height / 2, Screen.width / 2));
 Since you are in VR, and not using a mouse, the Input.mousePosition can't be used as a screen-point to cast the ray from, instead you could use the middle of the screen that the user sees (like crosshairs)

Body:
I wrote a script that allows the user to teleport between two spots by looking at designated objects. Specifically, it uses a ray to check whether one of the two objects is in the center of the screen. It works with the standard FPSController (placed under Main Camera) and mouse controls. When I enable VR support, the detection stops working (not just for the center point, but for the whole display). What should I add to my script to make it work with Oculus the same way it works with the mouse?

This code works by detecting objects by name and then teleporting to assigned objects by tag:

using UnityEngine;
using System.Collections;
using UnityEngine.VR;

public class lookTeleport : MonoBehaviour
{
    public GameObject destination;
    public Transform target;
    RaycastHit hit;
    Ray ray;

    void Start ()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update ()
    {
        ray = Camera.main.ScreenPointToRay(Input.mousePosition); //mouse control
        if (Physics.Raycast(ray, out hit))
        {
            if (hit.collider.gameObject.name == "teleporterA")
            {
                //Debug.Log("teleporter A detected");
                destination = GameObject.FindWithTag("teleportY");
                transform.position = destination.transform.position;
            }
            if (hit.collider.gameObject.name == "teleporterB")
            {
                //Debug.Log("teleporter B detected");
                destination = GameObject.FindWithTag("teleportX");
                transform.position = destination.transform.position;
            }
        }
    }
}

I think I will have to look into replacing Input.MousePosition with the VR equivalent.


问:
timthumb not working after site migration
I just move my site from xfactorapp.com and any new uploaded picture has no thumbnail. Image is on server but thumbnail is not generated.

How can i change that code to make thumbnail visible from new server?

```<code>function href_t`imthumb($file, $set = null, $xf = true) {
if (!$set || !$xf) {
    $timthumb = webpath_assets('/timthumb.php');
    $href = $timthumb . '?src=' . $file;
    if (xcount($set) > 0) {
        foreach ($set as $k => $v) {
            $href .= '&' . $k . '=' . $v;
        }
    }
    return $href;
} else {
    $param['w'] = 150;
    $param['h'] = 150;
    $param['zc'] = 0;
    $param['q'] = 90;
    if (DEV) {
        $app = DEV_PREFIX . APP_VERSION;
    } else {
        $app = LIVE_PREFIX . APP_VERSION;
    }
    if (xcount($set) > 0) {
        foreach ($set as $k => $v) {
            $param[$k] = $v;
        }
        $file = '/' . $app . $file;
        $protocol = 'http';
        if (isSSL()) {
            $protocol = 'https';
        }
return $protocol . '://thumb.xfactorapp.com/tt/' . implode('/', $param) . $file;
    }
}
}
</code>```

wich give me:

```<code><img class="img-responsive" alt="building" src="http://thumb.xfactorapp.com/tt/263/147/2/90/v3/uploads/_lifttec/cms/58529051881f8f0d87ab1401/5947fffeac28b_200-ATJ-Platforma-autoridicatoare-articulata.jpg">
</code>```

i wish to change code to take thumbnail with parnam properties but from upload not from thumb.xfactorapp.com

Thanks

答: Just change $xf from true to false $xf = false.</p>

Body:
I just move my site from xfactorapp.com and any new uploaded picture has no thumbnail. Image is on server but thumbnail is not generated.

How can i change that code to make thumbnail visible from new server?

function href_t`imthumb($file, $set = null, $xf = true) {
if (!$set || !$xf) {
    $timthumb = webpath_assets('/timthumb.php');
    $href = $timthumb . '?src=' . $file;
    if (xcount($set) > 0) {
        foreach ($set as $k => $v) {
            $href .= '&' . $k . '=' . $v;
        }
    }
    return $href;
} else {
    $param['w'] = 150;
    $param['h'] = 150;
    $param['zc'] = 0;
    $param['q'] = 90;
    if (DEV) {
        $app = DEV_PREFIX . APP_VERSION;
    } else {
        $app = LIVE_PREFIX . APP_VERSION;
    }
    if (xcount($set) > 0) {
        foreach ($set as $k => $v) {
            $param[$k] = $v;
        }
        $file = '/' . $app . $file;
        $protocol = 'http';
        if (isSSL()) {
            $protocol = 'https';
        }
return $protocol . '://thumb.xfactorapp.com/tt/' . implode('/', $param) . $file;
    }
}
}

wich give me:

i wish to change code to take thumbnail with parnam properties but from upload not from thumb.xfactorapp.com

Thanks


问:
How to run Elastic Beanstalk commands on EC2 instance before connecting Resources
We have a situation where we would like to run a Django server in the usual Elastic Beanstalk manner while hooking up a custom Docker container to be used by the Django website. So far, I basically have the following .ebextensions configuration file:

```<code>packages:
  yum:
    ecs-init: []

files:
  /etc/ecs/ecs.config:
    mode: "000644"
    owner/group: root
    content: ECS_CLUSTER=${Ref: MyCluster}

commands:
  01_start_docker: sudo service docker start
  02_start_ecs: sudo start ecs

Resources:
  MyCluster:
    Type: AWS::ECS::Cluster
  MyService:
    Type: AWS::ECS::Service
    Properties:
      Cluster: ${Ref: MyCluster}
      DesiredCount: 1
      TaskDefinition: ${Ref: MyTask}
  MyTask:
    Type: AWS::ECS::TaskDefinition
    Properties:
      ContainerDefinitions:
        - ...
</code>```

The problem is that the ECS service is trying to start up before the Elastic Beanstalk-provided EC2 instance is registered with the cluster. As a result, deploying to Elastic Beanstalk hangs. If I manually SSH'ed into the EC2 instance and manually installed ecs-init, created ecs.config, and ran the commands, the service continues being created and the EB environment is created successfully.

Is there a way to tell the service to wait until the EC2 instance created by EB's autoscaling group is registered with the cluster?

More context:

We want the Django server to be able to access the Docker container with localhost, but I wouldn't be opposed to including an EC2 instance in Resources specifically to host the Docker container, if it's easy to refer to in the auto-scaled EC2 instances

We've tried the multi-docker container approach, but this way seems closer to EB's usage (having the web server files directly in the environment instead of making a docker image for the environment to run)

答:
Try something like the below. As EB is just CloudFormation stacks look at the stacks beginning with awseb- to find yours. Then look at the CF Resources while your EB app deploys to see the names used by the predefined EB resources that you aren't specifying in the .ebextensions. I see AWSEBInstanceLaunchWaitCondition in mine, which appears to relate to the initial instances launch.</p>

```<code>Resources:
  MyService:
    Type: AWS::ECS::Service
    Properties:
      Cluster: ${Ref: MyCluster}
      DesiredCount: 1
      TaskDefinition: ${Ref: MyTask}
    DependsOn: AWSEBInstanceLaunchWaitCondition
</code>```

Body:
We have a situation where we would like to run a Django server in the usual Elastic Beanstalk manner while hooking up a custom Docker container to be used by the Django website. So far, I basically have the following .ebextensions configuration file:

packages:
  yum:
    ecs-init: []

files:
  /etc/ecs/ecs.config:
    mode: "000644"
    owner/group: root
    content: ECS_CLUSTER=${Ref: MyCluster}

commands:
  01_start_docker: sudo service docker start
  02_start_ecs: sudo start ecs

Resources:
  MyCluster:
    Type: AWS::ECS::Cluster
  MyService:
    Type: AWS::ECS::Service
    Properties:
      Cluster: ${Ref: MyCluster}
      DesiredCount: 1
      TaskDefinition: ${Ref: MyTask}
  MyTask:
    Type: AWS::ECS::TaskDefinition
    Properties:
      ContainerDefinitions:
        - ...

The problem is that the ECS service is trying to start up before the Elastic Beanstalk-provided EC2 instance is registered with the cluster. As a result, deploying to Elastic Beanstalk hangs. If I manually SSH'ed into the EC2 instance and manually installed ecs-init, created ecs.config, and ran the commands, the service continues being created and the EB environment is created successfully.

Is there a way to tell the service to wait until the EC2 instance created by EB's autoscaling group is registered with the cluster?

More context:

We want the Django server to be able to access the Docker container with localhost, but I wouldn't be opposed to including an EC2 instance in Resources specifically to host the Docker container, if it's easy to refer to in the auto-scaled EC2 instances

We've tried the multi-docker container approach, but this way seems closer to EB's usage (having the web server files directly in the environment instead of making a docker image for the environment to run)

Body:
Try something like the below. As EB is just CloudFormation stacks look at the stacks beginning with awseb- to find yours. Then look at the CF Resources while your EB app deploys to see the names used by the predefined EB resources that you aren't specifying in the .ebextensions. I see AWSEBInstanceLaunchWaitCondition in mine, which appears to relate to the initial instances launch.

Resources:
  MyService:
    Type: AWS::ECS::Service
    Properties:
      Cluster: ${Ref: MyCluster}
      DesiredCount: 1
      TaskDefinition: ${Ref: MyTask}
    DependsOn: AWSEBInstanceLaunchWaitCondition


问:
change inline class Style property using javascript/jquery
How to change inline class Style property using javascript/jquery.
for example:

```<code><style>
.iexp-info-bar-body {
    background-color: #000000;
}
</style>
<div class="iexp-info-bar-body">
//data
</div>
</code>```

i want to change background-color property of a class .iexp-info-bar-body  #000000 to #C04848 .

Please not that i know inline css technique/using !important keyword to change color.

But i want to change all the occurance of a class .iexp-info-bar-body property
ie
i need a result like

```<code><style>
.iexp-info-bar-body {
    background-color: #C04848;
}
</style>
<div class="iexp-info-bar-body">
//data
</code>```

答:
Have a look at a library called jss. Added or modifying classes is as simple as

```<code>jss.set('.demo', {
    'font-size': '15px',
    'color': 'red'
});
</code>```

This uses the style technique in the header to define the classes similar to the second code block in your question.

Body:
How to change inline class Style property using javascript/jquery.
for example:

//data

i want to change background-color property of a class .iexp-info-bar-body  #000000 to #C04848 .

Please not that i know inline css technique/using !important keyword to change color.

But i want to change all the occurance of a class .iexp-info-bar-body property
ie
i need a result like

//data

Body:
Have a look at a library called jss. Added or modifying classes is as simple as

jss.set('.demo', {
    'font-size': '15px',
    'color': 'red'
});

This uses the style technique in the header to define the classes similar to the second code block in your question.