问:
AsyncTask vs new Thread
I have an app that use with web service.

The action with the web service maybe will take a few seconds, when i search in google a way for handler with this concept i saw that i can use AsyncTask or new Thread.

I explain my basic action app.
In the MainActivity i have two fields username and password.
The MainActivity get from the user the inputs and send those inputs to function in ActionClass and there I use with WSClass.
In the function class i sent to web service and wait to the response.

How can i create the white circle when the user wait to my
actions app?

What the best option to use?(AsyncTask/new Thread)

MainActivity:

```<code>public class MainActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ActionClass = ActionClass.getInstans();
        ActionClass.setContext(this);
        ActionClass.login("username","password");// in the future in put a PlainText for username and password.
        if(isLogin == true)
        {
            //here i move to another activity....
        }
    }
}

public class ActionClass
{
    public void setContext(Context context) {
        if (this.context == null) {
            this.context = context;
            WSClass = new WSClass();
        }
    }
  public static ActionClass getInstans() {
        if (instans == null) {
            synchronized (ActionClass.class) {
                if (instans == null)
                    instans = new ActionClass();
            }
        }

        return instans;
    }

    public boolean login(String username, String password) {
    {
        WSClass.loginWs(url,username, password, object.class);
    }
}

     public class WSClass
     {
          public <T> T login(String URL,String username,String  password,
          Class<T> output)
          {

          //...Do Something...
          }
     }
</code>```

Update the qustion
The WsClass use with generic function that get and return <T> variable.

After i checked the AsyncTask... AsyncTask can be use as generic if not how can i resolve this?

The function in WSClass updated above.

Thanks,

Tal

答:
In my opinion Using Async Task is better.

Async task is created from Handler and Thread to handle asynchronous purpose.
For Handling Some task where execution time is short(for a few seconds) and having background works use Async task always. Async task executes Like an Individual thread without interpreting the UI Thread.

AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

Title: AsyncTask vs new Thread

Body:
I have an app that use with web service.

The action with the web service maybe will take a few seconds, when i search in google a way for handler with this concept i saw that i can use AsyncTask or new Thread.

I explain my basic action app.
In the MainActivity i have two fields username and password.
The MainActivity get from the user the inputs and send those inputs to function in ActionClass and there I use with WSClass.
In the function class i sent to web service and wait to the response.

How can i create the white circle when the user wait to my
actions app?

What the best option to use?(AsyncTask/new Thread)

MainActivity:

public class MainActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ActionClass = ActionClass.getInstans();
        ActionClass.setContext(this);
        ActionClass.login("username","password");// in the future in put a PlainText for username and password.
        if(isLogin == true)
        {
            //here i move to another activity....
        }
    }
}

public class ActionClass
{
    public void setContext(Context context) {
        if (this.context == null) {
            this.context = context;
            WSClass = new WSClass();
        }
    }
  public static ActionClass getInstans() {
        if (instans == null) {
            synchronized (ActionClass.class) {
                if (instans == null)
                    instans = new ActionClass();
            }
        }

        return instans;
    }

    public boolean login(String username, String password) {
    {
        WSClass.loginWs(url,username, password, object.class);
    }
}

     public class WSClass
     {
          public <T> T login(String URL,String username,String  password,
          Class<T> output)
          {

          //...Do Something...
          }
     }

Update the qustion
The WsClass use with generic function that get and return <T> variable.

After i checked the AsyncTask... AsyncTask can be use as generic if not how can i resolve this?

The function in WSClass updated above.

Thanks,

Tal


来源: stackexchange

问:
Xamarin Forms Images not loading from remote URL
I have a demo xamarin forms project that simply displays an image with its image source set to a remote URL. But the problem is it works for some URL and does not for others. I have picked up random image links from google image search and compiled a list of the working / non-working ones. Any insight on this strange behavior is hugely appreciated.

Thanks in Advance!

Working URLs

https://i.ytimg.com/vi/JTxPzXQ1Sso/maxresdefault.jpg

https://media-cdn.tripadvisor.com/media/photo-s/09/97/8c/27/castle-rock-trading-post.jpg

https://www.xamarin.com/content/images/pages/forms/example-app.png

Non-Working URLs

https://www.seminolehardrockhollywood.com/files/1637/Utilities-EventsCalendar-1250x450.jpg

http://melangesimsr.com.103-21-58-169.sdin-pp-wb3.webhostbox.net/Assets/UplaodedFiles/20171122090840812.png

https://www.chicagotraveler.com/sites/default/files/concerts-chicago-big-1.jpg

XAML file

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:XamarinImageTest"
             x:Class="XamarinImageTest.MainPage"
             BackgroundColor="#000000">

    <ContentPage.Content>
        <Image Source="https://i.ytimg.com/vi/JTxPzXQ1Sso/maxresdefault.jpg"
               VerticalOptions="Fill"
               HorizontalOptions="Fill"></Image>
    </ContentPage.Content>
</ContentPage>
</code>```

答:
Use native http client handlers + TLS2.0 for your app (can be set in project settings):

https://developer.xamarin.com/guides/android/application_fundamentals/http-stack/

https://developer.xamarin.com/guides/cross-platform/macios/http-stack/

For iOS also enable http downloads:

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

ContentLicense: CC BY-SA 3.0

Body:
I have a demo xamarin forms project that simply displays an image with its image source set to a remote URL. But the problem is it works for some URL and does not for others. I have picked up random image links from google image search and compiled a list of the working / non-working ones. Any insight on this strange behavior is hugely appreciated.

Thanks in Advance!

Working URLs

https://i.ytimg.com/vi/JTxPzXQ1Sso/maxresdefault.jpg

https://media-cdn.tripadvisor.com/media/photo-s/09/97/8c/27/castle-rock-trading-post.jpg

https://www.xamarin.com/content/images/pages/forms/example-app.png

Non-Working URLs

https://www.seminolehardrockhollywood.com/files/1637/Utilities-EventsCalendar-1250x450.jpg

http://melangesimsr.com.103-21-58-169.sdin-pp-wb3.webhostbox.net/Assets/UplaodedFiles/20171122090840812.png

https://www.chicagotraveler.com/sites/default/files/concerts-chicago-big-1.jpg

XAML file

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:XamarinImageTest"
             x:Class="XamarinImageTest.MainPage"
             BackgroundColor="#000000">

    <ContentPage.Content>
        <Image Source="https://i.ytimg.com/vi/JTxPzXQ1Sso/maxresdefault.jpg"
               VerticalOptions="Fill"
               HorizontalOptions="Fill"></Image>
    </ContentPage.Content>
</ContentPage>


问:
How do I sort DataList by result of function - SilverStripe 4
I have a set of objects Person that I would like to sort based on a score that is calculated by a  function on the object Score().

While I can easily display the Score() in ModelAdmin I am unable to sort by that field as it's not a db field. The score changes each day based on a few of the other fields in the db so it's not something that would be suitable to store itself.

I suspected there would be a function which is the equivilent of filterByCallback() such as sortByCallback() but I can't seem to find that existing.

I don't need it to be added in the ModelAdmin gridField but I would like to use it in a report. How have others got around this problem?

Cheers

答:
You could always sort with the native PHP methods. Eg.

```<code>$list = Person::get()->toArray();
usort($list, function($a, $b){
    // will sort in descending order. To reverse, swap $b and $a
    return $b->Score() - $a->Score();
});
</code>```

If you need to, you can then still convert to an ArrayList:

```<code>ArrayList::create($list);
</code>```

As UncleCheese pointed out in his comment, this can be quite slow and memory intensive… it really depends on how many records you're planning to sort.

Body:
You could always sort with the native PHP methods. Eg.

$list = Person::get()->toArray();
usort($list, function($a, $b){
    // will sort in descending order. To reverse, swap $b and $a
    return $b->Score() - $a->Score();
});

If you need to, you can then still convert to an ArrayList:

ArrayList::create($list);

As UncleCheese pointed out in his comment, this can be quite slow and memory intensive… it really depends on how many records you're planning to sort.


问:
Is it okay to create a Seed Node which does not host any shard or proxyShard
I have a 3 node cluster with

1 S1 - Seed Node
2 S2 - A node that hosts a shard SRD (which has S1 as seed node in config)
3 S3 - A node that hosts the proxy shard of the shard hosted in S2 (which has S1 as seed node in config)

Here S1 just creates the actorsystem, and does nothing else

When I Start the cluster (S1 first, then S2 and S3) and When S3 tries to send a message to the shard SRD(using the proxyshard actor ref), it complains:

```<code>WARN  akka.cluster.sharding.ShardRegion - Trying to register to coordinator at [Some(ActorSelection[Anchor(akka.tcp://ngage-akka-seed-cluster@akka-0.akka-svc.default.svc.cluster.local:2551/),
Path(/system/sharding/CallEntityCoordinator/singleton/coordinator)])], but no acknowledgement. Total [1] buffered messages.
</code>```

Here - akka-0.akka-svc.default.svc.cluster.local is the Seed node!!!, why is it contacting Seed node (which does not have any shard) instead of S2 ?

答:
By default akka-cluster-sharding shards and shard proxies will automatically assume, that corresponding regions are living on all nodes in the cluster. You can however apply constraint on that - both shard region and proxy allows you to specify the cluster role, i.e.:

```<code># HOCON config
akka.cluster.roles = [ "sharding" ]
akka.cluster.sharding.role = "sharding"
</code>```

You can also specify it manually:

// shard region - current cluster node must have that role
ClusterSharding(system).start(
    typeName = "Counter",
    entityProps = Props[Counter],
    settings = ClusterShardingSettings(system).withRole("sharding"),
    extractEntityId = extractEntityId,
    extractShardId = extractShardId)

// shard region proxy - current cluster node doesn't need to have that role
ClusterSharding(system).startProxy(
    typeName = "Counter",
    role = "sharding",
    dataCenter = Some("B"),
    extractEntityId = extractEntityId,
    extractShardId = extractShardId)
```

If it has been configured, cluster sharding will look up for shard regions only on cluster nodes with that role specified. You can use this mechanic to exclude seed nodes from the list of the nodes, cluster sharding will try to contact with.

Body:
I have a 3 node cluster with

1 S1 - Seed Node
2 S2 - A node that hosts a shard SRD (which has S1 as seed node in config)
3 S3 - A node that hosts the proxy shard of the shard hosted in S2 (which has S1 as seed node in config)

Here S1 just creates the actorsystem, and does nothing else

When I Start the cluster (S1 first, then S2 and S3) and When S3 tries to send a message to the shard SRD(using the proxyshard actor ref), it complains:

WARN  akka.cluster.sharding.ShardRegion - Trying to register to coordinator at [Some(ActorSelection[Anchor(akka.tcp://ngage-akka-seed-cluster@akka-0.akka-svc.default.svc.cluster.local:2551/),
Path(/system/sharding/CallEntityCoordinator/singleton/coordinator)])], but no acknowledgement. Total [1] buffered messages.

Here - akka-0.akka-svc.default.svc.cluster.local is the Seed node!!!, why is it contacting Seed node (which does not have any shard) instead of S2 ?

Body:
By default akka-cluster-sharding shards and shard proxies will automatically assume, that corresponding regions are living on all nodes in the cluster. You can however apply constraint on that - both shard region and proxy allows you to specify the cluster role, i.e.:

# HOCON config
akka.cluster.roles = [ "sharding" ]
akka.cluster.sharding.role = "sharding"

You can also specify it manually:

// shard region - current cluster node must have that role
ClusterSharding(system).start(
    typeName = "Counter",
    entityProps = Props[Counter],
    settings = ClusterShardingSettings(system).withRole("sharding"),
    extractEntityId = extractEntityId,
    extractShardId = extractShardId)

// shard region proxy - current cluster node doesn't need to have that role
ClusterSharding(system).startProxy(
    typeName = "Counter",
    role = "sharding",
    dataCenter = Some("B"),
    extractEntityId = extractEntityId,
    extractShardId = extractShardId)

If it has been configured, cluster sharding will look up for shard regions only on cluster nodes with that role specified. You can use this mechanic to exclude seed nodes from the list of the nodes, cluster sharding will try to contact with.


问:
How do I attach camera to Spark.components.VideoDisplay
I'm using Flash Builder and created a spark-application Flex project that will stream video from the local camera. If I use mx.controls.VideoDisplay; there is no problem since it has attachCamera(camera) method. But Spark's VideoDisplay component does not have that method. I know I can use mx controls inside a Spark app but I want to know:

What is the real difference between spark.components.VideoDisplay and mx.controls.VideoDisplay?

How do I attach camera to spark.components.VideoDisplay?

Is there any advantages if I go with spark (since it's newer to mx library)?

thanks.

EDIT: In the documentation this is mentioned: "Starting with Flex 4.0, Adobe recommends that you use the spark.components.VideoPlayer  class as an alternative to this class. (mx.controls.VideoDisplay)"

答:
Here are the specifics to get this working:</p>

```<code>import mx.events.FlexEvent;

import org.osmf.net.StreamType;

import spark.components.mediaClasses.DynamicStreamingVideoItem;
import spark.components.mediaClasses.DynamicStreamingVideoSource;

private var _cam:DynamicStreamingVideoSource =  new DynamicStreamingVideoSource();
private var _dynVideoSource:DynamicStreamingVideoSource;

protected function application1_creationCompleteHandler(event:FlexEvent):void
{

    _dynVideoSource=new DynamicStreamingVideoSource();

    var videoItems:Vector.<DynamicStreamingVideoItem>;
    videoItems=new Vector.<DynamicStreamingVideoItem>();
    videoItems[0]=new DynamicStreamingVideoItem();

    _dynVideoSource.host= "";
    _dynVideoSource.streamType=StreamType.LIVE;
    _dynVideoSource.streamItems=videoItems;

    mycam.source=_dynVideoSource;

    var cam:Camera = Camera.getCamera(); //Camera.names[0]);
    cam.setMode(640, 480, 15);
    cam.setQuality(0, 80);
    mycam.videoObject.attachCamera(cam);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here are the specifics to get this working:

import mx.events.FlexEvent;

import org.osmf.net.StreamType;

import spark.components.mediaClasses.DynamicStreamingVideoItem;
import spark.components.mediaClasses.DynamicStreamingVideoSource;

private var _cam:DynamicStreamingVideoSource =  new DynamicStreamingVideoSource();
private var _dynVideoSource:DynamicStreamingVideoSource;

protected function application1_creationCompleteHandler(event:FlexEvent):void
{

    _dynVideoSource=new DynamicStreamingVideoSource();

    var videoItems:Vector.<DynamicStreamingVideoItem>;
    videoItems=new Vector.<DynamicStreamingVideoItem>();
    videoItems[0]=new DynamicStreamingVideoItem();

    _dynVideoSource.host= "";
    _dynVideoSource.streamType=StreamType.LIVE;
    _dynVideoSource.streamItems=videoItems;

    mycam.source=_dynVideoSource;

    var cam:Camera = Camera.getCamera(); //Camera.names[0]);
    cam.setMode(640, 480, 15);
    cam.setQuality(0, 80);
    mycam.videoObject.attachCamera(cam);
}


问:
Open Facebook group page using Facebook app on IOS
In my IOS app, I want to open facebook app to a GROUP.

On Android, I simply opened the following URL:

"fb://group/12345678/" (I replaced the group id for this example)

This worked fine on android. When trying the same thing in IOS:

```<code> [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"fb://group/12345678/"]];
</code>```

Facebook app opens but I get:

"The link you followed may have been broken, or the page may have been removed."

I can't find any other ways to open to a public facebook group from IOS.

Thanks

答:
You can use profile and group ID to open Facebook group in facebook app, detail code:

```<code>NSURL *facebookGroupURL = [NSURL URLWithString:@"fb://profile/123456/"];
if ([[UIApplication sharedApplication] canOpenURL:facebookGroupURL]) {
    [[UIApplication sharedApplication] openURL:facebookGroupURL];
}
else {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.facebook.com/groups/123456/"]];
}
</code>```

Browse:
enter image description here

Mobile:
enter image description here

It works for me on Xcode 9.1/iOS 11.1.2

Body:
In my IOS app, I want to open facebook app to a GROUP.

On Android, I simply opened the following URL:

"fb://group/12345678/" (I replaced the group id for this example)

This worked fine on android. When trying the same thing in IOS:

 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"fb://group/12345678/"]];

Facebook app opens but I get:

"The link you followed may have been broken, or the page may have been removed."

I can't find any other ways to open to a public facebook group from IOS.

Thanks

Body:
You can use profile and group ID to open Facebook group in facebook app, detail code:

NSURL *facebookGroupURL = [NSURL URLWithString:@"fb://profile/123456/"];
if ([[UIApplication sharedApplication] canOpenURL:facebookGroupURL]) {
    [[UIApplication sharedApplication] openURL:facebookGroupURL];
}
else {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.facebook.com/groups/123456/"]];
}

Browse:
enter image description here

Mobile:
enter image description here

It works for me on Xcode 9.1/iOS 11.1.2


问:
Missing one element of dictionary cause of If statement
i use this code to store items of dictionaries in doc variable.
This code works fine but I miss the first element of time because of the if statement.

```<code>def convert(old):
    time_key = 'Time '
    # Save the time
    time_item = (time_key, old[time_key])
    # Add remove it
    del old[time_key]
    # Copy remaining items to new dicts and save them in a list
    return [dict([time_item, item]) for item in old.items()]

row = {
    'Time ': '2017-12-01T13:54:04',
    'Energy [kWh]': '0.01',
    'Voltage [V]': '221.64',
    'Current [A]': '0.08',
}

new_data = convert(row)
#print(new_data)
Zeitvalue= ""
Device=""
Value=""
for d in new_data:
    #print(d)
    for key, value in d.items():
        if key == 'Time ':
            Zeitvalue = value
            #print(value)
            continue
        else:
            Device = key
            Value = value
        doc = {'Time ':Zeitvalue,'Device':Device, 'Measure':Value}
        print("This is doc variable:",doc) # doc vaiable with missed time element
</code>```

SO when i print doc i got this
Output:

```<code>doc:     {'Device': 'Voltage [V]', 'Measure': '221.64', 'Time ': ''} # **ISSUE: variable time is missed here, How to fix it ?**
   doc:     {'Device': 'Current [A]', 'Measure': '0.08', 'Time ': '2017-12-01T13:54:04'}
   doc:     {'Device': 'Energy [kWh]', 'Measure': '0.01', 'Time ': '2017-12-01T13:54:04'}
</code>```

答:
you have problem in this line:

doc = {'Time ':Zeitvalue,'Device':Device, 'Measure':Value} when you use it inside the for loop! , each iteration overrides the previous assignment, furthermore - you cause unexpected behavior , since dictionary is not order data structure - meaning : if you encountered "tine" key first - it will work fine , but if you did not encountered 'time' first - the value of it is still == "" , since you initiate it to that value and you did not updated it since.

move the doc = {'Time ':Zeitvalue,'Device':Device, 'Measure':Value} to the outer loop , and not the one going over each key and value and you will be fine.

Body:
i use this code to store items of dictionaries in doc variable.
This code works fine but I miss the first element of time because of the if statement.

def convert(old):
    time_key = 'Time '
    # Save the time
    time_item = (time_key, old[time_key])
    # Add remove it
    del old[time_key]
    # Copy remaining items to new dicts and save them in a list
    return [dict([time_item, item]) for item in old.items()]

row = {
    'Time ': '2017-12-01T13:54:04',
    'Energy [kWh]': '0.01',
    'Voltage [V]': '221.64',
    'Current [A]': '0.08',
}

new_data = convert(row)
#print(new_data)
Zeitvalue= ""
Device=""
Value=""
for d in new_data:
    #print(d)
    for key, value in d.items():
        if key == 'Time ':
            Zeitvalue = value
            #print(value)
            continue
        else:
            Device = key
            Value = value
        doc = {'Time ':Zeitvalue,'Device':Device, 'Measure':Value}
        print("This is doc variable:",doc) # doc vaiable with missed time element

SO when i print doc i got this
Output:

doc:     {'Device': 'Voltage [V]', 'Measure': '221.64', 'Time ': ''} # **ISSUE: variable time is missed here, How to fix it ?**
   doc:     {'Device': 'Current [A]', 'Measure': '0.08', 'Time ': '2017-12-01T13:54:04'}
   doc:     {'Device': 'Energy [kWh]', 'Measure': '0.01', 'Time ': '2017-12-01T13:54:04'}


问:
Not able to open webpage on firefox browser in my macbook

I am trying to open google page on my MacBook getting error
</p>

```<code>package practice;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Test {

    public static void main(String[] args) {

        System.setProperty("webdriver.firefox.marionette", "/Users/swapnilasingh/eclipse-workspace/practice/practice/geckodriver");
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.com");
    }
}
</code>```

<p>
Expect to open google homepage on firefox
</p>

```<code>Exception in thread "main" org.openqa.selenium.WebDriverException: Timed out waiting 45 seconds for Firefox to start.
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z'
System info: host: 'swapnilas-MBP.Dlink', ip: '192.168.0.25', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.13.1', java.version: '1.8.0_152'
Driver info: driver.version: FirefoxDriver
    at org.openqa.selenium.firefox.XpiDriverService.waitUntilAvailable(XpiDriverService.java:112)
    at org.openqa.selenium.firefox.XpiDriverService.start(XpiDriverService.java:97)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:217)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:140)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:120)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:98)
    at practice.Test.main(Test.java:19)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:43144/hub/status] to be available after 45007 ms
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100)
    at org.openqa.selenium.firefox.XpiDriverService.waitUntilAvailable(XpiDriverService.java:110)
    ... 8 more
Caused by: java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask.get(FutureTask.java:205)
    at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:147)
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75)
    ... 9 more
</code>```

答:
Please rewrite your code like this.</p>

```<code> public static void main(String[] args) {

    System.setProperty("webdriver.gecko.driver", "/Users/swapnilasingh/eclipse-workspace/practice/practice/geckodriver");
    WebDriver driver = new FirefoxDriver();
    driver.get("http://www.google.com");
}
</code>```

Body:
I am trying to open google page on my MacBook getting error

package practice;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Test {

    public static void main(String[] args) {

        System.setProperty("webdriver.firefox.marionette", "/Users/swapnilasingh/eclipse-workspace/practice/practice/geckodriver");
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.com");
    }
}

Expect to open google homepage on firefox

Exception in thread "main" org.openqa.selenium.WebDriverException: Timed out waiting 45 seconds for Firefox to start.
Build info: version: '3.6.0', revision: '6fbf3ec767', time: '2017-09-27T16:15:26.402Z'
System info: host: 'swapnilas-MBP.Dlink', ip: '192.168.0.25', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.13.1', java.version: '1.8.0_152'
Driver info: driver.version: FirefoxDriver
    at org.openqa.selenium.firefox.XpiDriverService.waitUntilAvailable(XpiDriverService.java:112)
    at org.openqa.selenium.firefox.XpiDriverService.start(XpiDriverService.java:97)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:586)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:217)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:140)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:120)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:98)
    at practice.Test.main(Test.java:19)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:43144/hub/status] to be available after 45007 ms
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100)
    at org.openqa.selenium.firefox.XpiDriverService.waitUntilAvailable(XpiDriverService.java:110)
    ... 8 more
Caused by: java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask.get(FutureTask.java:205)
    at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:147)
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75)
    ... 9 more

Body:
Please rewrite your code like this.

 public static void main(String[] args) {

    System.setProperty("webdriver.gecko.driver", "/Users/swapnilasingh/eclipse-workspace/practice/practice/geckodriver");
    WebDriver driver = new FirefoxDriver();
    driver.get("http://www.google.com");
}


问:
Android Emulator Stuck With Black Screen
I'm just new with Android Development, and running the default blank project. I have Android Studio 2.1.2.
The problem is the emulator stuck with the black screen although HAXM works well:
"HAX is working and emulator runs in fast virt mode"
Most solutions suggest to uncheck "use host gpu" in AVD Manager, yet it seems this feature no longer appear in the new version of Android Studio.
I run macOS El Capitan.</p>

答: Selecting CPU/ABI with Intel Atom(x86_64) (when creat a emulator or editing a emulator) worked for me.


问:
Does Google Guava Cache do deduplication when refreshing value of the same key
I implemented a non-blocking cache using Google Guava, there's only one key in the cache, and value for the key is only refreshed asynchronously (by overriding reload()).

My question is that does Guava cache handle de-duplication if the first reload() task hasn't finished, and a new get() request comes in.

```<code>    //Cache is defined like below
    this.cache = CacheBuilder
            .newBuilder()
            .maximumSize(1)
            .refreshAfterWrite(10, TimeUnit.MINUTES)
            .recordStats()
            .build(loader);

//reload is overwritten asynchronously
@Override
public ListenableFuture<Map<String, CertificateInfo>> reload(final String key, Map<String, CertificateInfo> prevMap) throws IOException {
    LOGGER.info("Refreshing certificate cache.");
    ListenableFutureTask<Map<String, CertificateInfo>> task = ListenableFutureTask.create(new Callable<Map<String, CertificateInfo>>() {
        @Override
        public Map<String, CertificateInfo> call() throws Exception {
            return actuallyLoad();
        }
    });
    executor.execute(task);
    return task;
}
</code>```

答:
Yes, see the documentation for LoadingCache.get(K) (and it sibling, Cache.get(K, Runnable)):

If another call to get(K) or getUnchecked(K) is currently loading the value for key, simply waits for that thread to finish and returns its loaded value.

So if a cache entry is currently being computed (or reloaded/recomputed), other threads that try to retrieve that entry will simply wait for the computation to finish - they will not kick off their own redundant refresh.

Body:
I implemented a non-blocking cache using Google Guava, there's only one key in the cache, and value for the key is only refreshed asynchronously (by overriding reload()).

My question is that does Guava cache handle de-duplication if the first reload() task hasn't finished, and a new get() request comes in.

    //Cache is defined like below
    this.cache = CacheBuilder
            .newBuilder()
            .maximumSize(1)
            .refreshAfterWrite(10, TimeUnit.MINUTES)
            .recordStats()
            .build(loader);

//reload is overwritten asynchronously
@Override
public ListenableFuture<Map<String, CertificateInfo>> reload(final String key, Map<String, CertificateInfo> prevMap) throws IOException {
    LOGGER.info("Refreshing certificate cache.");
    ListenableFutureTask<Map<String, CertificateInfo>> task = ListenableFutureTask.create(new Callable<Map<String, CertificateInfo>>() {
        @Override
        public Map<String, CertificateInfo> call() throws Exception {
            return actuallyLoad();
        }
    });
    executor.execute(task);
    return task;
}


问:
image Intervention error
I am trying to add a logo onto the navbar but the image I used was too big so I saw this package called intervention image that almost everyone talks about and decided to use it. But before using it I am not sure if it is properly installed. This is what happen:

Added this into the composer.json:

```<code>"require": {
//"laravel/framework": "5.1.*", < -- didn't use this since there is a 5.5.*
   "intervention/image": "dev-master"
},
</code>```

run composer install

Added this inside config/app.php

Added inside the providers part:
Intervention\Image\ImageServiceProvider::class,

and added this inside the alias part:
'Image' => Intervention\Image\Facades\Image::class,

Run composer update and got this error:

I am not really sure if I should ignore it or not and continue using it but because I just started using image intervention, I don't want to messed up any installation since it might affect my code later on

While I am at it, I need to know if it is possible to resize the image in my navbar using imageIntervention in my app.blade.php in laravel.
Currently have something like this:

```<code>            <ul class="nav navbar-nav navbar-center">
                <img src="{{ URL::to('/image') }}/test.png">
            </ul>
</code>```

答:
To install intervention, run command

```<code>composer require intervention/image
</code>```

Intervention Docs

Title: image Intervention error

Body:
I am trying to add a logo onto the navbar but the image I used was too big so I saw this package called intervention image that almost everyone talks about and decided to use it. But before using it I am not sure if it is properly installed. This is what happen:

Added this into the composer.json:

"require": {
//"laravel/framework": "5.1.*", < -- didn't use this since there is a 5.5.*
   "intervention/image": "dev-master"
},

run composer install

Added this inside config/app.php

Added inside the providers part:
Intervention\Image\ImageServiceProvider::class,

and added this inside the alias part:
'Image' => Intervention\Image\Facades\Image::class,

Run composer update and got this error:

I am not really sure if I should ignore it or not and continue using it but because I just started using image intervention, I don't want to messed up any installation since it might affect my code later on

While I am at it, I need to know if it is possible to resize the image in my navbar using imageIntervention in my app.blade.php in laravel.
Currently have something like this:

Body:
To install intervention, run command

composer require intervention/image

Intervention Docs


问:
How to retrieve a shard region form a different cluster node in akka?
In the below code, how cluster node FrontendNode can get reference to the shard region "SomeShardRegion"
that is already started in the other cluster node BackendNode?
When I try the code below I get this exception: Shard type [SomeShardRegion] must be started first.

Note: I don't want to start another "SomeShardRegion" in FrontendNode!

```<code>object BackendNode extends App {
  implicit val system = ActorSystem("ClusterSystem", config)

  ClusterSharding(system).start(
    typeName = "SomeShardRegion",
    entityProps = someProps,
    settings = ClusterShardingSettings(system),
    extractEntityId = idExtractor,
    extractShardId = shardResolver)
}

object FrontendNode extends App {
  implicit val system = ActorSystem("ClusterSystem", config)

  // throws an exception:  Shard type [SomeShardRegion] must be started first
  val shardRegion = ClusterSharding(system).shardRegion("SomeShardRegion")
}
</code>```

答:
I found that a lot of people reference the documentation without pointing exactly where, so here is the link to the documentation, the closest point to the answer .

Quoting the documentation

Messages to the entities are always sent via the local ShardRegion.
  The ShardRegion actor reference for a named entity type is returned by
  ClusterSharding.start and it can also be retrieved with
  ClusterSharding.shardRegion. The ShardRegion will lookup the location
  of the shard for the entity if it does not already know its location.

Here a bit of code

```<code>// Selecting the ShardRegion with name Counter
val counterRegion: ActorRef = ClusterSharding(system).shardRegion("Counter")
counterRegion ! Message
</code>```

Body:
In the below code, how cluster node FrontendNode can get reference to the shard region "SomeShardRegion"
that is already started in the other cluster node BackendNode?
When I try the code below I get this exception: Shard type [SomeShardRegion] must be started first.

Note: I don't want to start another "SomeShardRegion" in FrontendNode!

object BackendNode extends App {
  implicit val system = ActorSystem("ClusterSystem", config)

  ClusterSharding(system).start(
    typeName = "SomeShardRegion",
    entityProps = someProps,
    settings = ClusterShardingSettings(system),
    extractEntityId = idExtractor,
    extractShardId = shardResolver)
}

object FrontendNode extends App {
  implicit val system = ActorSystem("ClusterSystem", config)

  // throws an exception:  Shard type [SomeShardRegion] must be started first
  val shardRegion = ClusterSharding(system).shardRegion("SomeShardRegion")
}

Body:
I found that a lot of people reference the documentation without pointing exactly where, so here is the link to the documentation, the closest point to the answer .

Quoting the documentation

Messages to the entities are always sent via the local ShardRegion.
  The ShardRegion actor reference for a named entity type is returned by
  ClusterSharding.start and it can also be retrieved with
  ClusterSharding.shardRegion. The ShardRegion will lookup the location
  of the shard for the entity if it does not already know its location.

Here a bit of code

// Selecting the ShardRegion with name Counter
val counterRegion: ActorRef = ClusterSharding(system).shardRegion("Counter")
counterRegion ! Message


问:
Soft reset on a Cortex-M using GDB
I'm working on a set of debugging tools for some in-house Cortex-M4 cores. I'm building embedded (no OS) ELF images using a gcc/binutils toolchain and simulating them using a modified version of QEMU. I'm creating the interrupt vector tables at the start (i.e. 0) of my images, and correctly initialising the stack pointer, and start address (i.e. the address of main).

The target programs are running as expected, and the debug tools which are built using the GDB remote protocol are working correctly.

What I'm currently trying to understand is how to initiate a soft-reset from GDB. That is, arrange for the target program to be reinitialised with the stack pointer reset to the initial value in the vector table, and the PC back at the start address.

I have already demonstrated to myself that the action of setting the PC value to 0, and running the core is not appropriate, and the result was that my "UsageFault" exception handler was invoked. (I assume that the core is in the wrong mode to execute this kind of action).

Is there a technique, i.e. by register writes using GDB remote protocol that I can soft-reset the simulated core, that is without having to power-cycle the QEMU session?

答:
This is a snippet of code for a Cortex-M3 I use to jump to any location with valid code in (including jumping to 0):

```<code>   IRQn_Type interrupt = (IRQn_Type)0;
   app_fn jump = *(app_fn *)(jumpaddr + sizeof(int));     //Reset is 2nd in table
   uint32_t stack_adr = *(uint32_t *)(jumpaddr);         //Stack pointer is 1st in table

   //Disable interrupts before jumping
   SysTick->CTRL &= ~ST_CTRL_ENABLE;

   while (interrupt <= CANActivity_IRQn)
   {
      NVIC_DisableIRQ(interrupt);
      interrupt++;
   }

   //Set the new stack pointer
   __set_MSP(stack_adr);

   //Set the new vector address
   SCB->VTOR = (location & 0x1FFFFF80);

   //Leap of faith!
   jump();
</code>```

This code assumes jumpaddr is the base address of a vector table, as the stack pointer is first in the table and reset handler is second in the table.

Disabling interrupts is a must as you could have an interrupt go off after you have moved the stack pointer which normally causes an exception.

Of course, doing it this way will not reset any peripherals so that would need to be done before enabling the interrupts again.

Edit:

You can find the contents of __set_MSP here.

Title: Soft reset on a Cortex-M using GDB

Body:
This is a snippet of code for a Cortex-M3 I use to jump to any location with valid code in (including jumping to 0):

   IRQn_Type interrupt = (IRQn_Type)0;
   app_fn jump = *(app_fn *)(jumpaddr + sizeof(int));     //Reset is 2nd in table
   uint32_t stack_adr = *(uint32_t *)(jumpaddr);         //Stack pointer is 1st in table

   //Disable interrupts before jumping
   SysTick->CTRL &= ~ST_CTRL_ENABLE;

   while (interrupt <= CANActivity_IRQn)
   {
      NVIC_DisableIRQ(interrupt);
      interrupt++;
   }

   //Set the new stack pointer
   __set_MSP(stack_adr);

   //Set the new vector address
   SCB->VTOR = (location & 0x1FFFFF80);

   //Leap of faith!
   jump();

This code assumes jumpaddr is the base address of a vector table, as the stack pointer is first in the table and reset handler is second in the table.

Disabling interrupts is a must as you could have an interrupt go off after you have moved the stack pointer which normally causes an exception.

Of course, doing it this way will not reset any peripherals so that would need to be done before enabling the interrupts again.

Edit:

You can find the contents of __set_MSP here.


问:
Exchangelib - Get meeting organizer mail
I'm currently using the exchangelib library in python. I would like to compare the mail of the account connected to exchangelib and the mail of a meeting organizer. I can have the account mail by typing "account.primary_smtp_address" but I don't know how I could get the meeting organizer mail.

For now i can only get the organizer's name by typing "item.subject" where "item" is my meeting.

Conversely, is it possible to get the account's name (the complete name: "Michael JORDAN" for example) which I could compare with the meeting organizer's name.

Thank you !

答: The meeting organizer is available on CalendarItem objects as item.organizer.


问:
Copying winforms between projects in Visual Studio
What is the best way to copy or cut/paste a form from one project to another project within a Solution in Visual Studio?

Whenever I try it, using the solution explorer (drag and drop or right clicking cut and paste), it only copies the underlying C# code and not the necessary 'bits and pieces' that help you visualise the form via the form designer.

答:
I am using Visual Studio 2010, below are the steps I performed:

Copy all 3 files (.cs, .resx, .Designer.cs) into destination project folder.

At Visual Studio, right click Project -> Add -> Existing Item...

Select all 3 files (.cs, .resx, .Designer.cs), click Add.

Change the namespace on 2 files (.cs, .Designer.cs), if it is different namespace on destination project.

Run the project.

Done!

ContentLicense: CC BY-SA 4.0


问:
Pull generated HTML programmatically vs. a HttpWebRequest
For our newsletter, I generate the final body of the email in a web page and then want to pull that into the body of the email. I found a way to do that with HttpWebRequest.

```<code>    private string GetHtmlBody(Guid id)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format("http://news.domain.com/News/View/{0}", id.ToString()));
        HttpWebResponse responce = (HttpWebResponse)request.GetResponse();
        System.IO.StreamReader sr = new System.IO.StreamReader(responce.GetResponseStream());

        return sr.ReadToEnd();
    }
</code>```

However, I feel there has to be a better way. Can I somehow pull the generated view without making a web call?

答:
You could use MVCContrib for this task.

Or try to roll some ugly code:

```<code>public static string ViewToString(string controlName, object viewData)
{
    var vd = new ViewDataDictionary(viewData);
    var vp = new ViewPage { ViewData = vd };
    var control = vp.LoadControl(controlName);
    vp.Controls.Add(control);
    var sb = new StringBuilder();
    using (var sw = new StringWriter(sb))
    using (HtmlTextWriter tw = new HtmlTextWriter(sw))
    {
        vp.RenderControl(tw);
    }
    return sb.ToString();
}
</code>```

and then:

```<code>var viewModel = ...
string template = ViewToString("~/Emails/EmailTemplate.ascx", viewModel);
</code>```

Body:
For our newsletter, I generate the final body of the email in a web page and then want to pull that into the body of the email. I found a way to do that with HttpWebRequest.

    private string GetHtmlBody(Guid id)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format("http://news.domain.com/News/View/{0}", id.ToString()));
        HttpWebResponse responce = (HttpWebResponse)request.GetResponse();
        System.IO.StreamReader sr = new System.IO.StreamReader(responce.GetResponseStream());

        return sr.ReadToEnd();
    }

However, I feel there has to be a better way. Can I somehow pull the generated view without making a web call?

Body:
You could use MVCContrib for this task.

Or try to roll some ugly code:

public static string ViewToString(string controlName, object viewData)
{
    var vd = new ViewDataDictionary(viewData);
    var vp = new ViewPage { ViewData = vd };
    var control = vp.LoadControl(controlName);
    vp.Controls.Add(control);
    var sb = new StringBuilder();
    using (var sw = new StringWriter(sb))
    using (HtmlTextWriter tw = new HtmlTextWriter(sw))
    {
        vp.RenderControl(tw);
    }
    return sb.ToString();
}

and then:

var viewModel = ...
string template = ViewToString("~/Emails/EmailTemplate.ascx", viewModel);


问:
Regex to get all the values in the html select tag
I'm trying to fetch all the values associated from a specific dropdown box

Example:

<select id='countries'>
    <option value='0'>All Categories</option>
    <option value='1'>USA</option>
    <option value='2'>China</option>
    <option selected='selected' value='3'>India</option>
    <option value='4'>Japan</option>
</select>

<select id='Gender'>
    <option value='0'>All Categories</option>
    <option selected='selected' value='1'>Male</option>
    <option value='2'>Female</option>
</select>

<select id='Body_ddlSite'>
    <option value='1'>Select-</option>
    <option value='2'>ECOSPACE</option>
    <option selected='selected' value='3'>MILLENNIUM TOWERS</option>
    <option value='4'>ABMIT-MT</option>
</select>
```

<p><strong>Note: consider above html as plain string</strong></p>

<p><strong>Result Should Be:</strong> <strong>For id='Gender'</strong></p>

<pre class="lang-none prettyprint-override"><code>0
1
2
</code>```

OR

All Categories
Male
Female
```

<p>For now I have tried to get all the <code><option></code> for a specifier <code><select>...</select></code> block by using this regex:</p>

<pre class="lang-regex prettyprint-override"><code>(?<=id='Gender'>)((.|\n)*?)(?=</select>)
</code>```

Result of above regex:

<option value='0'>All Categories</option>
<option selected='selected' value='1'>Male</option>
<option value='2'>Female</option>
```

But now I want to fetch all the value associated with it.

Body:
I'm trying to fetch all the values associated from a specific dropdown box

Example:

<select id='countries'>
    <option value='0'>All Categories</option>
    <option value='1'>USA</option>
    <option value='2'>China</option>
    <option selected='selected' value='3'>India</option>
    <option value='4'>Japan</option>
</select>

<select id='Gender'>
    <option value='0'>All Categories</option>
    <option selected='selected' value='1'>Male</option>
    <option value='2'>Female</option>
</select>

<select id='Body_ddlSite'>
    <option value='1'>Select-</option>
    <option value='2'>ECOSPACE</option>
    <option selected='selected' value='3'>MILLENNIUM TOWERS</option>
    <option value='4'>ABMIT-MT</option>
</select>

Note: consider above html as plain string

Result Should Be: For id='Gender'

0
1
2

OR

All Categories
Male
Female

For now I have tried to get all the <option> for a specifier <select>...</select> block by using this regex:

(?<=id='Gender'>)((.|\n)*?)(?=</select>)

Result of above regex:

<option value='0'>All Categories</option>
<option selected='selected' value='1'>Male</option>
<option value='2'>Female</option>

But now I want to fetch all the value associated with it.

Body:
This works for me:

(?:\G(?!\A)|\bid='Gender'>)\s*<option\s[^<]*?value='(?<val>\d+)'>(?<txt>[^<]*)</option>


问:
Lines are not copying in Odoo
The Python code is below.Just check the function which is in the initial class have any error .

employee.py

```<code>import time
import math
import os, base64
from tempfile import TemporaryFile
import random

from odoo.osv import expression
from odoo.tools.float_utils import float_round as round
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.exceptions import UserError, ValidationError
from odoo import api, fields, models, _
#==================================================
# Class : BiEmployee
# Description : Employee Main Class
#==================================================
class BiEmployee(models.Model):
    _name = "bi.employee"
    _description = "Employee Module"
    _rec_name = "name"
    name = fields.Char(string='Name', required=False )
    emp_name = fields.Char(string = 'Employee Name')
    age = fields.Char(string = 'Age')
    address = fields.Text(string = 'Address')
    ug_degree = fields.Selection([('bcom', 'B.Com'),('be', 'BE'),('btech', 'B.Tech'),], string = 'Degree', required=True )

    # ten_mark = fields.Float("10th Mark")
    # plustwo_mark = fields.Float("12th Mark")
    # deg_mark = fields.Float("Degree Mark")

    employee_ids = fields.One2many('bi.employee.line','employee_id',"employee")
    employee_copy_ids = fields.One2many('bi.employee.line.copy','employee_copy_id')
    employee_line_idss = fields.One2many('bi.employee.copy','employee_line_id')

    @api.multi
    def button_confirm(self):
        line_obj = self.env['bi.employee.line']
        for file in self:
            values = {}
            vals = {
                'emp_name_copy':file.emp_name,
                'age_copy':file.age,
                'address_copy':file.address,
                'ug_degree_line':file.ug_degree,
                'employee_copy_id':file.id,
                }
            # raise UserError(_(str(vals)))
        self.env['bi.employee.line.copy'].create(vals)
        for line in line_obj:
            values = {
                'ten_mark_copy':line.ten_mark,
                'plustwo_mark_copy':line.plustwo_mark,
                'deg_mark_copy':line.deg_mark,
                'employee_line_id':line.id
            }
            # raise UserError(_(str(values)))
        self.env['bi.employee.copy'].create(values)

#==================================================
# Class : BiEmployeeLine
# Description : Employee Line
#==================================================

class BiEmployeeLine(models.Model):
    _name = "bi.employee.line"
    _description = "Employee line"
    # _rec_name = "name"

    ten_mark = fields.Float(string = '10th Mark')
    plustwo_mark = fields.Float(string = '12th Mark')
    deg_mark = fields.Float(string = 'Degree Mark')

    employee_id = fields.Many2one('bi.employee',"Employee")
    employee_line_ids = fields.One2many('bi.employee.copy','employee_line_id')

    # @api.multi
    # def button_confirms(self):
    #   for file in self:
    #       values = {
    #           'ten_mark_copy':file.ten_mark,
    #           'plustwo_mark_copy':file.plustwo_mark,
    #           'deg_mark_copy':file.deg_mark,
    #           'employee_line_id':file.id
    #           }
    #   self.env['bi.employee.copy'].create(values)

#==================================================
# Class : BiEmployeeLineCopy
# Description : Employee Line Copy
#==================================================

class BiEmployeeLineCopy(models.Model):
    _name = "bi.employee.line.copy"
    _description = "Employee Line Copy"

    emp_name_copy = fields.Char(string = 'Employee Name')
    age_copy = fields.Char(string = 'Age')
    address_copy = fields.Char(string = 'Address')
    ug_degree_line = fields.Char(string='Degree')

    employee_line_copy_ids = fields.One2many('bi.employee.copy','employee_line_copy_id')
    employee_copy_id = fields.Many2one('bi.employee')

#==================================================
# Class : BiEmployeeCopy
# Description : Employee Copy
#==================================================

class BiEmployeeCopy(models.Model):
    _name = "bi.employee.copy"
    _description = "Employee Copy"

    ten_mark_copy = fields.Float(string = '10th Mark')
    plustwo_mark_copy = fields.Float(string = '12th Mark')
    deg_mark_copy = fields.Float(string = 'Degree Mark')
    employee_line_copy_id = fields.Many2one('bi.employee.line.copy')
    employee_line_id = fields.Many2one('bi.employee.line')
</code>```

The XML code is just below:
employee.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>
    <data>
       <menuitem name="Employee Details"
            id="bi_menu_employee_root"
            web_icon="bi_employee,static/description/icon.png"/>

        <menuitem
            id="bi_menu_employee_main"
            name="Details"
            parent="bi_employee.bi_menu_employee_root"
            sequence="0"/>

        <record id="bi_view_employee_tree" model="ir.ui.view">
            <field name="name">bi.employee.tree</field>
            <field name="model">bi.employee</field>
            <field name="arch" type="xml">
                <tree string="Employee">
                    <field name="emp_name"/>
                </tree>
            </field>
        </record>

        <record id="view_employee" model="ir.ui.view">
            <field name="name">bi.employee.form</field>
            <field name="model">bi.employee</field>
            <field name="arch" type="xml">
                <form string="Employee Details">
                    <header>
                        <button name = "button_confirm" string ="Confirm" class ="oe_highlight" type = "object"/>
                    </header>
                    <sheet>
                        <group>
                            <group>
                                <field name="emp_name"/>
                                <field name="ug_degree"/>
                            </group>
                            <group>
                                <field name="age"/>
                                <field name="address"/>
                            </group>
                        </group>
                    <notebook>
                    <page string="Academic Details">
                        <field name="employee_ids">
                            <tree string="Employee Information" editable="bottom">
                                <field name="ten_mark"/>
                                <field name="plustwo_mark"/>
                                <field name="deg_mark"/>
                            </tree>
                        </field>
                    </page>
                    </notebook>
                    </sheet>
                </form>
            </field>
        </record>

        <record id="bi_view_employee" model="ir.actions.act_window">
            <field name="name">Employee Management</field>
            <field name="res_model">bi.employee</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,form</field>
            <field name="domain">[]</field>
            <field name="context">{}</field>
            <field name="view_id" eval="False"/>
            <field name="help" type="html">
                <p class="oe_view_nocontent_create">
                </p>
            </field>
        </record>

        <menuitem
            id="bi_menu_employee_details"
            name="Employee Details"
            action = "bi_view_employee"
            parent="bi_employee.bi_menu_employee_main"
            sequence="1"/>

        <record id="bi_view_employee_line_copy_tree" model="ir.ui.view">
            <field name="name">bi.employee.line.copy.tree</field>
            <field name="model">bi.employee.line.copy</field>
            <field name="arch" type="xml">
                <tree string="Employee">
                    <field name="emp_name_copy"/>
                </tree>
            </field>
        </record>

        <record id="view_employee_line_copy_form" model="ir.ui.view">
            <field name="name">bi.employee.line.copy.form</field>
            <field name="model">bi.employee.line.copy</field>
            <field name="arch" type="xml">
                <form string="Employee Details Copy">

                    <sheet>
                        <group>
                            <group>
                                <field name="emp_name_copy"/>
                                <field name="ug_degree_line"/>
                            </group>
                            <group>
                                <field name="age_copy"/>
                                <field name="address_copy"/>
                            </group>
                        </group>
                    <notebook>
                    <page string="Academic Details">
                        <field name="employee_line_copy_ids">

                            <tree string="Employee Information" editable="bottom">
                                <field name="ten_mark_copy"/>
                                <field name="plustwo_mark_copy"/>
                                <field name="deg_mark_copy"/>
                            </tree>
                        </field>
                    </page>
                    </notebook>
                    </sheet>
                </form>
            </field>
        </record>

        <record id="bi_view_employee_line_copy" model="ir.actions.act_window">
            <field name="name">Employee Management</field>
            <field name="res_model">bi.employee.line.copy</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,form</field>
            <field name="domain">[]</field>
            <field name="context">{}</field>
            <field name="view_id" eval="False"/>
            <field name="help" type="html">
                <p class="oe_view_nocontent_create">
                </p>
            </field>
        </record>

        <menuitem
            id="bi_menu_employee_line_copy_details"
            name="Employee Details Copy"
            action = "bi_view_employee_line_copy"
            parent="bi_employee.bi_menu_employee_main"
            sequence="2"/>

    </data>
</odoo>
</code>```

I need to copy all the fields to another object including line when I click 'Confirm' button.But unfortunately the lines are not copying.Can anybody help ?

答:
Finally I got the answer. Here the code it is.

```<code>@api.multi
    def button_confirm(self):
        line_obj = self.env['bi.employee.line']
        for file in self:

            vals = {
                'emp_name_copy':file.emp_name,
                'age_copy':file.age,
                'address_copy':file.address,
                'ug_degree_line':file.ug_degree
                # 'employee_copy_id':file.id,
                }
            # raise UserError(_(str(vals)))
        order = self.env['bi.employee.line.copy'].create(vals)
        for line in self.employee_ids:
            values = {
                    'ten_mark_copy':line.ten_mark,
                    'plustwo_mark_copy':line.plustwo_mark,
                    'deg_mark_copy':line.deg_mark,
                    'employee_line_copy_id':order.id
                }
            # raise UserError(_(str(values)))
        self.env['bi.employee.copy'].create(values)
</code>```

Hope it may help someone.Thanks in advance.

Title: Lines are not copying in Odoo

Body:
The Python code is below.Just check the function which is in the initial class have any error .

employee.py

import time
import math
import os, base64
from tempfile import TemporaryFile
import random

from odoo.osv import expression
from odoo.tools.float_utils import float_round as round
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.exceptions import UserError, ValidationError
from odoo import api, fields, models, _
#==================================================
# Class : BiEmployee
# Description : Employee Main Class
#==================================================
class BiEmployee(models.Model):
    _name = "bi.employee"
    _description = "Employee Module"
    _rec_name = "name"
    name = fields.Char(string='Name', required=False )
    emp_name = fields.Char(string = 'Employee Name')
    age = fields.Char(string = 'Age')
    address = fields.Text(string = 'Address')
    ug_degree = fields.Selection([('bcom', 'B.Com'),('be', 'BE'),('btech', 'B.Tech'),], string = 'Degree', required=True )

    # ten_mark = fields.Float("10th Mark")
    # plustwo_mark = fields.Float("12th Mark")
    # deg_mark = fields.Float("Degree Mark")

    employee_ids = fields.One2many('bi.employee.line','employee_id',"employee")
    employee_copy_ids = fields.One2many('bi.employee.line.copy','employee_copy_id')
    employee_line_idss = fields.One2many('bi.employee.copy','employee_line_id')

    @api.multi
    def button_confirm(self):
        line_obj = self.env['bi.employee.line']
        for file in self:
            values = {}
            vals = {
                'emp_name_copy':file.emp_name,
                'age_copy':file.age,
                'address_copy':file.address,
                'ug_degree_line':file.ug_degree,
                'employee_copy_id':file.id,
                }
            # raise UserError(_(str(vals)))
        self.env['bi.employee.line.copy'].create(vals)
        for line in line_obj:
            values = {
                'ten_mark_copy':line.ten_mark,
                'plustwo_mark_copy':line.plustwo_mark,
                'deg_mark_copy':line.deg_mark,
                'employee_line_id':line.id
            }
            # raise UserError(_(str(values)))
        self.env['bi.employee.copy'].create(values)

#==================================================
# Class : BiEmployeeLine
# Description : Employee Line
#==================================================

class BiEmployeeLine(models.Model):
    _name = "bi.employee.line"
    _description = "Employee line"
    # _rec_name = "name"

    ten_mark = fields.Float(string = '10th Mark')
    plustwo_mark = fields.Float(string = '12th Mark')
    deg_mark = fields.Float(string = 'Degree Mark')

    employee_id = fields.Many2one('bi.employee',"Employee")
    employee_line_ids = fields.One2many('bi.employee.copy','employee_line_id')

    # @api.multi
    # def button_confirms(self):
    #   for file in self:
    #       values = {
    #           'ten_mark_copy':file.ten_mark,
    #           'plustwo_mark_copy':file.plustwo_mark,
    #           'deg_mark_copy':file.deg_mark,
    #           'employee_line_id':file.id
    #           }
    #   self.env['bi.employee.copy'].create(values)

#==================================================
# Class : BiEmployeeLineCopy
# Description : Employee Line Copy
#==================================================

class BiEmployeeLineCopy(models.Model):
    _name = "bi.employee.line.copy"
    _description = "Employee Line Copy"

    emp_name_copy = fields.Char(string = 'Employee Name')
    age_copy = fields.Char(string = 'Age')
    address_copy = fields.Char(string = 'Address')
    ug_degree_line = fields.Char(string='Degree')

    employee_line_copy_ids = fields.One2many('bi.employee.copy','employee_line_copy_id')
    employee_copy_id = fields.Many2one('bi.employee')

#==================================================
# Class : BiEmployeeCopy
# Description : Employee Copy
#==================================================

class BiEmployeeCopy(models.Model):
    _name = "bi.employee.copy"
    _description = "Employee Copy"

    ten_mark_copy = fields.Float(string = '10th Mark')
    plustwo_mark_copy = fields.Float(string = '12th Mark')
    deg_mark_copy = fields.Float(string = 'Degree Mark')
    employee_line_copy_id = fields.Many2one('bi.employee.line.copy')
    employee_line_id = fields.Many2one('bi.employee.line')

The XML code is just below:
employee.xml

<?xml version="1.0" encoding="utf-8"?>
<odoo>
    <data>
       <menuitem name="Employee Details"
            id="bi_menu_employee_root"
            web_icon="bi_employee,static/description/icon.png"/>

        <menuitem
            id="bi_menu_employee_main"
            name="Details"
            parent="bi_employee.bi_menu_employee_root"
            sequence="0"/>

        <record id="bi_view_employee_tree" model="ir.ui.view">
            <field name="name">bi.employee.tree</field>
            <field name="model">bi.employee</field>
            <field name="arch" type="xml">
                <tree string="Employee">
                    <field name="emp_name"/>
                </tree>
            </field>
        </record>

        <record id="view_employee" model="ir.ui.view">
            <field name="name">bi.employee.form</field>
            <field name="model">bi.employee</field>
            <field name="arch" type="xml">
                <form string="Employee Details">

                        <button name = "button_confirm" string ="Confirm" class ="oe_highlight" type = "object"/>

                    <sheet>
                        <group>
                            <group>
                                <field name="emp_name"/>
                                <field name="ug_degree"/>
                            </group>
                            <group>
                                <field name="age"/>
                                <field name="address"/>
                            </group>
                        </group>
                    <notebook>
                    <page string="Academic Details">
                        <field name="employee_ids">
                            <tree string="Employee Information" editable="bottom">
                                <field name="ten_mark"/>
                                <field name="plustwo_mark"/>
                                <field name="deg_mark"/>
                            </tree>
                        </field>
                    </page>
                    </notebook>
                    </sheet>
                </form>
            </field>
        </record>

        <record id="bi_view_employee" model="ir.actions.act_window">
            <field name="name">Employee Management</field>
            <field name="res_model">bi.employee</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,form</field>
            <field name="domain">[]</field>
            <field name="context">{}</field>
            <field name="view_id" eval="False"/>
            <field name="help" type="html">

            </field>
        </record>

        <menuitem
            id="bi_menu_employee_details"
            name="Employee Details"
            action = "bi_view_employee"
            parent="bi_employee.bi_menu_employee_main"
            sequence="1"/>

        <record id="bi_view_employee_line_copy_tree" model="ir.ui.view">
            <field name="name">bi.employee.line.copy.tree</field>
            <field name="model">bi.employee.line.copy</field>
            <field name="arch" type="xml">
                <tree string="Employee">
                    <field name="emp_name_copy"/>
                </tree>
            </field>
        </record>

        <record id="view_employee_line_copy_form" model="ir.ui.view">
            <field name="name">bi.employee.line.copy.form</field>
            <field name="model">bi.employee.line.copy</field>
            <field name="arch" type="xml">
                <form string="Employee Details Copy">

                    <sheet>
                        <group>
                            <group>
                                <field name="emp_name_copy"/>
                                <field name="ug_degree_line"/>
                            </group>
                            <group>
                                <field name="age_copy"/>
                                <field name="address_copy"/>
                            </group>
                        </group>
                    <notebook>
                    <page string="Academic Details">
                        <field name="employee_line_copy_ids">

                            <tree string="Employee Information" editable="bottom">
                                <field name="ten_mark_copy"/>
                                <field name="plustwo_mark_copy"/>
                                <field name="deg_mark_copy"/>
                            </tree>
                        </field>
                    </page>
                    </notebook>
                    </sheet>
                </form>
            </field>
        </record>

        <record id="bi_view_employee_line_copy" model="ir.actions.act_window">
            <field name="name">Employee Management</field>
            <field name="res_model">bi.employee.line.copy</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,form</field>
            <field name="domain">[]</field>
            <field name="context">{}</field>
            <field name="view_id" eval="False"/>
            <field name="help" type="html">

            </field>
        </record>

        <menuitem
            id="bi_menu_employee_line_copy_details"
            name="Employee Details Copy"
            action = "bi_view_employee_line_copy"
            parent="bi_employee.bi_menu_employee_main"
            sequence="2"/>

    </data>
</odoo>

I need to copy all the fields to another object including line when I click 'Confirm' button.But unfortunately the lines are not copying.Can anybody help ?

Body:
Finally I got the answer. Here the code it is.

@api.multi
    def button_confirm(self):
        line_obj = self.env['bi.employee.line']
        for file in self:

            vals = {
                'emp_name_copy':file.emp_name,
                'age_copy':file.age,
                'address_copy':file.address,
                'ug_degree_line':file.ug_degree
                # 'employee_copy_id':file.id,
                }
            # raise UserError(_(str(vals)))
        order = self.env['bi.employee.line.copy'].create(vals)
        for line in self.employee_ids:
            values = {
                    'ten_mark_copy':line.ten_mark,
                    'plustwo_mark_copy':line.plustwo_mark,
                    'deg_mark_copy':line.deg_mark,
                    'employee_line_copy_id':order.id
                }
            # raise UserError(_(str(values)))
        self.env['bi.employee.copy'].create(values)

Hope it may help someone.Thanks in advance.


问:
How to get value from upcomming row if condition is met?
I searched in google and SO but could not find any answer to my question.

I try to get a value from the first upcomming row if the condition is met.

Example:

```<code>Pupil   participation   bonus
  2           55          6
  2           33          3
  2           88          9
  2            0          -100
  2           44          4
  2           66          7
  2            0          -33
</code>```

to

```<code>Pupil   participation   bonus   bonusAtNoParti   sumBonusTillParticipation=0
  2           55          6          -94                    6+3+9 = 18
  2           33          3          -97                      3+9 = 12
  2           88          9          -91                       9
  2            0          -100        0                        0
  2           44          4          -29                     4+7=11
  2           66          7          -26                       7
  2            0          -33         0                        0
</code>```

So I need to do this:
Iterate through the dataframe and check next rows till participation equals to 0 and get the bonus from that line and add the bonus from the current line and write it to bonusAtNoPati.

My problem here is the "check next rows till participation equals to 0 and get the bonus from that line"
I know how to Iterate through the whole list but not after the current point(row)
I would need to do this process to the whole list where i can get any random participation value in random order.

Has anyone any idea how to realize it?

Edit, I also added another column("sumBonusTillParticipation=0", only sum value is required) which is even harder to realize. R is such a hard to learn language =(

答:
you can use which to get which row number participation is 0.

```<code>df <- read.table(text = 'Pupil   participation   bonus
             2           55          6
             2           33          3
             2           88          9
             2            0          -100
             2           44          4
             2           66          7
             2            0          -33', header = T)

index <- c(0, which(df$participation == 0))
diffs <- diff(index)
df$tp <- rep(df$bonus[index], times = diffs)
df$bonusAtNoParti <- df$bonus + df$tp
df$bonusAtNoParti[index] <- 0
df$tp <- NULL

     Pupil participation bonus bonusAtNoParti
 1     2            55     6            -94
 2     2            33     3            -97
 3     2            88     9            -91
 4     2             0  -100              0
 5     2            44     4            -29
 6     2            66     7            -26
 7     2             0   -33              0
</code>```

Body:
I searched in google and SO but could not find any answer to my question.

I try to get a value from the first upcomming row if the condition is met.

Example:

Pupil   participation   bonus
  2           55          6
  2           33          3
  2           88          9
  2            0          -100
  2           44          4
  2           66          7
  2            0          -33

to

Pupil   participation   bonus   bonusAtNoParti   sumBonusTillParticipation=0
  2           55          6          -94                    6+3+9 = 18
  2           33          3          -97                      3+9 = 12
  2           88          9          -91                       9
  2            0          -100        0                        0
  2           44          4          -29                     4+7=11
  2           66          7          -26                       7
  2            0          -33         0                        0

So I need to do this:
Iterate through the dataframe and check next rows till participation equals to 0 and get the bonus from that line and add the bonus from the current line and write it to bonusAtNoPati.

My problem here is the "check next rows till participation equals to 0 and get the bonus from that line"
I know how to Iterate through the whole list but not after the current point(row)
I would need to do this process to the whole list where i can get any random participation value in random order.

Has anyone any idea how to realize it?

Edit, I also added another column("sumBonusTillParticipation=0", only sum value is required) which is even harder to realize. R is such a hard to learn language =(

Body:
you can use which to get which row number participation is 0.

df <- read.table(text = 'Pupil   participation   bonus
             2           55          6
             2           33          3
             2           88          9
             2            0          -100
             2           44          4
             2           66          7
             2            0          -33', header = T)

index <- c(0, which(df$participation == 0))
diffs <- diff(index)
df$tp <- rep(df$bonus[index], times = diffs)
df$bonusAtNoParti <- df$bonus + df$tp
df$bonusAtNoParti[index] <- 0
df$tp <- NULL

     Pupil participation bonus bonusAtNoParti
 1     2            55     6            -94
 2     2            33     3            -97
 3     2            88     9            -91
 4     2             0  -100              0
 5     2            44     4            -29
 6     2            66     7            -26
 7     2             0   -33              0


问:
window.top.location.href is not working in Microsoft Edge browser
I have a web page http://example.com/search/ where we have a link, on click of that link we are opening an iframe in popup using colorbox jQuery plugin.

Then that iframe have a <button> element on click of that we are redirecting user to another web page. As it is inside an iframe so we are using following code:

```<code>mcbcarea.on("click", ".btnBook", function(){
   window.top.location.href = $(this).data("href");
});
</code>```

This code is working in all browsers, and even in all IE except in new IE Edge browser.

Currently it is not opening new button url, instead it is simply refreshing the parent page: http://example.com/search/

Can anyone please check and help here?

答:
change code:

```<code>window.top.location.href = $(this).data("href");
</code>```

To

top.window.location.href = $(this).data("href");

Body:
I have a web page http://example.com/search/ where we have a link, on click of that link we are opening an iframe in popup using colorbox jQuery plugin.

Then that iframe have a <button> element on click of that we are redirecting user to another web page. As it is inside an iframe so we are using following code:

mcbcarea.on("click", ".btnBook", function(){
   window.top.location.href = $(this).data("href");
});

This code is working in all browsers, and even in all IE except in new IE Edge browser.

Currently it is not opening new button url, instead it is simply refreshing the parent page: http://example.com/search/

Can anyone please check and help here?

Body:
change code:

window.top.location.href = $(this).data("href");

To

top.window.location.href = $(this).data("href");


问:
CSS: cant use alpha filter
I am want transparency a screen and show the screen behind

my css:

```<code>.correct-answer {
  background-color: #98CB66;
  filter: alpha(opacity=60);
  z-index: 10;
  opacity: 0.7;
  height: 100%;
  width: 100%;
}
</code>```

i tried use alpha filter in css,
and its not working

答:
if you just want to apply opacity to background-color then you could convert your hex to rgb and use it with alpha

```<code> background-color : rgba(152,203,102,0.6);
</code>```

In another case, if you want to apply opacity to whole block, then use CSS3 filter property.

```<code> -webkit-filter: opacity(60%); /* Safari 6.0 - 9.0 */
 filter : opacity(60%);
</code>```

Title: CSS: cant use alpha filter

Body:
I am want transparency a screen and show the screen behind

my css:

.correct-answer {
  background-color: #98CB66;
  filter: alpha(opacity=60);
  z-index: 10;
  opacity: 0.7;
  height: 100%;
  width: 100%;
}

i tried use alpha filter in css,
and its not working

Body:
if you just want to apply opacity to background-color then you could convert your hex to rgb and use it with alpha

 background-color : rgba(152,203,102,0.6);

In another case, if you want to apply opacity to whole block, then use CSS3 filter property.

 -webkit-filter: opacity(60%); /* Safari 6.0 - 9.0 */
 filter : opacity(60%);


问:
how to use 'getOwnPropertyNames' to iterate through contents of a map
I have the map posted below in the code section. I added some values to the map as shown.But when i tried to display the contents of the map using
'getOwnPropertyNames' as shown in th code, the log statement in the loop does not display any thing.

please let me know how to utilize 'getOwnPropertyNames' properly

code:

```<code>const mymap = new Map();

const mapKeyToValue = (key, value) => {
  mymap.set(key, value);
};

const getMyMap = () => mymap;

mapKeyToValue('1', [{ 'a': 10, 'b': 100, 'c': 1000 }]);
mapKeyToValue('2', [{ 'a': 20, 'b': 200, 'c': 2000 }]);
mapKeyToValue('3', [{ 'a': 30, 'b': 300, 'c': 3000 }]);
mapKeyToValue('4', [{ 'a': 40, 'b': 400, 'c': 4000 }]);

console.log(Object.getOwnPropertyNames(mymap));//displays []

Object.getOwnPropertyNames(mymap).forEach( (v) => {
  console.log(mymap[v]);//displays nothing
});
</code>```

答:
A map does not have properties (which would be limited to string and symbol keys). It stores its elements on the inside. To iterate through a Map, use its entries, values, keys, or implicit iterator methods with a for … of loop:

```<code>for (const [key, value] of mymap) {
    console.log(key, value);
}
</code>```

Body:
I have the map posted below in the code section. I added some values to the map as shown.But when i tried to display the contents of the map using
'getOwnPropertyNames' as shown in th code, the log statement in the loop does not display any thing.

please let me know how to utilize 'getOwnPropertyNames' properly

code:

const mymap = new Map();

const mapKeyToValue = (key, value) => {
  mymap.set(key, value);
};

const getMyMap = () => mymap;

mapKeyToValue('1', [{ 'a': 10, 'b': 100, 'c': 1000 }]);
mapKeyToValue('2', [{ 'a': 20, 'b': 200, 'c': 2000 }]);
mapKeyToValue('3', [{ 'a': 30, 'b': 300, 'c': 3000 }]);
mapKeyToValue('4', [{ 'a': 40, 'b': 400, 'c': 4000 }]);

console.log(Object.getOwnPropertyNames(mymap));//displays []

Object.getOwnPropertyNames(mymap).forEach( (v) => {
  console.log(mymap[v]);//displays nothing
});

Body:
A map does not have properties (which would be limited to string and symbol keys). It stores its elements on the inside. To iterate through a Map, use its entries, values, keys, or implicit iterator methods with a for … of loop:

for (const [key, value] of mymap) {
    console.log(key, value);
}


问:
_this.store.getState is not a function when testing react component with enzyme and mocha
I'm trying to test a React component with enzyme and mocha as follows

```<code>import { mount, shallow } from 'enzyme';
import React from 'react';
import chai, { expect } from 'chai'
import chaiEnzyme from 'chai-enzyme'
import sinon from 'sinon'

import MyComponent from 'myComponent'

chai.use(chaiEnzyme())
describe('MyComponent', () => {
  const store = {
    id: 1
  }
  it ('renders', () => {
    const wrapper = mount(<MyComponent />, {context: {store: store}})
  })
})
</code>```

haven't actually written the test as it fails at the declaration of wrapper

Error message: TypeError: _this.store.getState is not a function

No idea what the problem is and cant find anything addressing this!

Any help would be great!

答:
This error means that store can't get the state correctly.
I would recommend mocking the store using redux-mock-store
and import configureStore

```<code>import configureStore from 'redux-mock-store';
</code>```

then mock the state by doing this

```<code>    const initialState = { id: 1 };
    const mockStore = configureStore();
</code>```

and you can continue by wrapping your component with provider

```<code>import { Provider } from 'react-redux'; // add this to the top of your file

const wrapper = mount(
  <Provider store={mockStore(initialState)}>
    <MyComponent />
  </Provider>,
);
</code>```

Body:
I'm trying to test a React component with enzyme and mocha as follows

import { mount, shallow } from 'enzyme';
import React from 'react';
import chai, { expect } from 'chai'
import chaiEnzyme from 'chai-enzyme'
import sinon from 'sinon'

import MyComponent from 'myComponent'

chai.use(chaiEnzyme())
describe('MyComponent', () => {
  const store = {
    id: 1
  }
  it ('renders', () => {
    const wrapper = mount(<MyComponent />, {context: {store: store}})
  })
})

haven't actually written the test as it fails at the declaration of wrapper

Error message: TypeError: _this.store.getState is not a function

No idea what the problem is and cant find anything addressing this!

Any help would be great!

Body:
This error means that store can't get the state correctly.
I would recommend mocking the store using redux-mock-store
and import configureStore

import configureStore from 'redux-mock-store';

then mock the state by doing this

    const initialState = { id: 1 };
    const mockStore = configureStore();

and you can continue by wrapping your component with provider

import { Provider } from 'react-redux'; // add this to the top of your file

const wrapper = mount(
  <Provider store={mockStore(initialState)}>
    <MyComponent />
  </Provider>,
);


问:
Refactoring R code using ESS/R
I would like to know if it is possible to refactor R code in ESS. Using search and replace in Emacs does not seem to be a good alternative to it.</p>

答:
ESS itself does not provide any facilities for refactoring. Instead you can use emacs functionality.

Here is an example of how to replace all words starting with "xxx" and ending with "yyy" with "zzzzzz" in all your open R files in your project directory.

C-x d (enter dired)

% m r$ (mark all files ending in R or r)

Q (enter dired-to-query-replace-regexp)

type   xxx.*zzz  and  zzzzzz  when asked for replacement patterns.

accept, skip with y,n

Here is a complete tutorial of how to search-replace in multiple files.
and also how to save all modified buffers with ibuffer.

Title: Refactoring R code using ESS/R


问:
setting custom routes only form some pages in asp.net web forms
I made a website using asp.net webforms. It uses the default route which is url friendly. Can I set a custom route for some pages by assigning it to global.asax without affecting all other pages route?</p>

答:
By default MVC uses the conventional routing which uses something of this sort.

```<code>routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
</code>```

Which translates to http://localhost:9999/<controllerName>/<ActionName>/<OptionalIDs>

But if you want custom routes its possible in ASP.NET MVC 5 this feature is called Attribute Routing, if you are using Visual Studio 2015 or above.

For example:

Adding the following line to your global.asax.cs file will enable attribute routing in your MVC 5 application:
routes.MapMvcAttributeRoutes();

This will be rendered as http://localhost:9999

```<code>[HttpGet]
[Route(Name = "HomeView")]
public ActionResult Index()
{
  return View();
}
</code>```

This will be rendered as http://localhost:9999/Login

```<code>[HttpGet]
[Route("~/Login", Name = "LoginGET")]
public ActionResult Login()
{
   return View();
}
</code>```

In your view you can use the Html.BeginRouteForm("<RouteName>", FormMethod.Post) helper method for handling routes.

```<code>[HttpPost]
[Route("~/Login", Name = "LoginPOST")]
public ActionResult Login(FormCollection UserCredentials)
{
   //do stuff
   return RedirectToRoute("HomeView");
}
</code>```

For referring MVC Actions via Routes in _layout.html you can use:

```<code>Html.RouteLink("Link text that you want to display in the view", "<RouteName>");
</code>```

For More information you can always check MSDN Attribute Routing.

Body:
By default MVC uses the conventional routing which uses something of this sort.

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

Which translates to http://localhost:9999/<controllerName>/<ActionName>/<OptionalIDs>

But if you want custom routes its possible in ASP.NET MVC 5 this feature is called Attribute Routing, if you are using Visual Studio 2015 or above.

For example:

Adding the following line to your global.asax.cs file will enable attribute routing in your MVC 5 application:
routes.MapMvcAttributeRoutes();

This will be rendered as http://localhost:9999

[HttpGet]
[Route(Name = "HomeView")]
public ActionResult Index()
{
  return View();
}

This will be rendered as http://localhost:9999/Login

[HttpGet]
[Route("~/Login", Name = "LoginGET")]
public ActionResult Login()
{
   return View();
}

In your view you can use the Html.BeginRouteForm("<RouteName>", FormMethod.Post) helper method for handling routes.

[HttpPost]
[Route("~/Login", Name = "LoginPOST")]
public ActionResult Login(FormCollection UserCredentials)
{
   //do stuff
   return RedirectToRoute("HomeView");
}

For referring MVC Actions via Routes in _layout.html you can use:

Html.RouteLink("Link text that you want to display in the view", "<RouteName>");

For More information you can always check MSDN Attribute Routing.


问:
Django: Use of DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT in settings.py?
I would like to globally (through my entire site, admin and front-end) adjust the way dates and time are displayed to my likings, but I cannot figure out what is going on with the DATE_FORMAT, DATETIME_FORMAT and TIME_FORMAT variables in settings.py.

In this question it says that the settings are ignored. The question is over a year old though. In the Django documentation it says they can be used when you have USE_L10N = True and apparently something changed in Django 1.2. According to this however there might be a bug.

I am currently using Django 1.2 and when I have USE_L10N = True it just ignores the date(time) format in settings.py. When I have USE_L10N = False it also seems to ignore them.

Is there a way to globally customize the date and time display? Or should I create my own custom formats file as Karen suggests in the Django Users Google Group post?

答:
A late response, but hopefully this will help anyone else searching for this.
By setting USE_L10N = True in your settings, Django looks for locale specific formats, giving them precedence over non-locale related settings.

The solution:  (to display 30/12/2017 on a DateField)

```<code>from django.conf.locale.en import formats as en_formats

en_formats.DATE_FORMAT = "%d/%m/%Y"
</code>```

and for inputs (to accept 30/12/2017 or 30-12-2017)

```<code>en_formats.DATE_INPUT_FORMATS = ['%d/%m/%Y', '%d-%m-%Y']
</code>```

Reference:  https://mounirmesselmeni.github.io/2014/11/06/date-format-in-django-admin/

*tested on Django==1.10.7

Body:
A late response, but hopefully this will help anyone else searching for this.
By setting USE_L10N = True in your settings, Django looks for locale specific formats, giving them precedence over non-locale related settings.

The solution:  (to display 30/12/2017 on a DateField)

from django.conf.locale.en import formats as en_formats

en_formats.DATE_FORMAT = "%d/%m/%Y"

and for inputs (to accept 30/12/2017 or 30-12-2017)

en_formats.DATE_INPUT_FORMATS = ['%d/%m/%Y', '%d-%m-%Y']

Reference:  https://mounirmesselmeni.github.io/2014/11/06/date-format-in-django-admin/

*tested on Django==1.10.7


问:
failed : app:processDebugMainfest in android
Merging Errors:

Error: Attribute meta-data#android.support.VERSION@value
  value=(26.0.1) from AndroidManifest.xml:23:13-35 is also present at
  AndroidManifest.xml:25:13-35 value=(26.1.0). Suggestion: add
  'tools:replace="android:value"' to  element at
  AndroidManifest.xml:21:9-24:15 to override.

答:
You have the answer in the error report. Read it.

Suggestion: add 'tools:replace="android:value"' to element at
  AndroidManifest.xml:21:9-24:15 to override.

Add tools:replace="android:value" in your manifest file.

check this question
Manifest merger failed error. It is explained very clear


问:
Cannot initialize the data source object of OLE DB provider Microsoft.ACE.OLEDB.12.0 for linked server (null)
```<code>DECLARE @PATH NVARCHAR(1000) = N'\\MY-SERVER\C$\Folder\\'
DECLARE @TABLE NVARCHAR(50) = SUBSTRING(@FILENAME,0,CHARINDEX('.',@FILENAME))
DECLARE @SQL NVARCHAR(4000) =
    N'IF OBJECT_ID(''dbo.' + @TABLE + ''' , ''U'') IS NOT NULL
    DROP TABLE dbo.[' + @TABLE + ']
    SELECT * INTO [' + @TABLE + ']
    FROM OPENROWSET(''Microsoft.ACE.OLEDB.12.0''
                    ,''Text; Database='+@PATH+';''
                    ,''SELECT * FROM [' + @FILENAME + ']'')'

EXEC(@SQL)
</code>```

Today I have come across an issue with Microsoft.ACE.OLEDB.12.0 driver in SSIS 2012. The script above sits in a stored procedure which dynamically loads the .csv's into the database based on the current file which is supplied by the SSIS loop in which stored procedure sits.  There are files in the directory.

The stored procedure runs correctly when run directly in SQL Server Management Studio.

This has been working fine up until today. Today I am getting the following error:

Executing the query "EXEC [dbo].[CreateAndImportCSVs]  ?" failed with the following error: "Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".".
  Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

Any help on this issue would be great!

Edit

So looking into what's changed I hear alarm bells when I look at the windows updates installed on the server yesterday! The following two were installed:

Microsoft Office Access Runtime and Data Connectivity 2007 (SP3)
http://support.microsoft.com/kb/2526310

Update for the 2007 Microsoft Office System (KB967642)
http://www.microsoft.com/downloads/details.aspx?FamilyId=E93AB1BE-ADE6-4FF8-8637-DBD3EBE3C5C5&displaylang=en

答:
This problem resolved itself. There were further updates installed, one of these must have fixed the issue introduced by the previous updates:

Update for Microsoft Office 2010 (KB4011188) 64-Bit Edition
https://support.microsoft.com/kb/4011188

Update for Microsoft Office 2010 (KB2553347) 64-Bit Edition
http://support.microsoft.com/kb/2553347

Security Update for Microsoft Office 2010 (KB2553338) 64-Bit Edition
https://support.microsoft.com/kb/2553338

Thanks for all the help with this!

Body:
DECLARE @PATH NVARCHAR(1000) = N'\\MY-SERVER\C$\Folder\\'
DECLARE @TABLE NVARCHAR(50) = SUBSTRING(@FILENAME,0,CHARINDEX('.',@FILENAME))
DECLARE @SQL NVARCHAR(4000) =
    N'IF OBJECT_ID(''dbo.' + @TABLE + ''' , ''U'') IS NOT NULL
    DROP TABLE dbo.[' + @TABLE + ']
    SELECT * INTO [' + @TABLE + ']
    FROM OPENROWSET(''Microsoft.ACE.OLEDB.12.0''
                    ,''Text; Database='+@PATH+';''
                    ,''SELECT * FROM [' + @FILENAME + ']'')'

EXEC(@SQL)

Today I have come across an issue with Microsoft.ACE.OLEDB.12.0 driver in SSIS 2012. The script above sits in a stored procedure which dynamically loads the .csv's into the database based on the current file which is supplied by the SSIS loop in which stored procedure sits.  There are files in the directory.

The stored procedure runs correctly when run directly in SQL Server Management Studio.

This has been working fine up until today. Today I am getting the following error:

Executing the query "EXEC [dbo].[CreateAndImportCSVs]  ?" failed with the following error: "Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".".
  Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

Any help on this issue would be great!

Edit

So looking into what's changed I hear alarm bells when I look at the windows updates installed on the server yesterday! The following two were installed:

Microsoft Office Access Runtime and Data Connectivity 2007 (SP3)
http://support.microsoft.com/kb/2526310

Update for the 2007 Microsoft Office System (KB967642)
http://www.microsoft.com/downloads/details.aspx?FamilyId=E93AB1BE-ADE6-4FF8-8637-DBD3EBE3C5C5&displaylang=en


问:
Is it possible to get (feed) Facebook posts multilingual?
Since a while its possible to post on Facebook multilingual:
https://code.facebook.com/posts/597373993776783/building-a-better-way-to-write-posts-in-multiple-languages/

I'm posting on my page in German and English and I wanna integrate my Facebook posts on a website. If you use the website English, I wanna present them the English versions of my posts.

So, I try to get the posts multilinugal, but I couldn't find any option in the Graph API Explorer. The posts always show up in the default language.
https://developers.facebook.com/tools/explorer/

Is it possible to get (feed) Facebook posts multilingual?

答:
You can use the locale parameter for that,
https://developers.facebook.com/docs/graph-api/using-graph-api/#readmodifiers:

locale

  Used if your app needs the ability to retrieve localized content in the language of a particular locale (when available).

If the post is available in the requested locale, you will get that one returned - otherwise, the “default” language version of the post.


问:
Replace cell value if containing specified words
How is it possible to scan for words and replace the whole cell via command?
I have the value

ASUS MB Z270 D4 1151

or

MB ASUS D4 Z270 1151

(word order doesn't matter)

And I want it to be:

Motherboard - Asus Z270 DDR4 LGA1151

I want to do the same for 1000+ values

答: Hit CTRL + H for Search & Replace.

Body: Hit CTRL + H for Search & Replace.