问:
Grab key and value in .map
Not sure what I'm missing here:

```<code>export function extractOptions(options){
  return options.map((option, i) => {
    if(!option.value){
      logRequiredOptionsMissingError(option.key)
      process.exit(1)
      return
    }
  })
}
</code>```

Given this array as options:

```<code>[{ branch: 'A15'},
 { awsKey: 'AKIAQ'},
 { awsSecret: '0ro'}]
</code>```

I get undefined for .value.  And yes there's data there, I see it when I debug.

Basically I want it to go through and check whether each key has a value...otherwise log an error and stop if it comes across a key with no value

UPDATE

I ultimately went with this:

```<code>export function extractOptions(options){
  for (let option of options) {
    if(!option || option.length < 1){
      logRequiredOptionsMissingError(option[0][0])
      process.exit(1)
      return
    }
  }

  return options
}
</code>```

As an added bonus I'll share my test

```<code>it('extracts options', () => {
      const options = [
        { branch: 'A15'},
        { awsKey: 'AKIAQ'},
        { awsSecret: '0ro'}
      ],
        list = Deploy.extractOptions(options)

      expect(list).to.deep.equal(options)
 })
</code>```

答:
You can get key value pairs as array from object using Object.entries()

```<code>return options.map((option, i) => {
    var data = Object.entries(option)
    console.log(data[0][0], data[0][1]) // will be your key and value
    if(!data[0][1]){
      logRequiredOptionsMissingError(data[0][0])
      process.exit(1)
      return
    }
  })
</code>```

Documentation on Object.entries()

Title: Grab key and value in .map

Body:
Not sure what I'm missing here:

export function extractOptions(options){
  return options.map((option, i) => {
    if(!option.value){
      logRequiredOptionsMissingError(option.key)
      process.exit(1)
      return
    }
  })
}

Given this array as options:

[{ branch: 'A15'},
 { awsKey: 'AKIAQ'},
 { awsSecret: '0ro'}]

I get undefined for .value.  And yes there's data there, I see it when I debug.

Basically I want it to go through and check whether each key has a value...otherwise log an error and stop if it comes across a key with no value

UPDATE

I ultimately went with this:

export function extractOptions(options){
  for (let option of options) {
    if(!option || option.length < 1){
      logRequiredOptionsMissingError(option[0][0])
      process.exit(1)
      return
    }
  }

  return options
}

As an added bonus I'll share my test

it('extracts options', () => {
      const options = [
        { branch: 'A15'},
        { awsKey: 'AKIAQ'},
        { awsSecret: '0ro'}
      ],
        list = Deploy.extractOptions(options)

      expect(list).to.deep.equal(options)
 })

Body:
You can get key value pairs as array from object using Object.entries()

return options.map((option, i) => {
    var data = Object.entries(option)
    console.log(data[0][0], data[0][1]) // will be your key and value
    if(!data[0][1]){
      logRequiredOptionsMissingError(data[0][0])
      process.exit(1)
      return
    }
  })

Documentation on Object.entries()


来源: stackexchange

问:
cant open image in android studio (file not found)
I'm using android studio and I have some pics located here: ..\app\src\main\res\pics

I have this method to open images in the adapter java class

```<code>private Drawable drawImage(String iconString) {
    Log.i(TAG , "icon string = " + iconString) ;
    AssetManager assetManager=ctx.getAssets();
    InputStream inputStream;

    try {
        inputStream=assetManager.open("pics/"+iconString+".png");
        Log.i(TAG , "icon string try = " + iconString) ;
        Drawable drawable=Drawable.createFromStream(inputStream, null);
        return  drawable ;

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

}
</code>```

I did invoke the method
but when I build and run it I get the following error:

```<code>java.io.FileNotFoundException: pics/ic_payments.png
06-08 10:10:44.577 8002-8002/ ... W/System.err:
at android.content.res.AssetManager.openAsset(Native Method)
</code>```

What did I miss here?

答:
Your code is ok. Check your assets folder path.

src->main->assets->pics->test.png

ContentLicense: CC BY-SA 3.0

Body:
I'm using android studio and I have some pics located here: ..\app\src\main\res\pics

I have this method to open images in the adapter java class

private Drawable drawImage(String iconString) {
    Log.i(TAG , "icon string = " + iconString) ;
    AssetManager assetManager=ctx.getAssets();
    InputStream inputStream;

    try {
        inputStream=assetManager.open("pics/"+iconString+".png");
        Log.i(TAG , "icon string try = " + iconString) ;
        Drawable drawable=Drawable.createFromStream(inputStream, null);
        return  drawable ;

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

}

I did invoke the method
but when I build and run it I get the following error:

java.io.FileNotFoundException: pics/ic_payments.png
06-08 10:10:44.577 8002-8002/ ... W/System.err:
at android.content.res.AssetManager.openAsset(Native Method)

What did I miss here?


问:
How To Configure Custom CookieGenerator Spring to override the cookie path
I am unable to configure custom CookieGenerator in Spring.
The requirement is very simple, I need to set the path of cookie to root "/" but didn't find any configuration settings. Since my war file is portal.war and bydefault spring is setting path=/portal which I want to change.
I searched on google but non of the option is working coz most of the solution as referring to older version of spring.

Here is what I have tried :
Created MyCookieGenerator :

```<code>public class MyCookieGenerator extends CookieGenerator {
        @Override
        public String getCookiePath() {
            return DEFAULT_COOKIE_PATH;
        }

        @Override
        public void setCookiePath(String cookiePath) {
            super.setCookiePath(DEFAULT_COOKIE_PATH);
        }

}
</code>```

And added following bean in context.xml

```<code>< bean id="cookieGenerator" class="com.test.web.util.MyCookieGenerator" />
</code>```

but this is not working. It seems to be some small configuration but I am unable to find the solution.

答:
CookieGenerator has a default property DEFAULT_COOKIE_PATH, which shows to the root:

```<code>public class CookieGenerator {
    public static final String DEFAULT_COOKIE_PATH = "/";
...
}
</code>```

If in xml Spring declaration, you declare to use it, then your cookie path will be set to root

```<code><bean id="cookieGenerator" class="com.test.web.util.MyCookieGenerator" />
    <property name="useDefaultPath" value="true"/>
</bean>
</code>```

Hope it helps.
Best regards!

Body:
I am unable to configure custom CookieGenerator in Spring.
The requirement is very simple, I need to set the path of cookie to root "/" but didn't find any configuration settings. Since my war file is portal.war and bydefault spring is setting path=/portal which I want to change.
I searched on google but non of the option is working coz most of the solution as referring to older version of spring.

Here is what I have tried :
Created MyCookieGenerator :

public class MyCookieGenerator extends CookieGenerator {
        @Override
        public String getCookiePath() {
            return DEFAULT_COOKIE_PATH;
        }

        @Override
        public void setCookiePath(String cookiePath) {
            super.setCookiePath(DEFAULT_COOKIE_PATH);
        }

}

And added following bean in context.xml

< bean id="cookieGenerator" class="com.test.web.util.MyCookieGenerator" />

but this is not working. It seems to be some small configuration but I am unable to find the solution.

Body:
CookieGenerator has a default property DEFAULT_COOKIE_PATH, which shows to the root:

public class CookieGenerator {
    public static final String DEFAULT_COOKIE_PATH = "/";
...
}

If in xml Spring declaration, you declare to use it, then your cookie path will be set to root

<bean id="cookieGenerator" class="com.test.web.util.MyCookieGenerator" />
    <property name="useDefaultPath" value="true"/>
</bean>

Hope it helps.
Best regards!


问:
How do I exclude a folder from a project but not from publish?
I've migrated an asp.net core project to VS2017 RC, which now supports the ability to exclude files from a project. I've excluded two folders, which added these lines to my csproj file:

```<code><ItemGroup>
  <Content Remove="wwwroot\dist\**" />
  <Content Remove="wwwroot\lib\**" />
</ItemGroup>
</code>```

This works great, except now those files don't get published anymore. How do I exclude these folders from the project but still include them on publish?

答:
The following msbuild items taken from the dotnet new spa templates helped me to achieve what I believe you are after:</p>

```<code><ItemGroup>
    <Content Remove="wwwroot\dist\**" />
    <Content Remove="wwwroot\lib\**" />
</ItemGroup>

<Target Name="GiveAName" AfterTargets="ComputeFilesToPublish">
    <!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
    <Exec Command="npm install" />
    <Exec Command="npm etc etc do your stuff" />
    <Exec Command="or webpack" />

    <!-- Include the newly-built files in the publish output -->
    <ItemGroup>
        <DistFiles Include="wwwroot\dist\**; wwwroot\lib\**" />
        <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
            <RelativePath>%(DistFiles.Identity)</RelativePath>
            <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
        </ResolvedFileToPublish>
    </ItemGroup>
</Target>
</code>```

Body:
I've migrated an asp.net core project to VS2017 RC, which now supports the ability to exclude files from a project. I've excluded two folders, which added these lines to my csproj file:

<ItemGroup>
  <Content Remove="wwwroot\dist\**" />
  <Content Remove="wwwroot\lib\**" />
</ItemGroup>

This works great, except now those files don't get published anymore. How do I exclude these folders from the project but still include them on publish?

Body:
The following msbuild items taken from the dotnet new spa templates helped me to achieve what I believe you are after:

<ItemGroup>
    <Content Remove="wwwroot\dist\**" />
    <Content Remove="wwwroot\lib\**" />
</ItemGroup>

<Target Name="GiveAName" AfterTargets="ComputeFilesToPublish">
    <!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
    <Exec Command="npm install" />
    <Exec Command="npm etc etc do your stuff" />
    <Exec Command="or webpack" />

    <!-- Include the newly-built files in the publish output -->
    <ItemGroup>
        <DistFiles Include="wwwroot\dist\**; wwwroot\lib\**" />
        <ResolvedFileToPublish Include="@(DistFiles-&gt;'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
            <RelativePath>%(DistFiles.Identity)</RelativePath>
            <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
        </ResolvedFileToPublish>
    </ItemGroup>
</Target>


问:
How to check iOS version?
I want to check if the iOS version of the device is greater than 3.1.3
I tried things like:

```<code>[[UIDevice currentDevice].systemVersion floatValue]
</code>```

but it does not work, I just want a:

```<code>if (version > 3.1.3) { }
</code>```

How can I achieve this?

答:
Starting Xcode 9, in Objective-C:

```<code>if (@available(iOS 11, *)) {
    // iOS 11 (or newer) ObjC code
} else {
    // iOS 10 or older code
}
</code>```

Starting Xcode 7, in Swift:

```<code>if #available(iOS 11, *) {
    // iOS 11 (or newer) Swift code
} else {
    // iOS 10 or older code
}
</code>```

For the version, you can specify the MAJOR, the MINOR or the PATCH (see http://semver.org/ for definitions). Examples:

iOS 11 and iOS 11.0 are the same minimal version

iOS 10, iOS 10.3, iOS 10.3.1 are different minimal versions

You can input values for any of those systems:

iOS, macOS, watchOS, tvOS

Real case example taken from one of my pods:

```<code>if #available(iOS 10.0, tvOS 10.0, *) {
    // iOS 10+ and tvOS 10+ Swift code
} else {
    // iOS 9 and tvOS 9 older code
}
</code>```

documentation

Title: How to check iOS version?

Body:
I want to check if the iOS version of the device is greater than 3.1.3
I tried things like:

[[UIDevice currentDevice].systemVersion floatValue]

but it does not work, I just want a:

if (version > 3.1.3) { }

How can I achieve this?

Body:
Starting Xcode 9, in Objective-C:

if (@available(iOS 11, *)) {
    // iOS 11 (or newer) ObjC code
} else {
    // iOS 10 or older code
}

Starting Xcode 7, in Swift:

if #available(iOS 11, *) {
    // iOS 11 (or newer) Swift code
} else {
    // iOS 10 or older code
}

For the version, you can specify the MAJOR, the MINOR or the PATCH (see http://semver.org/ for definitions). Examples:

iOS 11 and iOS 11.0 are the same minimal version

iOS 10, iOS 10.3, iOS 10.3.1 are different minimal versions

You can input values for any of those systems:

iOS, macOS, watchOS, tvOS

Real case example taken from one of my pods:

if #available(iOS 10.0, tvOS 10.0, *) {
    // iOS 10+ and tvOS 10+ Swift code
} else {
    // iOS 9 and tvOS 9 older code
}

documentation


问:
How will I know when to create an interface?
I'm at a point in my development learning where I feel like I must learn more about interfaces.

I frequently read about them but it just seems like I cannot grasp them.

I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"

What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.

答:
The easiest example to give is something like Payment Processors.(Paypal, PDS etc).

Say you create an interface IPaymentProcessor that has ProcessACH and ProcessCreditCard methods.

You can now implement a concrete Paypal implementation.  Making those methods call PayPal specific functions.

If you decide later you need to switch to another provider, you can.  Just create another concrete implementation for the new provider.  Since all you are tied to is your interface(contract), you can swap out which one your application uses without changing the code that consumes it.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: ALassek

OwnerDisplayName: Jesse Brown


问:
Javascript , encodeURI failed to encode round bracket "("
I have cookie value which contains round bracket " e.g: demo (1)"
When I try to encode with encodeURI , the round bracket ( is not encoded to %28 , what is the alternative to encode the special characters like round brackets</p>

答:
encodeURI only encodes reserved characters so this function should not be expected to encode parentheses.

You could write your own function to encode all the characters in the string, or just create a custom list of characters you want to encode.

Fiddle

```<code>function superEncodeURI(url) {

  var encodedStr = '', encodeChars = ["(", ")"];
  url = encodeURI(url);

  for(var i = 0, len = url.length; i < len; i++) {
    if (encodeChars.indexOf(url[i]) >= 0) {
        var hex = parseInt(url.charCodeAt(i)).toString(16);
        encodedStr += '%' + hex;
    }
    else {
        encodedStr += url[i];
    }
  }

  return encodedStr;
}
</code>```

Body:
encodeURI only encodes reserved characters so this function should not be expected to encode parentheses.

You could write your own function to encode all the characters in the string, or just create a custom list of characters you want to encode.

Fiddle

function superEncodeURI(url) {

  var encodedStr = '', encodeChars = ["(", ")"];
  url = encodeURI(url);

  for(var i = 0, len = url.length; i < len; i++) {
    if (encodeChars.indexOf(url[i]) >= 0) {
        var hex = parseInt(url.charCodeAt(i)).toString(16);
        encodedStr += '%' + hex;
    }
    else {
        encodedStr += url[i];
    }
  }

  return encodedStr;
}


问:
ANDROID:- not able to get the available wifi list using ScanResult
I'm trying to list available wifi network by ScanResult.

Can anyone tell me what's wrong in my code? I'm not getting the desired output.

Here's My code:

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

    Switch aSwitch;
    TextView textView;
    WifiManager wifiManager;
    WifiInfo wifiInfo;
    String info;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scanwifi);

        aSwitch=(Switch) findViewById(R.id.s);
        textView=(TextView) findViewById(R.id.textView);
        wifiManager=(WifiManager) getSystemService(Context.WIFI_SERVICE);
        wifiManager.startScan();

        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // switch on
                if(isChecked && ! wifiManager.isWifiEnabled())
                {
                    wifiManager.setWifiEnabled(true);
                    wifiInfo=wifiManager.getConnectionInfo();
                }
                // switch off
                if (!isChecked && wifiManager.isWifiEnabled())
                {
                  wifiManager.setWifiEnabled(false);
                }
            }
        });
        broadcast b=new broadcast();
        registerReceiver(b,new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    }

    public class broadcast extends BroadcastReceiver{
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onReceive(Context context, Intent intent) {
            // onReceive method updates any change in the available wifi
            StringBuffer stringBuffer=new StringBuffer();
           /// List<WifiConfiguration> list=wifiManager.getConfiguredNetworks();
            List<ScanResult> list=wifiManager.getScanResults();
            //for(WifiConfiguration wifiConfiguration : list)
            for(ScanResult scanResult : list)
            {
                stringBuffer.append(scanResult);
            }

            textView.setText(stringBuffer);

        }
    }
}
</code>```

答:
```<code>    import android.app.Activity;
    import android.content.BroadcastReceiver;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.content.ServiceConnection;
    import android.net.Uri;
    import android.net.wifi.ScanResult;
    import android.net.wifi.WifiManager;
    import android.view.View;
    import android.widget.TextView;
    import android.widget.Toast;
    import java.util.List;

    public class MainActivity extends Activity {
    private StringBuilder sb = new StringBuilder();
    List<ScanResult> scanList;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
      textView = (TextView)findViewById(R.id.textView);
      getWifiNetworksList();
    }

    private void getWifiNetworksList(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        final WifiManager wifiManager =
                   (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.startScan();
    registerReceiver(new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent) {
        sb = new StringBuilder();
        scanList = wifiManager.getScanResults();
        sb.append("\n  Number Of Wifi connections :" + " "    +scanList.size()+"\n\n");
        for(int i = 0; i < scanList.size(); i++){
        sb.append(new Integer(i+1).toString() + ". ");
        sb.append((scanList.get(i)).toString());
        sb.append("\n\n");
    }
      Toast.makeText(getApplicationContext(),""+sb.toString(),Toast.LENGTH_LONG).show();
       textView.setText(sb);
       }
      },filter);
     }
    }

Manifest:

        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</code>```

EDIT:

Body:
I'm trying to list available wifi network by ScanResult.

Can anyone tell me what's wrong in my code? I'm not getting the desired output.

Here's My code:

public class Activity_scanwifi extends AppCompatActivity {

    Switch aSwitch;
    TextView textView;
    WifiManager wifiManager;
    WifiInfo wifiInfo;
    String info;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scanwifi);

        aSwitch=(Switch) findViewById(R.id.s);
        textView=(TextView) findViewById(R.id.textView);
        wifiManager=(WifiManager) getSystemService(Context.WIFI_SERVICE);
        wifiManager.startScan();

        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // switch on
                if(isChecked && ! wifiManager.isWifiEnabled())
                {
                    wifiManager.setWifiEnabled(true);
                    wifiInfo=wifiManager.getConnectionInfo();
                }
                // switch off
                if (!isChecked && wifiManager.isWifiEnabled())
                {
                  wifiManager.setWifiEnabled(false);
                }
            }
        });
        broadcast b=new broadcast();
        registerReceiver(b,new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    }

    public class broadcast extends BroadcastReceiver{
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onReceive(Context context, Intent intent) {
            // onReceive method updates any change in the available wifi
            StringBuffer stringBuffer=new StringBuffer();
           /// List<WifiConfiguration> list=wifiManager.getConfiguredNetworks();
            List<ScanResult> list=wifiManager.getScanResults();
            //for(WifiConfiguration wifiConfiguration : list)
            for(ScanResult scanResult : list)
            {
                stringBuffer.append(scanResult);
            }

            textView.setText(stringBuffer);

        }
    }
}

Body:
    import android.app.Activity;
    import android.content.BroadcastReceiver;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.content.ServiceConnection;
    import android.net.Uri;
    import android.net.wifi.ScanResult;
    import android.net.wifi.WifiManager;
    import android.view.View;
    import android.widget.TextView;
    import android.widget.Toast;
    import java.util.List;

    public class MainActivity extends Activity {
    private StringBuilder sb = new StringBuilder();
    List<ScanResult> scanList;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
      textView = (TextView)findViewById(R.id.textView);
      getWifiNetworksList();
    }

    private void getWifiNetworksList(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        final WifiManager wifiManager =
                   (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.startScan();
    registerReceiver(new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent) {
        sb = new StringBuilder();
        scanList = wifiManager.getScanResults();
        sb.append("\n  Number Of Wifi connections :" + " "    +scanList.size()+"\n\n");
        for(int i = 0; i < scanList.size(); i++){
        sb.append(new Integer(i+1).toString() + ". ");
        sb.append((scanList.get(i)).toString());
        sb.append("\n\n");
    }
      Toast.makeText(getApplicationContext(),""+sb.toString(),Toast.LENGTH_LONG).show();
       textView.setText(sb);
       }
      },filter);
     }
    }

Manifest:

        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

EDIT:


问:
Xamarin Forms Image fill width with proper aspect
Here is xaml (an image in stacklayout). Everything is logical: I set Aspect to AspectFit and HorizontalOptions to FillAndExpand. Width of image must fill the width of stacklayout. Height must be calculated in order to image Aspect.

```<code><Image BackgroundColor="Fuchsia"
       Aspect="AspectFit"
       Source="{Binding GroupLogo}"
       HorizontalOptions="FillAndExpand"
       VerticalOptions="FillAndExpand"/>
</code>```

It fill the width but It doesn't want to draw image full width. Why?

答:
As I've found no working example. This works perfectly for me:</p>

```<code><Grid VerticalOptions="FillAndExpand">
      <Image Source="{Binding MyImageSrc}" Aspect="AspectFill" />
</Grid>
</code>```

Body:
Here is xaml (an image in stacklayout). Everything is logical: I set Aspect to AspectFit and HorizontalOptions to FillAndExpand. Width of image must fill the width of stacklayout. Height must be calculated in order to image Aspect.

<Image BackgroundColor="Fuchsia"
       Aspect="AspectFit"
       Source="{Binding GroupLogo}"
       HorizontalOptions="FillAndExpand"
       VerticalOptions="FillAndExpand"/>

It fill the width but It doesn't want to draw image full width. Why?

Body:
As I've found no working example. This works perfectly for me:

<Grid VerticalOptions="FillAndExpand">
      <Image Source="{Binding MyImageSrc}" Aspect="AspectFill" />
</Grid>

ContentLicense: CC BY-SA 4.0


问:
FORTRAN wipes arg values between function calls?
So strange. Does FORTRAN require variables to be reinitialized after they've been sent as parameters? I kept getting a segmentation fault whenever I'd send the same arguments to another subroutine. I discovered that the argument values were being wiped between the first call and the second, with no reassignment statements on the arguments between function calls or even in either function. The scope of these arguments is limited to the main program (I'm not using any COMMON blocks).

I can't post code right now as I'm writing from my phone, but any ideas? The temporary workaround is to reassign the values right before calling the second function.

Thanks for the help.

答:
No Fortran doesn't zap variables when they have been used as arguments in a subroutine call.

However, arguments passed by reference can have their values changed by the called subroutine.

Try printing the variables before the second call. Have a look at how the first subroutine uses the parameters.

Just my ¤0.02 worth - it's decades since I looked at Fortran (IV).


问:
Maven surefire VM crashes or forking freezes on Eclipse Neon .3
When I run the maven command 'mvn clean install' from Eclipse (Neon.3, EE version)
I get the error:

org.apache.maven.plugin.PluginExecutionException: Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test failed: The forked VM terminated without saying properly goodbye. VM crash or System.exit called ?

The Eclipse installation uses m2e-plugin (default) and Java 1.8.0_131. But I have also tried with some earlier versions, including 1.7.x.

Tried to look for a solution to this issue and found this:
The forked VM terminated without saying properly goodbye. VM crash or System.exit called

Tried to add the following configuration to the pom.xml

```<code><profiles>
    <profile>
        <id>normal_build_profile</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.20</version>
                    <configuration>
                        <!-- Tried with lots of different values, no change -->
                        <threadCount>3</threadCount>
                        <forkCount>3</forkCount>
                        <reuseForks>true</reuseForks>
                        <argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>
</code>```

With the configuration above, it freezes in Eclipse while executing this command (from log)

[DEBUG] Forking command line: cmd.exe /X /C "C:\Java\jdk1.8.0_131\jre\bin\java -Xmx1024m -XX:MaxPermSize=256m -jar C:\workspace\miniTest\target\surefire\surefirebooter2156530837851203141.jar C:\workspace\miniTest\target\surefire 2017-06-08T08-58-59_461-jvmRun1 surefire2401124720884095509tmp surefire_03952770368534211516tmp"

But when I run 'mvn clean install' from the command line, all is good.
The Eclipse is configured to use the same Maven installation as used at the command line. The Maven version would be 3.5.0. (Though this happened also with 3.3.3 version)

As this seems to be related to running test, I should note that I do also have these:

```<code><dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <!-- 4.11 Does not require that hamcrest dependency -->
    <version>4.12</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>
</code>```

Does anyone have an idea what is going on with the Eclipse as this seems to be related to it?
It's rather inconvenient to do build from the command line.
Running unit tests in Eclipse without Maven is ok.

答:
```<code><threadCount>3</threadCount>
<forkCount>0</forkCount>
<reuseForks>false</reuseForks>
</code>```

Seems to do the trick at least at the case I used to debug this issue.

Body:
When I run the maven command 'mvn clean install' from Eclipse (Neon.3, EE version)
I get the error:

org.apache.maven.plugin.PluginExecutionException: Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test failed: The forked VM terminated without saying properly goodbye. VM crash or System.exit called ?

The Eclipse installation uses m2e-plugin (default) and Java 1.8.0_131. But I have also tried with some earlier versions, including 1.7.x.

Tried to look for a solution to this issue and found this:
The forked VM terminated without saying properly goodbye. VM crash or System.exit called

Tried to add the following configuration to the pom.xml

<profiles>
    <profile>
        <id>normal_build_profile</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.20</version>
                    <configuration>

                        <threadCount>3</threadCount>
                        <forkCount>3</forkCount>
                        <reuseForks>true</reuseForks>
                        <argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

With the configuration above, it freezes in Eclipse while executing this command (from log)

[DEBUG] Forking command line: cmd.exe /X /C "C:\Java\jdk1.8.0_131\jre\bin\java -Xmx1024m -XX:MaxPermSize=256m -jar C:\workspace\miniTest\target\surefire\surefirebooter2156530837851203141.jar C:\workspace\miniTest\target\surefire 2017-06-08T08-58-59_461-jvmRun1 surefire2401124720884095509tmp surefire_03952770368534211516tmp"

But when I run 'mvn clean install' from the command line, all is good.
The Eclipse is configured to use the same Maven installation as used at the command line. The Maven version would be 3.5.0. (Though this happened also with 3.3.3 version)

As this seems to be related to running test, I should note that I do also have these:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>

    <version>4.12</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

Does anyone have an idea what is going on with the Eclipse as this seems to be related to it?
It's rather inconvenient to do build from the command line.
Running unit tests in Eclipse without Maven is ok.

Body:
<threadCount>3</threadCount>
<forkCount>0</forkCount>
<reuseForks>false</reuseForks>

Seems to do the trick at least at the case I used to debug this issue.


问:
Alfresco - Want to Change Content store path
I want to change the existing content store path of my Alfresco instance just because it is about to get full. One solution is to move existing content store at another location and change the path in alfresco.global.properties but I want to write new data at another location and read the existing from the current one.</p>

答:
Of course this is possible but maybe not as you expect. AFaust's simple-content-stores is a collection of different content store implementations following different concepts how to generate the server side document path. You may check the selector property-based routing store to chose the location by creation/modification date.
If your goal is just to handle your restricted disk space in a test and development system it may be much easier to work with symlinks (or shortcuts) by moving folders to another disk and create symlinks instead where Alfresco expects the directory.
But be warned: This may end up in a confusing folder structure. If you loose the overview about your moved folders you may accidently cause data loss.

If you you run on linux/unix it may be much easier to create logical volumes containing different physical devices/partitions.

Another quite simple solution: move the whole directory alf_data/contentstore/ to a network storage, big enough to store all the data and change that path in your alfresco-global.properties


问:
Ionic native Transfer plugin's `file.dataDirectory` shows error
I'm going to use the Ionic native Transfer plugin as shown below.
Problem is here this.file.dataDirectory.It shows error like [ts] Property 'dataDirectory' does not exist on type 'File'..Can you tell me what is the solution for this?

download() {
        const fileTransfer: TransferObject = this.transfer.create();
        const url = 'http://www.example.com/file.pdf';
        fileTransfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => {
            console.log('download complete: ' + entry.toURL());
        }, (error) => {
            // handle error
        });
    }
```

答:
Oh.. My bad :(

I have to install File plugin too :D

```<code>$ ionic cordova plugin add cordova-plugin-file --save
$ npm install --save @ionic-native/file
</code>```

Body:
Oh.. My bad :(

I have to install File plugin too :D

$ ionic cordova plugin add cordova-plugin-file --save
$ npm install --save @ionic-native/file


问:
What should I increase Xmx setting to for IntelliJ 9.04?
I'm getting out of memory issues when I'm running IntelliJ IDEA 9.0.4, build IU-95.627.

My Macbook Pro has 4GB of Memory

I've heard one recommendation clearing out the ~/Library/Caches/IntelliJ90 folder is an answer..
Is that something others would recommend?

What should I set it to?
I saw this post and tried setting EXE4J_JAVA_HOME in my ~/.profile but that did't make a difference.

I've heard others say setting this too high is not a good idea as well..

Any ideas?
IntelliJ Contents/info.plist VMOptions setting:
-Xms64m -Xmx512m -XX:MaxPermSize=128m -ea -Xbootclasspath/a:../lib/boot.jar

PS: Just in case this has any bearing on things, I've been trying to use Sqlprofiler at the same time with a Grails app using the p6spy plugin in my IDE.

答:
I usually increase -Xmx to 800m

```<code>-Xmx800m
</code>```

No other changes. I don't have any problems with that in any of my projects, some of them Grails projects. Lately I have followed the EAP versions, and now I use IDEA X.

(I also have a MacBook Pro, three years old, but with 6GB RAM)

Body:
I usually increase -Xmx to 800m

-Xmx800m

No other changes. I don't have any problems with that in any of my projects, some of them Grails projects. Lately I have followed the EAP versions, and now I use IDEA X.

(I also have a MacBook Pro, three years old, but with 6GB RAM)


问:
Polly retry policy outcome always successful regardless of actual response
I'm trying to take advantage of Polly's ability to handle arbitrary result conditions https://github.com/App-vNext/Polly/#step-1b-optionally-specify-return-results-you-want-to-handle.

In my test case I'm using RestSharp to make HTTP requests.  Here's my sample code:

```<code>var policy = Policy
    .HandleResult<IRestResponse>(r => r.Content.Contains("bla"))
    .Retry(2)
    .ExecuteAndCapture(() =>
        {
            IRestClient client = new RestClient("https://httpbin.org/anything");
            IRestRequest request = new RestRequest(Method.GET);
            var response = client.Execute(request);
            return response;
        });
</code>```

The call to https://httpbin.org/anything echos back a bunch of stuff - the exact content isn't relevant.  As you can see in the predicate I'm looking for the string "bla" in the result body.

The problem is that policy.Outcome is always successful (policy.Outcome == OutcomeType.Successful) but "bla" is not in the result body.

答:
The .HandleResult<TResult>(Func<TResult, bool>) clause specifies TResults you want to be considered failures - TResult values which should (in this case) trigger a retry. If "bla" is not in the result body, the result will be considered a success, a retry will not be made, and you will (expected behaviour) get .Outcome == OutcomeType.Successful.

The following unit-test in the Polly codebase demonstrates how .ExecuteAndCapture(...) is returning OutcomeType.Failure when it should: https://github.com/App-vNext/Polly/blob/73fc38029f52d2e1bfa6f4b03bcb1e12d8c78065/src/Polly.SharedSpecs/PolicyTResultSpecs.cs#L50

Body:
I'm trying to take advantage of Polly's ability to handle arbitrary result conditions https://github.com/App-vNext/Polly/#step-1b-optionally-specify-return-results-you-want-to-handle.

In my test case I'm using RestSharp to make HTTP requests.  Here's my sample code:

var policy = Policy
    .HandleResult<IRestResponse>(r => r.Content.Contains("bla"))
    .Retry(2)
    .ExecuteAndCapture(() =>
        {
            IRestClient client = new RestClient("https://httpbin.org/anything");
            IRestRequest request = new RestRequest(Method.GET);
            var response = client.Execute(request);
            return response;
        });

The call to https://httpbin.org/anything echos back a bunch of stuff - the exact content isn't relevant.  As you can see in the predicate I'm looking for the string "bla" in the result body.

The problem is that policy.Outcome is always successful (policy.Outcome == OutcomeType.Successful) but "bla" is not in the result body.


问:
TensorFlow for Go demo example run failed
i have the issue.

environment

```<code>macbookpro:lib fredlee$ go version
go version go1.8.3 darwin/amd64
macbookpro:lib fredlee$ pwd
/usr/local/lib
macbookpro:lib fredlee$ ls -alh libtensorflow.so
-r-xr-xr-x  1 root  wheel   102M  1  1  1970 libtensorflow.so
macbookpro:lib fredlee$ file libtensorflow.so
libtensorflow.so: Mach-O 64-bit dynamically linked shared library x86_64
macbookpro:lib fredlee$
</code>```

issue

```<code>> macbookpro:~ fredlee$ go get
> github.com/tensorflow/tensorflow/tensorflow/go macbookpro:~ fredlee$
> go test github.com/tensorflow/tensorflow/tensorflow/go
> # github.com/tensorflow/tensorflow/tensorflow/go ld: library not found for -ltensorflow clang: error: linker command failed with exit code 1
> (use -v to see invocation)
> FAIL  github.com/tensorflow/tensorflow/tensorflow/go [build failed]
</code>```

anyone can help me make it works?

答:
The error is pretty clear:

ld: library not found for -ltensorflow

When you run go test you're invoking the go compiler that compiles the required libraries, your test files and then executes them.

When you compile a program that uses a "non-pure" go library, you have to make the compiler (and the linker) aware of the library.

In the compilation phase, the compiler looks for the libraries (also) in the paths listed into the environment variable:

LIBRARY_PATH on OS X & Linux.

Thus you have to add into this variable the location of the compiled library.

For example I have:

```<code>TFGOLIB="${GOPATH}/src/github.com/tensorflow/tensorflow/bazel-bin/tensorflow"
export LIBRARY_PATH="${TFGOLIB}:${LIBRARY_PATH}"
</code>```

During the runtime, instead, the os looks for the library in order to perform dynamic linking.

Thus you have to set this other variable (LD_LIBRARY_PATH on Linux and DYLD_LIBRARY_PATH on OS X) to the same location.

Moreover I suggest  you to also add the CUDA library path to this variable, in order to make it available at runtime.

```<code>export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/opt/cuda/lib64:/opt/cuda/extras/CUPTI/lib64:/opt/cudnn5.1/cuda/lib64:${TFGOLIB}"
</code>```

Body:
i have the issue.

environment

macbookpro:lib fredlee$ go version
go version go1.8.3 darwin/amd64
macbookpro:lib fredlee$ pwd
/usr/local/lib
macbookpro:lib fredlee$ ls -alh libtensorflow.so
-r-xr-xr-x  1 root  wheel   102M  1  1  1970 libtensorflow.so
macbookpro:lib fredlee$ file libtensorflow.so
libtensorflow.so: Mach-O 64-bit dynamically linked shared library x86_64
macbookpro:lib fredlee$

issue

> macbookpro:~ fredlee$ go get
> github.com/tensorflow/tensorflow/tensorflow/go macbookpro:~ fredlee$
> go test github.com/tensorflow/tensorflow/tensorflow/go
> # github.com/tensorflow/tensorflow/tensorflow/go ld: library not found for -ltensorflow clang: error: linker command failed with exit code 1
> (use -v to see invocation)
> FAIL  github.com/tensorflow/tensorflow/tensorflow/go [build failed]

anyone can help me make it works?

Body:
The error is pretty clear:

ld: library not found for -ltensorflow

When you run go test you're invoking the go compiler that compiles the required libraries, your test files and then executes them.

When you compile a program that uses a "non-pure" go library, you have to make the compiler (and the linker) aware of the library.

In the compilation phase, the compiler looks for the libraries (also) in the paths listed into the environment variable:

LIBRARY_PATH on OS X & Linux.

Thus you have to add into this variable the location of the compiled library.

For example I have:

TFGOLIB="${GOPATH}/src/github.com/tensorflow/tensorflow/bazel-bin/tensorflow"
export LIBRARY_PATH="${TFGOLIB}:${LIBRARY_PATH}"

During the runtime, instead, the os looks for the library in order to perform dynamic linking.

Thus you have to set this other variable (LD_LIBRARY_PATH on Linux and DYLD_LIBRARY_PATH on OS X) to the same location.

Moreover I suggest  you to also add the CUDA library path to this variable, in order to make it available at runtime.

export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/opt/cuda/lib64:/opt/cuda/extras/CUPTI/lib64:/opt/cudnn5.1/cuda/lib64:${TFGOLIB}"


问:
Android webview with PDF load
I am loading a page inside the webview

```<code>webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.xxxxxxxxx/howtoguide.aspx");
</code>```

then inside the webview I have several function to click event below

```<code>            @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (url.contains("concierge@xxxx.com.sg")) {
                final Intent eIntent = new Intent(
                        android.content.Intent.ACTION_SEND);
                eIntent.setType("plain/text");
                eIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                        new String[]{"xxxxxx"});
                eIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                        "");
                eIntent.putExtra(android.content.Intent.EXTRA_TEXT,
                        "Text to be send");
                startActivity(Intent.createChooser(eIntent,
                        "Send mail..."));

            } else if (url.startsWith("tel:")) {

            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                startActivity(intent);
                view.reload();

            } else if (url.contains(".pdf")) {
            //Intent intent = new Intent(Intent.ACTION_VIEW);
            //intent.setDataAndType(Uri.parse(url), "application/pdf");
            //try{
            //view.getContext().startActivity(intent);
            //} catch (ActivityNotFoundException e) {
            //user does not have a pdf viewer installed
            //}
            // view.loadUrl("https://docs.google.com/viewer?url=" + url);
               view.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + url);
            } else {
                view.loadUrl(url);
            }
            return true;
        }
</code>```

in this webview there is a click event for PDF. So if I click this the PDF not loading

答:
That the use of these methods need to log in to Google.

Other way use pdf.js

You must save pdf file into sdcard and load in webview.

Add the pdfjs files to your Assets directory

```<code> else if (url.contains(".pdf"))
        {
           File file = new File(Environment.getExternalStorageDirectory() + "/test.pdf");

   view.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=" + file.getAbsolutePath() + "#zoom=page-width");
        }
</code>```

Full sample project

Title: Android webview with PDF load

Body:
I am loading a page inside the webview

webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.xxxxxxxxx/howtoguide.aspx");

then inside the webview I have several function to click event below

            @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (url.contains("concierge@xxxx.com.sg")) {
                final Intent eIntent = new Intent(
                        android.content.Intent.ACTION_SEND);
                eIntent.setType("plain/text");
                eIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                        new String[]{"xxxxxx"});
                eIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                        "");
                eIntent.putExtra(android.content.Intent.EXTRA_TEXT,
                        "Text to be send");
                startActivity(Intent.createChooser(eIntent,
                        "Send mail..."));

            } else if (url.startsWith("tel:")) {

            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                startActivity(intent);
                view.reload();

            } else if (url.contains(".pdf")) {
            //Intent intent = new Intent(Intent.ACTION_VIEW);
            //intent.setDataAndType(Uri.parse(url), "application/pdf");
            //try{
            //view.getContext().startActivity(intent);
            //} catch (ActivityNotFoundException e) {
            //user does not have a pdf viewer installed
            //}
            // view.loadUrl("https://docs.google.com/viewer?url=" + url);
               view.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + url);
            } else {
                view.loadUrl(url);
            }
            return true;
        }

in this webview there is a click event for PDF. So if I click this the PDF not loading

Body:
That the use of these methods need to log in to Google.

Other way use pdf.js

You must save pdf file into sdcard and load in webview.

Add the pdfjs files to your Assets directory

 else if (url.contains(".pdf"))
        {
           File file = new File(Environment.getExternalStorageDirectory() + "/test.pdf");

   view.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=" + file.getAbsolutePath() + "#zoom=page-width");
        }

Full sample project


问:
My local website freeze my raspberry
I have a Raspberry PI3 with Apache installed. I made a website where I read some outputs commands (4 commands) and I refresh every 50 ms each command to get the exact value in time. I already used flush command but it doesn't change.

This local site just gives me some information in CANBUS from a machine.

But, after 2 hours in the website , the memory usage is nearly full (947732 kiB in total, 874855 kiB used after 2 hours).

Does it because I never erase the memory after I read a value ?

To see approximatly how I read a value in variable_can.php :

<?php
$output = shell_exec("sh r.sh"); // r.sh contains the command
preg_match("/1D000700 +\[2\]\s+\K[A-Z0-9]{2}\s+[A-Z0-9]{2}/",$output,$value);
echo "$value A";
?>```
</div>
</div>
</p>

<p>in my index.php where I have javascript :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>function myFunction(){
$.ajax({ url: 'variable_can.php',
             data: {action: 'variable_can'},
             type: 'post',
             success: function(output) {
              document.getElementById("demo").innerHTML = output; // demo is my ID of my variable_can.php
              setInterval(myFunction(), 50);
                      }
          });

    }
    setInterval(myFunction(), 50);</code>```

答: It's probably because you run a shell script called r.sh, and you never kill it. So every 50ms it'll re-run the shell script.

Title: My local website freeze my raspberry

Body:
I have a Raspberry PI3 with Apache installed. I made a website where I read some outputs commands (4 commands) and I refresh every 50 ms each command to get the exact value in time. I already used flush command but it doesn't change.

This local site just gives me some information in CANBUS from a machine.

But, after 2 hours in the website , the memory usage is nearly full (947732 kiB in total, 874855 kiB used after 2 hours).

Does it because I never erase the memory after I read a value ?

To see approximatly how I read a value in variable_can.php :

<?php
$output = shell_exec("sh r.sh"); // r.sh contains the command
preg_match("/1D000700 +\[2\]\s+\K[A-Z0-9]{2}\s+[A-Z0-9]{2}/",$output,$value);
echo "$value A";
?>

in my index.php where I have javascript :

function myFunction(){
$.ajax({ url: 'variable_can.php',
             data: {action: 'variable_can'},
             type: 'post',
             success: function(output) {
              document.getElementById("demo").innerHTML = output; // demo is my ID of my variable_can.php
              setInterval(myFunction(), 50);
                      }
          });

    }
    setInterval(myFunction(), 50);


问:
Class that returns json, python
I have a python class that should return a json, it looks something like this:

```<code>class ScanThis():
    def__init__(self, test):
        data={}
        if test>5:
            data["amount"] = test
            self.json_data = json.dumps(data)
        else:
            data["fail"] = test
            self.json_data = json.dumps(data)

    def __str__(self):
        return self.json_data
</code>```

and I'm trying to call it like so:

```<code>output= json.loads(ScanThis(8))
print(output["command"])
</code>```

But I get this error:

```<code>TypeError: the JSON object must be str, bytes or bytearray, not 'ScanThis'
</code>```

I believe my earlier clas returns an object of type ScanThis() rather than a JSon like I wanted. I just wanted to now how I'd fix this
Thank you

PS: I apologise if this code is rough or invalid, it's not the actual code, just something similar I made up

Update: Again, this isn't the real code, it's just a small basic fragment of the actual code. There's a good reason I'm using a class, and a json is used cause data transfer over the internet is involved

答:
Use str(..)

You can't call json.loads on a ScanThis object directly. So that won't work. Like the error says, json.loads expects a str, bytes or bytearray object.

You can however use str(..) to invoke the __str__(self) method, and thus obtain the JSON data:

```<code>output = json.loads(<b>str(</b>ScanThis(8)<b>)</b>)
#                   ^ get the __str__ result </code>```

Use another method

That being said, it is usually a better idea to define a method, for instance to_json to obtain the JSON data, since now you have made str(..) return a JSON object. So perhaps a more elegant way to do this is the following:

```<code>class ScanThis():
    def__init__(self, test):
        data={}
        if test>5:
            data["amount"] = test
            self.json_data = json.dumps(data)
        else:
            data["fail"] = test
            self.json_data = json.dumps(data)

    def to_json(self):
        return self.json_data
</code>```

and call it with:

```<code>output = json.loads(ScanThis(8).to_json())
</code>```

Now you can still use __str__ for another purpose. Furthermore by using to_json you make it explicit that the result will be a JSON string. Using str for JSON conversion is of course not forbidden, but str(..) as a name, does not provide much guarantees about the format of the result whereas to_json (or another similar name) strongly hints that you will obtain JSON data.

Title: Class that returns json, python

Body:
I have a python class that should return a json, it looks something like this:

class ScanThis():
    def__init__(self, test):
        data={}
        if test>5:
            data["amount"] = test
            self.json_data = json.dumps(data)
        else:
            data["fail"] = test
            self.json_data = json.dumps(data)

    def __str__(self):
        return self.json_data

and I'm trying to call it like so:

output= json.loads(ScanThis(8))
print(output["command"])

But I get this error:

TypeError: the JSON object must be str, bytes or bytearray, not 'ScanThis'

I believe my earlier clas returns an object of type ScanThis() rather than a JSon like I wanted. I just wanted to now how I'd fix this
Thank you

PS: I apologise if this code is rough or invalid, it's not the actual code, just something similar I made up

Update: Again, this isn't the real code, it's just a small basic fragment of the actual code. There's a good reason I'm using a class, and a json is used cause data transfer over the internet is involved

Body:
Use str(..)

You can't call json.loads on a ScanThis object directly. So that won't work. Like the error says, json.loads expects a str, bytes or bytearray object.

You can however use str(..) to invoke the __str__(self) method, and thus obtain the JSON data:

output = json.loads(str(ScanThis(8)))
#                   ^ get the __str__ result

Use another method

That being said, it is usually a better idea to define a method, for instance to_json to obtain the JSON data, since now you have made str(..) return a JSON object. So perhaps a more elegant way to do this is the following:

class ScanThis():
    def__init__(self, test):
        data={}
        if test>5:
            data["amount"] = test
            self.json_data = json.dumps(data)
        else:
            data["fail"] = test
            self.json_data = json.dumps(data)

    def to_json(self):
        return self.json_data

and call it with:

output = json.loads(ScanThis(8).to_json())

Now you can still use __str__ for another purpose. Furthermore by using to_json you make it explicit that the result will be a JSON string. Using str for JSON conversion is of course not forbidden, but str(..) as a name, does not provide much guarantees about the format of the result whereas to_json (or another similar name) strongly hints that you will obtain JSON data.


问:
How to replace the DataField values with exact column names in Spark-MLlib PMML file?
I use Spark 2.1.0.

I've been trying to export Spark-MLlib Linear Regression model as PMML file. I've also successfully exported the PMML file. But in that file, I couldn't see any field name in it. All I can see is like this,

Can anyone let me know what's the reason for this? Also, please let me know how to obtain the column names in place of that.

答:
There are two approaches to exporting Apache Spark models into PMML data format. First, when working at Spark ML abstraction level, then you can use the JPMML-SparkML library. Second, when working at Spark MLlib abstraction level, which appears to be the case here, then you can use the built-in PMMLExportable trait.

JPMML-SparkML retrieves column names from the Spark ML data schema via DataFrame#schema(). Unfortunately, there is no such option for Spark MLlib, so feature names "field_{n}" and the label name "target" are simply dummy hard-coded names.

It is fairly easy to rename fields in the PMML document using the JPMML-Model library:

```<code>pmmlExportable.toPMML("/tmp/raw-pmml-file")
org.dmg.pmml.PMML pmml = org.jpmml.model.JAXBUtil.unmarshal("/tmp/raw-pmml-file");
org.jpmml.model.visitors.FieldRenamer targetRenamer = new FieldRenamer(FieldName.create("target"), FieldRenamer.create("y"));
targetRenamer.applyTo(pmml);
org.jpmml.model.JAXBUtil.marshal(pmml, "/tmp/final-pmml-file");
</code>```

If you marshal this PMML object instance to a PMML file, then you can see that the field "target" (and all its references) has been renamed to "y". Repeat the procedure with features.

Body:
There are two approaches to exporting Apache Spark models into PMML data format. First, when working at Spark ML abstraction level, then you can use the JPMML-SparkML library. Second, when working at Spark MLlib abstraction level, which appears to be the case here, then you can use the built-in PMMLExportable trait.

JPMML-SparkML retrieves column names from the Spark ML data schema via DataFrame#schema(). Unfortunately, there is no such option for Spark MLlib, so feature names "field_{n}" and the label name "target" are simply dummy hard-coded names.

It is fairly easy to rename fields in the PMML document using the JPMML-Model library:

pmmlExportable.toPMML("/tmp/raw-pmml-file")
org.dmg.pmml.PMML pmml = org.jpmml.model.JAXBUtil.unmarshal("/tmp/raw-pmml-file");
org.jpmml.model.visitors.FieldRenamer targetRenamer = new FieldRenamer(FieldName.create("target"), FieldRenamer.create("y"));
targetRenamer.applyTo(pmml);
org.jpmml.model.JAXBUtil.marshal(pmml, "/tmp/final-pmml-file");

If you marshal this PMML object instance to a PMML file, then you can see that the field "target" (and all its references) has been renamed to "y". Repeat the procedure with features.


问:
browser.tabs undefined in Microsoft Edge extension
I am writing a Microsoft Edge extension.

I have the following manifest file:

```<code>{
  "author": "",
  "description": "Test",
  "name": "Test",
  "version": "1.0",
    "permissions": [
        "tabs",
        "<all_urls>"
    ],
  "content_scripts": [{
    "js": ["script.js"],
    "matches": ["*://*/*"]
  }],
  "icons": {
    "48": "icons/icon-40x40.png"
  }
}
</code>```

When i put into my script.js:

```<code>var currentTab = browser.tabs.getCurrent();
alert(currentTab.index);
</code>```

It fails because browser.tabs is undefined?

Why?

答:
You can call this function browser.tabs.getCurrent() in contexts where there is a browser tab, such as an options page. If you call it from a background script or a popup, it will return undefined.But as I see you have used this function in content script, so it shouldn't be a problem.

This is an asynchronous function that returns a Promise.

You can check this site for further information on how to use the function for Edge Extension.

Also you shouldn't leave the author field empty, it may give some error . So try writing you name in it.

Body:
I am writing a Microsoft Edge extension.

I have the following manifest file:

{
  "author": "",
  "description": "Test",
  "name": "Test",
  "version": "1.0",
    "permissions": [
        "tabs",
        "<all_urls>"
    ],
  "content_scripts": [{
    "js": ["script.js"],
    "matches": ["*://*/*"]
  }],
  "icons": {
    "48": "icons/icon-40x40.png"
  }
}

When i put into my script.js:

var currentTab = browser.tabs.getCurrent();
alert(currentTab.index);

It fails because browser.tabs is undefined?

Why?


问:
ignore prefix (namespace) when unmarshalling xml
I have this XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<s:XXMsg xmlns:s="com:sample:test:msg">
    <s:Header>
        <s:cpyCod>xxx</s:cpyCod>
        <s:appCod>yyy</s:appCod>
    </s:Header>
</s:XXMsg>
</code>```

and I want this to be unmarshalled into the following Java class:

```<code>public class XXHeader
{
    private String cpyCod;
    private String appCod;
}
</code>```

I have written this code:

```<code>    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
    try
    {
        XMLStreamReader streamReader = inputFactory
            .createXMLStreamReader(Test.class.getClassLoader().getResourceAsStream("xxmsg.xml"));
        while (streamReader.hasNext())
        {
            int next = streamReader.next();
            if (streamReader.getEventType() == XMLStreamReader.START_ELEMENT
                && streamReader.getLocalName().equals("Header"))
            {
                JAXBContext context = JAXBContext.newInstance(XXHeader.class);
                Unmarshaller unmarshaller = context.createUnmarshaller();
                XXHeader xxHeader = unmarshaller.unmarshal(streamReader, XXHeader.class).getValue();
                System.out.println(xxHeader);
                break;
            }
        }
</code>```

I am getting all field values of XXHeader as null. But if I do change the xml and remove the prefixes s: in every element then I get the correct values.

How can I ignore this prefix while unmarshalling to get the correct values?

PS: Use of @XML** annotations in XXHeader class is discouraged.

答: Here you may find useful information about ignoring namespace or you may define XML schema (with field description) and use it instead of com:sample:test:msg.

Body:
I have this XML:

<?xml version="1.0" encoding="UTF-8"?>
<s:XXMsg xmlns:s="com:sample:test:msg">
    <s:Header>
        <s:cpyCod>xxx</s:cpyCod>
        <s:appCod>yyy</s:appCod>
    </s:Header>
</s:XXMsg>

and I want this to be unmarshalled into the following Java class:

public class XXHeader
{
    private String cpyCod;
    private String appCod;
}

I have written this code:

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
    try
    {
        XMLStreamReader streamReader = inputFactory
            .createXMLStreamReader(Test.class.getClassLoader().getResourceAsStream("xxmsg.xml"));
        while (streamReader.hasNext())
        {
            int next = streamReader.next();
            if (streamReader.getEventType() == XMLStreamReader.START_ELEMENT
                && streamReader.getLocalName().equals("Header"))
            {
                JAXBContext context = JAXBContext.newInstance(XXHeader.class);
                Unmarshaller unmarshaller = context.createUnmarshaller();
                XXHeader xxHeader = unmarshaller.unmarshal(streamReader, XXHeader.class).getValue();
                System.out.println(xxHeader);
                break;
            }
        }

I am getting all field values of XXHeader as null. But if I do change the xml and remove the prefixes s: in every element then I get the correct values.

How can I ignore this prefix while unmarshalling to get the correct values?

PS: Use of @XML** annotations in XXHeader class is discouraged.


问:
Restore Nuget Packages command in VS2015, restoring only XMLs not the DLLs
I got a new laptop with Visual Studio 2015. I have an existing VS Solution that worked well in my previous Laptop.

In my new laptop, I have Nuget restore issue, it is restoring only the XML files not the DLLs for most of the assemblies. Please check the below steps I performed.

In "Nuget Package manager->General" I checked/enabled the below options.

Allow Nuget to download missing packages

Automatically check List item for missing package

Steps performed:

I have downloaded the Solution from the Source control, with empty Package folder

I rightclick the solution and selected "Restore Nuget Package"

It created the Package folder and all assemblies related sub folders

However, when I went into some folders, example the Newtonsoft.Json.8.0.1 folder it contains a subfolder named lib\net45 with only Newtonsoft.Json.xml in it but NO DLLs

The Newtonsoft.Json.dll is missing in the subfolders

Most of the DLLs are missing in the subfolders and it have only XML files in that subfolders

Please let me know how to resolve it.

答:
Please let me know how to resolve it.

First close all instances of Visual Studio. This is generally a good idea when doing anything outside of VS that will affect what VS thinks is going on.

Then try to clear your local package cache: nuget.exe locals all -clear.

You can follow below steps to clear your local package:

First, download the nuget command line tool from here.

Next, open a command prompt and cd to the directory to which nuget.exe was downloaded.

You can list the local caches with this command:

```<code>nuget locals all -list
</code>```

You can clear all caches with this command:

```<code>nuget locals all -clear
</code>```

Besides, try to make the Available packages sources only with nuget.org (Tools->Options->NuGet Package Manager->Package Source)

Body:
Please let me know how to resolve it.

First close all instances of Visual Studio. This is generally a good idea when doing anything outside of VS that will affect what VS thinks is going on.

Then try to clear your local package cache: nuget.exe locals all -clear.

You can follow below steps to clear your local package:

First, download the nuget command line tool from here.

Next, open a command prompt and cd to the directory to which nuget.exe was downloaded.

You can list the local caches with this command:

nuget locals all -list

You can clear all caches with this command:

nuget locals all -clear

Besides, try to make the Available packages sources only with nuget.org (Tools->Options->NuGet Package Manager->Package Source)


问:
Django - Filter ForeignKey drop down menu in inline formsets
I have the following models:

models.py

```<code>class Train(models.Model):
    pass

class City(models.Model):
    train = models.ForeignKey(Train)
    name = models.CharField(max_length=100)

class Route(models.Model):
    train = models.ForeignKey(Train)
    name = models.CharField(max_length=100)

class Travel(models.Model):
    train = models.ForeignKey(Train)
    current_city = models.ForeignKey(City, related_name = 'current')
    through = models.ForeignKey(Route)
    next_city = models.ForeignKey(City, related_name = 'next')
</code>```

and I'm using inline formsets to create Travel instances related to a specific train with the following:

views.py

```<code>class TrainInfoUpdate(UpdateView):
    model = Train
    fields = []
    success_url = reverse_lazy('train-list')

    def get_context_data(self, **kwargs):
        data = super(TrainInfoUpdate, self).get_context_data(**kwargs)
        if self.request.POST:
            data['travels'] = TravelFormSet(self.request.POST, instance=self.object)
        else:
            data['travels'] = TravelFormSet(instance=self.object)
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        travels = context['travels']
        with transaction.atomic():
            self.object = form.save()

            if travels.is_valid():
                travels.instance = self.object
                travels.save()
        return super(TrainInfoUpdate, self).form_valid(form)
</code>```

forms.py

```<code>class TrainForm(ModelForm):
    class Meta:
        model = Train

class CityForm(ModelForm):
    class Meta:
        model = City

class RouteForm(ModelForm):
    class Meta:
        model = Route

class TravelForm(ModelForm):
    class Meta:
        model = Travel

CityFormSet = inlineformset_factory(Train, City, form=CityForm, extra=1)

RouteFormSet = inlineformset_factory(Train, Route, form=RouteForm, extra=1)

TravelFormSet = inlineformset_factory(Train, Travel, form=TravelForm, extra=1)
</code>```

This gives me dropdown menu with all the cities and routes available but I would like to limit them to only the cities and routes related to that train, how can I achieve that?

答:
You can use formfield_callback argument to inlineformset_factory to customize the queryset. The inline documentation the source code says this about the formfield_callback argument:

formfield_callback is a callable that takes a model field and
  returns
      a form field.

For your case the solution would be:

```<code>def custom_form_field_callback(field, **kwargs):
    cities_query = City.objects.filter(filter_field=filter_value)
    if field.name == "city":
         return City(queryset= cities_query)
    else:
         return field.formfield(**kwargs)

CityFormSet = inlineformset_factory(Train, City, formfield_callback=custom_form_field_callback)
</code>```

Note: If you are not customizing the ModelForm then you don't need to pass the form=CityForm argument to inlineformset_factory

Body:
I have the following models:

models.py

class Train(models.Model):
    pass

class City(models.Model):
    train = models.ForeignKey(Train)
    name = models.CharField(max_length=100)

class Route(models.Model):
    train = models.ForeignKey(Train)
    name = models.CharField(max_length=100)

class Travel(models.Model):
    train = models.ForeignKey(Train)
    current_city = models.ForeignKey(City, related_name = 'current')
    through = models.ForeignKey(Route)
    next_city = models.ForeignKey(City, related_name = 'next')

and I'm using inline formsets to create Travel instances related to a specific train with the following:

views.py

class TrainInfoUpdate(UpdateView):
    model = Train
    fields = []
    success_url = reverse_lazy('train-list')

    def get_context_data(self, **kwargs):
        data = super(TrainInfoUpdate, self).get_context_data(**kwargs)
        if self.request.POST:
            data['travels'] = TravelFormSet(self.request.POST, instance=self.object)
        else:
            data['travels'] = TravelFormSet(instance=self.object)
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        travels = context['travels']
        with transaction.atomic():
            self.object = form.save()

            if travels.is_valid():
                travels.instance = self.object
                travels.save()
        return super(TrainInfoUpdate, self).form_valid(form)

forms.py

class TrainForm(ModelForm):
    class Meta:
        model = Train

class CityForm(ModelForm):
    class Meta:
        model = City

class RouteForm(ModelForm):
    class Meta:
        model = Route

class TravelForm(ModelForm):
    class Meta:
        model = Travel

CityFormSet = inlineformset_factory(Train, City, form=CityForm, extra=1)

RouteFormSet = inlineformset_factory(Train, Route, form=RouteForm, extra=1)

TravelFormSet = inlineformset_factory(Train, Travel, form=TravelForm, extra=1)

This gives me dropdown menu with all the cities and routes available but I would like to limit them to only the cities and routes related to that train, how can I achieve that?

Body:
You can use formfield_callback argument to inlineformset_factory to customize the queryset. The inline documentation the source code says this about the formfield_callback argument:

formfield_callback is a callable that takes a model field and
  returns
      a form field.

For your case the solution would be:

def custom_form_field_callback(field, **kwargs):
    cities_query = City.objects.filter(filter_field=filter_value)
    if field.name == "city":
         return City(queryset= cities_query)
    else:
         return field.formfield(**kwargs)

CityFormSet = inlineformset_factory(Train, City, formfield_callback=custom_form_field_callback)

Note: If you are not customizing the ModelForm then you don't need to pass the form=CityForm argument to inlineformset_factory


问:
vb.net key combination
I'm trying to capture two key presses in my VB.net application, for this example CTRL + B, the code below doesn't work but it does for single keys. I have tried setting keypreview as true but this has no effect.

```<code>  Private Sub main_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles mybase.KeyDown
            If e.KeyCode = Keys.ControlKey And e.KeyCode = Keys.B Then
                MsgBox("CTRL + B Pressed !")
            End If
        End Sub
    End Class
</code>```

Thanks

答:
If you look at the documentation for KeyEventArgs, you'll note that the class exposes properties for ALT, CTRL and Modifiers which allow you to determine whether these keys were pressed in addition to the main symbol key you're interested in. </p>

```<code>Private Sub main_KeyDown(
        ByVal sender As Object,
        ByVal e As System.Windows.Forms.KeyEventArgs)
   Handles mybase.KeyDown

    If e.Control And e.KeyCode = Keys.B Then
        MsgBox("CTRL + B Pressed !")
    End If
End Sub
</code>```

Title: vb.net key combination

Body:
I'm trying to capture two key presses in my VB.net application, for this example CTRL + B, the code below doesn't work but it does for single keys. I have tried setting keypreview as true but this has no effect.

  Private Sub main_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles mybase.KeyDown
            If e.KeyCode = Keys.ControlKey And e.KeyCode = Keys.B Then
                MsgBox("CTRL + B Pressed !")
            End If
        End Sub
    End Class

Thanks

Body:
If you look at the documentation for KeyEventArgs, you'll note that the class exposes properties for ALT, CTRL and Modifiers which allow you to determine whether these keys were pressed in addition to the main symbol key you're interested in.

Private Sub main_KeyDown(
        ByVal sender As Object,
        ByVal e As System.Windows.Forms.KeyEventArgs)
   Handles mybase.KeyDown

    If e.Control And e.KeyCode = Keys.B Then
        MsgBox("CTRL + B Pressed !")
    End If
End Sub


问:
How to display plain-text response from a Server using HTTP GET in Angular2
I am working on Angular-4 (most recent) with @angular/cli on Windows 10 with npm v5.0.0 and node v8.0.0.

I have a server set up with actually gives response in Plain-Text.

I have a very simple interface where all I do is press a button and ask for GET request from my server. My goal is to show the plain text between

Working of the server

```<code>http://servername.com/detectMeaning?keyword=mail
</code>```

with GET gives me some text in plain-text.

My Code

my component is called simplesearch

```<code>-- simplesearch/
               --simplesearch.component.ts
               --simplesearch.service.ts
-- app.component.ts
-- app.component.html
-- app.component.css
-- app.module.ts
</code>```

simplesearch.component.ts:

```<code>import { Component } from '@angular/core';
import { SimplesearchService } from './simplesearch.service';
@Component({
   selector: 'app-simplesearch',
    template: `
    <button (click)="onTestGet()">GET Test</button>
    <p>{{getOutput}}</p>
    `,
    styles: [],
    providers: [SimplesearchService]
})
export class SimplesearchComponent {
  getOutput: string;

  constructor(private httpService: SimplesearchService) {}

  onTestGet() {
     this.httpService.getData()
      .subscribe(
        data => this.getOutput = data, // since data is plain-text
        error => console.log(error)
      );
  }
}
</code>```

simplesearch.service.ts

```<code>import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()

export class SimplesearchService {
    private headers = new Headers();
    constructor(private http: Http) {
        this.headers.append('Allow-Control-Allow-Origin', '*');
        this.headers.append('Content-Type', 'text/plain');
     }

    getData(){
        return this.http
        .get('http://myserver.com:8090/detectMeaning?keyword=mail')
        .map(res => res.text());
    }
}
</code>```

Error in Console for Mozilla Firefox

After the XHR GET request after the Button Push I get the error

Object { _body: error, status: 0, ok: false, statusText: "", headers: Object, type: 3, url: null }

I assume this is the JSON response I receive hence the .JSON.stringify(data) in my code.

I also end up getting the CORS Header 'Access-Control-Allow-Origin' in the end. But I have added the header in the code already!

I have tried doing a curl on the URL for the same and there I get the result easily.

What are the necessary steps or improvements I should look into?

答:
The API was available for usage after the Server was set up with CORS so that a cross-origin request could be made from the Frontend.

Also the final edit made where this.getOutput = data is used in my case since the available format is in plain-text and binding it into JSON.stringify() would actually lead to an error:

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of JSON data

which will be visible in the Debugger Tools under Network Analyses.

Body:
I am working on Angular-4 (most recent) with @angular/cli on Windows 10 with npm v5.0.0 and node v8.0.0.

I have a server set up with actually gives response in Plain-Text.

I have a very simple interface where all I do is press a button and ask for GET request from my server. My goal is to show the plain text between

Working of the server

http://servername.com/detectMeaning?keyword=mail

with GET gives me some text in plain-text.

My Code

my component is called simplesearch

-- simplesearch/
               --simplesearch.component.ts
               --simplesearch.service.ts
-- app.component.ts
-- app.component.html
-- app.component.css
-- app.module.ts

simplesearch.component.ts:

import { Component } from '@angular/core';
import { SimplesearchService } from './simplesearch.service';
@Component({
   selector: 'app-simplesearch',
    template: `
    <button (click)="onTestGet()">GET Test</button>

{{getOutput}}

    `,
    styles: [],
    providers: [SimplesearchService]
})
export class SimplesearchComponent {
  getOutput: string;

  constructor(private httpService: SimplesearchService) {}

  onTestGet() {
     this.httpService.getData()
      .subscribe(
        data => this.getOutput = data, // since data is plain-text
        error => console.log(error)
      );
  }
}

simplesearch.service.ts

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()

export class SimplesearchService {
    private headers = new Headers();
    constructor(private http: Http) {
        this.headers.append('Allow-Control-Allow-Origin', '*');
        this.headers.append('Content-Type', 'text/plain');
     }

    getData(){
        return this.http
        .get('http://myserver.com:8090/detectMeaning?keyword=mail')
        .map(res => res.text());
    }
}

Error in Console for Mozilla Firefox

After the XHR GET request after the Button Push I get the error

Object { _body: error, status: 0, ok: false, statusText: "", headers: Object, type: 3, url: null }

I assume this is the JSON response I receive hence the .JSON.stringify(data) in my code.

I also end up getting the CORS Header 'Access-Control-Allow-Origin' in the end. But I have added the header in the code already!

I have tried doing a curl on the URL for the same and there I get the result easily.

What are the necessary steps or improvements I should look into?


问:
xapian-full installed on mac os x snow leopard but failed with dlopen LoadError
Since I have tried to install xapian but failed, I try another alternative with xapian-full. Installation seems goes well, but when I try to write code with that I got toasted with error message again:

```<code>irb(main):001:0> require 'xapian'
LoadError: dlopen(/opt/ruby-enterprise/lib/ruby/gems/1.8/gems/xapian-full-1.1.3.4/lib/_xapian.bundle, 9): Library not loaded: /usr/local/lib/libxapian-1.1.3.dylib
  Referenced from: /opt/ruby-enterprise/lib/ruby/gems/1.8/gems/xapian-full-1.1.3.4/lib/_xapian.bundle
  Reason: image not found - /opt/ruby-enterprise/lib/ruby/gems/1.8/gems/xapian-full-1.1.3.4/lib/_xapian.bundle
    from /opt/ruby-enterprise/lib/ruby/gems/1.8/gems/xapian-full-1.1.3.4/lib/_xapian.bundle
    from /opt/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
    from /opt/ruby-enterprise/lib/ruby/site_ruby/1.8/xapian.rb:40
    from /opt/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
    from /opt/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
    from (irb):1
</code>```

Anyone know how to solve this?

答:
This issue is fixed in https://github.com/rex1fernando/xapian-full. From there, download the updated Rakefile and place it in

```<code>~/.gem/gems/xapian-full-1.1.3.4
</code>```

Rebuild the gem by typing

```<code>rake
</code>```

and the problem should be solved.

Update: rex1fernando recommends a nicer procedure in http://masanjin.net/sup-bugs/msg323:

```<code>git clone git://github.com/rex1fernando/xapian-full.git
cd xapian-full
(sudo) gem uninstall xapian-full
gem build xapian-full.gemspec
(sudo) gem install --local xapian-full
</code>```

Body:
Since I have tried to install xapian but failed, I try another alternative with xapian-full. Installation seems goes well, but when I try to write code with that I got toasted with error message again:

irb(main):001:0> require 'xapian'
LoadError: dlopen(/opt/ruby-enterprise/lib/ruby/gems/1.8/gems/xapian-full-1.1.3.4/lib/_xapian.bundle, 9): Library not loaded: /usr/local/lib/libxapian-1.1.3.dylib
  Referenced from: /opt/ruby-enterprise/lib/ruby/gems/1.8/gems/xapian-full-1.1.3.4/lib/_xapian.bundle
  Reason: image not found - /opt/ruby-enterprise/lib/ruby/gems/1.8/gems/xapian-full-1.1.3.4/lib/_xapian.bundle
    from /opt/ruby-enterprise/lib/ruby/gems/1.8/gems/xapian-full-1.1.3.4/lib/_xapian.bundle
    from /opt/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
    from /opt/ruby-enterprise/lib/ruby/site_ruby/1.8/xapian.rb:40
    from /opt/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
    from /opt/ruby-enterprise/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
    from (irb):1

Anyone know how to solve this?

Body:
This issue is fixed in https://github.com/rex1fernando/xapian-full. From there, download the updated Rakefile and place it in

~/.gem/gems/xapian-full-1.1.3.4

Rebuild the gem by typing

rake

and the problem should be solved.

Update: rex1fernando recommends a nicer procedure in http://masanjin.net/sup-bugs/msg323:

git clone git://github.com/rex1fernando/xapian-full.git
cd xapian-full
(sudo) gem uninstall xapian-full
gem build xapian-full.gemspec
(sudo) gem install --local xapian-full


问:
Open new window in background using Chrome API
I have a content script that sends a basic message (a link) to my background.js of of my extension.

My question is how can I open that link in the background with chrome.windows.create without it gaining focus at all, also when i minimize chrome and another link gets opened I dont want chrome to gain focus again.

```<code>//Opens received link //background.js
chrome.runtime.onMessage.addListener( function(message, sender, sendResponse){
    chrome.windows.create({
        url: message.link
    });
});
</code>```

Edit:
I have added this to my code for creating the new window and it doesnt switch to it but my question is, is there any way that can all happen in the background? like without any window showing up, not even minimized?

```<code>chrome.windows.create({
    url: message.link,
    type: "normal",
    state: "minimized"
});
</code>```

答:
```<code>chrome.windows.getCurrent(function(winCurrent){
        chrome.windows.create({url:message.link}, function(win){
            chrome.windows.update(winCurrent.id, {focused: true});
        });
    });
</code>```

Use getCurrent to get your current window, create a new window and shift focus back to the previous window (winCurrent). The process is fast so viewer doesn't feel much.

Body:
I have a content script that sends a basic message (a link) to my background.js of of my extension.

My question is how can I open that link in the background with chrome.windows.create without it gaining focus at all, also when i minimize chrome and another link gets opened I dont want chrome to gain focus again.

//Opens received link //background.js
chrome.runtime.onMessage.addListener( function(message, sender, sendResponse){
    chrome.windows.create({
        url: message.link
    });
});

Edit:
I have added this to my code for creating the new window and it doesnt switch to it but my question is, is there any way that can all happen in the background? like without any window showing up, not even minimized?

chrome.windows.create({
    url: message.link,
    type: "normal",
    state: "minimized"
});

Body:
chrome.windows.getCurrent(function(winCurrent){
        chrome.windows.create({url:message.link}, function(win){
            chrome.windows.update(winCurrent.id, {focused: true});
        });
    });

Use getCurrent to get your current window, create a new window and shift focus back to the previous window (winCurrent). The process is fast so viewer doesn't feel much.


问:
How can I turn a DataTable to a CSV?
Could somebody please tell me why the following code is not working.  The data is saved into the csv file, however the data is not separated.  It all exists within the first cell of each row.

```<code>StringBuilder sb = new StringBuilder();

foreach (DataColumn col in dt.Columns)
{
    sb.Append(col.ColumnName + ',');
}

sb.Remove(sb.Length - 1, 1);
sb.Append(Environment.NewLine);

foreach (DataRow row in dt.Rows)
{
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        sb.Append(row[i].ToString() + ",");
    }

    sb.Append(Environment.NewLine);
}

File.WriteAllText("test.csv", sb.ToString());
</code>```

Thanks.

答:
```<code>public void ExpoetToCSV(DataTable dtDataTable, string strFilePath)
{

    StreamWriter sw = new StreamWriter(strFilePath, false);
    //headers
    for (int i = 0; i < dtDataTable.Columns.Count; i++)
    {
        sw.Write(dtDataTable.Columns[i].ToString().Trim());
        if (i < dtDataTable.Columns.Count - 1)
        {
            sw.Write(",");
        }
    }
    sw.Write(sw.NewLine);
    foreach (DataRow dr in dtDataTable.Rows)
    {
        for (int i = 0; i < dtDataTable.Columns.Count; i++)
        {
            if (!Convert.IsDBNull(dr[i]))
            {
                string value = dr[i].ToString().Trim();
                if (value.Contains(','))
                {
                    value = String.Format("\"{0}\"", value);
                    sw.Write(value);
                }
                else
                {
                    sw.Write(dr[i].ToString().Trim());
                }
            }
            if (i < dtDataTable.Columns.Count - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);
    }
    sw.Close();
}
</code>```

Title: How can I turn a DataTable to a CSV?

Body:
Could somebody please tell me why the following code is not working.  The data is saved into the csv file, however the data is not separated.  It all exists within the first cell of each row.

StringBuilder sb = new StringBuilder();

foreach (DataColumn col in dt.Columns)
{
    sb.Append(col.ColumnName + ',');
}

sb.Remove(sb.Length - 1, 1);
sb.Append(Environment.NewLine);

foreach (DataRow row in dt.Rows)
{
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        sb.Append(row[i].ToString() + ",");
    }

    sb.Append(Environment.NewLine);
}

File.WriteAllText("test.csv", sb.ToString());

Thanks.


问:
How to make no item selected in a listbox on tkinter
Is there a method to make it so that there are no items selected on a listbox in tkinter? The only idea I have right now is to delete whatever item is selected and then put it back.</p>

答:
There's a selection_clear() method for this purpose.

Try this snippet:

```<code>try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk

#   root
root = tk.Tk()

#   listbox
listbox = tk.Listbox(root, selectmode='multiple')
listbox.insert('end', *['A', 'B', 'C', 'D'])
listbox.pack()

#   clear selection button
clear_button = tk.Button(root, text='Clear Selection',
                         command=lambda: listbox.selection_clear(0, 'end'))
clear_button.pack()

#   mainloop
root.mainloop()
</code>```

Also, there're some good resources for trivial questions like this:

Tkinter 8.5 reference: a GUI for Python

An Introduction to Tkinter

Graphical User Interfaces with Tk (Python docs)

Body:
There's a selection_clear() method for this purpose.

Try this snippet:

try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk

#   root
root = tk.Tk()

#   listbox
listbox = tk.Listbox(root, selectmode='multiple')
listbox.insert('end', *['A', 'B', 'C', 'D'])
listbox.pack()

#   clear selection button
clear_button = tk.Button(root, text='Clear Selection',
                         command=lambda: listbox.selection_clear(0, 'end'))
clear_button.pack()

#   mainloop
root.mainloop()

Also, there're some good resources for trivial questions like this:

Tkinter 8.5 reference: a GUI for Python

An Introduction to Tkinter

Graphical User Interfaces with Tk (Python docs)


问:
Having multiple versions of Rails installed on OS X
OS X 10.6 has Rails 2.2.2 installed by default.

How to upgrade to Rails 2.3.8?

Since Rails 3 is out, is it possible to have multiple versions of Rails (like 2.3.8 and 3) installed on OS X?

(For example, I could be working on two Rails projects, one is Rails 2.x and the other is Rails 3.x).

答:
Use

```<code>gem install -v=2.3.8 rails
</code>```

where -v=[version number you want to install]

Then

```<code>list gem rails
</code>```

In your config/environment.rb you can state which version of Rails you want to use.

Body:
Use

gem install -v=2.3.8 rails

where -v=[version number you want to install]

Then

list gem rails

In your config/environment.rb you can state which version of Rails you want to use.


问:
How to do quantization in JPEG compression?
I am studying on the JPEG compression algorithm. I followed some simple version instruction to implement it in MatLab and I stuck at the quantization process.

So in JPEG, I use 8x8 blocks as a unit to perform the forward transform then quantize each block based on a quantization matrix (or divide by a number N for simplicity, in the instruction).

I implemented the DCT by myself and it works just like the built-in dct2 so I think there is no problem in my DCT code.

```<code>function transformed_matrix = dctTransform(block, inverse)
m_size = size(block, 1);
A = zeros(m_size);

for i = 0:m_size - 1
    for j = 0:m_size - 1
        if i == 0
            a = sqrt(1 / m_size);
        else
            a = sqrt(2 / m_size);
        end
        A(i + 1, j + 1) = a * cos(pi * (j + 0.5) * i / m_size);
    end
end

if inverse == true
    transformed_matrix = A' * block * A;
else
    transformed_matrix = A * block * A';
end

end
</code>```

Then I start my quantization implementation, I have done a simple version looks like below (Just for grayscale now..):

```<code>function quantized_matrix = quantize(block, quality, inverse, mode)
m_size = size(block, 1);
N = 16;
DEFAULT_QUANTIZATION_MATRIX = ...
    [16 11 10 16 24 40 51 61
     12 12 14 19 26 58 60 55
     14 13 16 24 40 57 69 56
     14 17 22 29 51 87 80 62
     18 22 37 56 68 109 103 77
     24 35 55 64 81 104 113 92
     49 64 78 87 103 121 120 101
     72 92 95 98 112 100 103 99] * quality;

% check for input size and mode
if strcmp(mode, 'default') && m_size == 8
    if inverse == true
        quantized_matrix = block .* DEFAULT_QUANTIZATION_MATRIX;
    else
        quantized_matrix = round(block ./ DEFAULT_QUANTIZATION_MATRIX);
    end
else
    if inverse == true
        quantized_matrix = block * N;
    else
        quantized_matrix = round(block / N);
    end
end

end
</code>```

My main program code is

```<code>I = im2double(imread('../images/lena.bmp'));
block_size = 8;
fun = @(block_struct) quantize(dctTransform(block_struct.data, false), 1, false, 'defualt')
fun2 = @(block_struct) dctTransform(block_struct.data, false)
fun3 = @(block_struct) dct2(block_struct.data)
I2 = blockproc(I, [block_size block_size], fun2);
I3 = blockproc(I, [block_size block_size], fun3);
I4 = blockproc(I, [block_size block_size], fun);
subplot(2,2,1), imshow(I, []), title('The Original Image');
subplot(2,2,2), imshow(I2, []), title('The DCT Image');
subplot(2,2,3), imshow(I3, []), title('The builtin DCT Image');
subplot(2,2,4), imshow(I4, []), title('The Quantized Image');
</code>```

There is no difference between my DCT and the built-in DCT implementation so I think there must be something wrong with my quantization implementation. I have checked the result from the DCT computation, most of the numbers in the matrix are very small, and that is why I finally have a black image (all rounded to 0). Is there any misunderstanding of JPEG compression from my implementation?

Any help is appreciated.

答:
OK, I have figured it out.

The problem is not about the algorithm and my DCT/Quantization implementation.

The problem is I am using im2double to convert my image.
From the MatLab official documentation,

I2 = im2double(I) converts the intensity image I to double precision,
  rescaling the data if necessary.

So after I = im2double(imread('../images/lena.bmp'));
I actually got a scaled image, therefore the pixel values are very small (between 0 and 1).

I just switched to

I = double(imread('../images/lena.bmp'));

Body:
I am studying on the JPEG compression algorithm. I followed some simple version instruction to implement it in MatLab and I stuck at the quantization process.

So in JPEG, I use 8x8 blocks as a unit to perform the forward transform then quantize each block based on a quantization matrix (or divide by a number N for simplicity, in the instruction).

I implemented the DCT by myself and it works just like the built-in dct2 so I think there is no problem in my DCT code.

function transformed_matrix = dctTransform(block, inverse)
m_size = size(block, 1);
A = zeros(m_size);

for i = 0:m_size - 1
    for j = 0:m_size - 1
        if i == 0
            a = sqrt(1 / m_size);
        else
            a = sqrt(2 / m_size);
        end
        A(i + 1, j + 1) = a * cos(pi * (j + 0.5) * i / m_size);
    end
end

if inverse == true
    transformed_matrix = A' * block * A;
else
    transformed_matrix = A * block * A';
end

end

Then I start my quantization implementation, I have done a simple version looks like below (Just for grayscale now..):

function quantized_matrix = quantize(block, quality, inverse, mode)
m_size = size(block, 1);
N = 16;
DEFAULT_QUANTIZATION_MATRIX = ...
    [16 11 10 16 24 40 51 61
     12 12 14 19 26 58 60 55
     14 13 16 24 40 57 69 56
     14 17 22 29 51 87 80 62
     18 22 37 56 68 109 103 77
     24 35 55 64 81 104 113 92
     49 64 78 87 103 121 120 101
     72 92 95 98 112 100 103 99] * quality;

% check for input size and mode
if strcmp(mode, 'default') && m_size == 8
    if inverse == true
        quantized_matrix = block .* DEFAULT_QUANTIZATION_MATRIX;
    else
        quantized_matrix = round(block ./ DEFAULT_QUANTIZATION_MATRIX);
    end
else
    if inverse == true
        quantized_matrix = block * N;
    else
        quantized_matrix = round(block / N);
    end
end

end

My main program code is

I = im2double(imread('../images/lena.bmp'));
block_size = 8;
fun = @(block_struct) quantize(dctTransform(block_struct.data, false), 1, false, 'defualt')
fun2 = @(block_struct) dctTransform(block_struct.data, false)
fun3 = @(block_struct) dct2(block_struct.data)
I2 = blockproc(I, [block_size block_size], fun2);
I3 = blockproc(I, [block_size block_size], fun3);
I4 = blockproc(I, [block_size block_size], fun);
subplot(2,2,1), imshow(I, []), title('The Original Image');
subplot(2,2,2), imshow(I2, []), title('The DCT Image');
subplot(2,2,3), imshow(I3, []), title('The builtin DCT Image');
subplot(2,2,4), imshow(I4, []), title('The Quantized Image');

There is no difference between my DCT and the built-in DCT implementation so I think there must be something wrong with my quantization implementation. I have checked the result from the DCT computation, most of the numbers in the matrix are very small, and that is why I finally have a black image (all rounded to 0). Is there any misunderstanding of JPEG compression from my implementation?

Any help is appreciated.