问:
canvas image gets blurry
https://jsfiddle.net/Abhi_Solanki/9yktct3z/3/ here fiddle link..

what    i am trying to do is to show the same output as the highcharts show    when it is exported in PDF format or SVG format, infact in this code    i have used the same function that is used to generate SVG file of    Highcharts the output of that seems proper to me

 but the problem    arises when i pass that variable into canvg.js file calling canvg at function that time the output of the image gets blurry

 where i want the output    to remain same as it is without pixels getting blurred as it is same    in the highcharts pdf. as i have to display that image of chart in a pdf file so please help. code is as below.

var svgres = chart.getSVG();
var svgArr = [],
   top = 0,
   height = 0,
   width = 0,
   col=0;
   svgCustDim = 400;
   var svgWidth = 600,
   svg = svgres.replace('<svg', '<g transform="translate(' + col * svgWidth + ',' + top  + ')" ');
   svg = svg.replace('</svg>', '</g>');
   svg = '<svg height="' + svgCustDim + '" width="' + svgCustDim*(3)+ '" version="1.1" xmlns="http://www.w3.org/2000/svg">' + svg + '</svg>';
canvg('canvas', svg);
var canvas = document.getElementById('canvas');
return canvas.toDataURL("image/jpeg");```

答:
The version of canvg used in the demo page on github is buggy. If i take the script from here https://github.com/canvg/canvg/blob/master/canvg.js and paste it in the fiddle it works fine.

You can read more about it here https://github.com/canvg/canvg/issues/486.

Also your canvas is a lot bigger than the image, you can take the chart width and height so that the canvas is the same dimension as the chart.

```<code>svgCustDim = chart.chartHeight;
var svgWidth = chart.chartWidth,
svg = svgres.replace('<svg', '<g');
svg = svg.replace('</svg>', '</g>');
svg = '<svg height="' + svgCustDim + '" width="' + svgWidth+ '" version="1.1" xmlns="http://www.w3.org/2000/svg">' + svg + '</svg>';
</code>```

Here is a fiddle with the canvg.js taken from the url above and the changes so that your canvas is the same dimension as your chart https://jsfiddle.net/9yktct3z/6/

Note that it appear that the minified version (canvg.min.js) is

if you want a bigger resolution image remove the height and width from you chart container

```<code><div id="container" style="margin: 0 auto"></div>
</code>```

and set them in the chart option, i used 2000*2000 but you play around with the values

```<code>chart: {
    height: 2000,
    width: 2000,
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie'
},
</code>```

here is the full fiddle https://jsfiddle.net/9yktct3z/10/

Title: canvas image gets blurry

Body:
The version of canvg used in the demo page on github is buggy. If i take the script from here https://github.com/canvg/canvg/blob/master/canvg.js and paste it in the fiddle it works fine.

You can read more about it here https://github.com/canvg/canvg/issues/486.

Also your canvas is a lot bigger than the image, you can take the chart width and height so that the canvas is the same dimension as the chart.

svgCustDim = chart.chartHeight;
var svgWidth = chart.chartWidth,
svg = svgres.replace('<svg', '<g');
svg = svg.replace('</svg>', '</g>');
svg = '<svg height="' + svgCustDim + '" width="' + svgWidth+ '" version="1.1" xmlns="http://www.w3.org/2000/svg">' + svg + '</svg>';

Here is a fiddle with the canvg.js taken from the url above and the changes so that your canvas is the same dimension as your chart https://jsfiddle.net/9yktct3z/6/

Note that it appear that the minified version (canvg.min.js) is

if you want a bigger resolution image remove the height and width from you chart container

<div id="container" style="margin: 0 auto"></div>

and set them in the chart option, i used 2000*2000 but you play around with the values

chart: {
    height: 2000,
    width: 2000,
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie'
},

here is the full fiddle https://jsfiddle.net/9yktct3z/10/


来源: stackexchange

问:
How to backup of deploy rails application from server?
Hi I have a ruby on rails app hosted on AWS EC2 and it is using mysql3 as database.Now I have to take backup of the database to my local machine.</p>

答:
There are two ways to take backup.

Using mysql workbench UI tool connect you database via ssh tunnel.

Connect to the AWS EC2 and take backup there itself and copy the backup file using scp command.

Hope this might help you.

ContentLicense: CC BY-SA 3.0


问:
java.lang.OutOfMemoryError - How do I fix this?
I am trying to implement paging in one activity but I keep running out of memory. The app runs till the 4th page but when it gets to the 5th it crashes. I've tried increasing the JVM heap size but the app still crashes at this one point where it runs out of memory to allocate.

This is my main file:

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

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

    MyPagerAdapter adapter = new MyPagerAdapter();
    ViewPager myPager = (ViewPager) findViewById(R.id.intro_panels);
    myPager.setAdapter(adapter);
    myPager.setCurrentItem(0);
}

Intent intent = new Intent(S1Intro.this,S2CharacterIntro.class);

public void nextScreen(View view){
    startActivity(intent);
}
</code>```

This is the PageAdapter Class:

```<code>public class MyPagerAdapter extends PagerAdapter {

public int getCount() {
    return 5;
}

public Object instantiateItem(View collection, int position) {

    LayoutInflater inflater = (LayoutInflater) collection.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    int resId = 0;
    switch (position) {
        case 0:
            resId = R.layout.s1a;
            break;
        case 1:
            resId = R.layout.s1b;
            break;
        case 2:
            resId = R.layout.s1c;
            break;
        case 3:
            resId = R.layout.s1d;
            break;
        case 4:
            resId = R.layout.s1e;
            break;
    }

    View view = inflater.inflate(resId, null);

    ((ViewPager) collection).addView(view, 0);

    return view;
}

@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
    ((ViewPager) arg0).removeView((View) arg2);

}

@Override
public boolean isViewFromObject(View arg0, Object arg1) {
    return arg0 == ((View) arg1);

}

@Override
public Parcelable saveState() {
    return null;
}
</code>```

}

This is the 1st page's xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/a"/>
</LinearLayout>
</code>```

All the other pages are just like this with different drawables. Except the 5th page, which looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_screen2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.miniproject32.writeup.S1Intro">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/e"/>
<Button
    style="@style/buttonStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button_s1"
    android:text="@string/start"
    android:onClick="nextScreen"/>
</RelativeLayout>
</code>```

This is the logcat:

```<code>03-30 12:17:31.866 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.866 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.896 498-498/? I/art: Alloc sticky concurrent mark sweep GC freed 1003(75KB) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/89MB, paused 885us total 33.721ms
03-30 12:17:31.896 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.906 1139-1139/? D/ResourcesManager: For user 0 new overlays fetched Null
03-30 12:17:31.916 498-498/? I/art: Alloc partial concurrent mark sweep GC freed 71(2848B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 823us total 17.333ms
03-30 12:17:31.916 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.946 498-498/? I/art: Alloc concurrent mark sweep GC freed 115(20KB) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 885us total 24.108ms
03-30 12:17:31.946 498-498/? I/art: Forcing collection of SoftReferences for 36MB allocation
03-30 12:17:31.946 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.946 612-836/? D/ResourcesManager: For user 0 new overlays fetched Null
03-30 12:17:31.966 498-504/? W/art: Suspending all threads took: 19.805ms
03-30 12:17:31.966 498-498/? I/art: Alloc concurrent mark sweep GC freed 11(344B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 1.434ms total 23.834ms
03-30 12:17:31.966 498-498/? W/art: Throwing OutOfMemoryError "Failed to allocate a 38125292 byte allocation with 16777216 free bytes and 21MB until OOM"
03-30 12:17:31.976 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.976 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.976 612-836/? D/ResourcesManager: For user 0 new overlays fetched Null
03-30 12:17:31.986 498-498/? I/art: Alloc sticky concurrent mark sweep GC freed 3(1264B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 915us total 10.620ms
03-30 12:17:31.986 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.986 612-612/? I/IntowowAdapter: not wifi, stop request intowow ad
03-30 12:17:31.996 498-498/? I/art: Alloc partial concurrent mark sweep GC freed 10(320B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 885us total 13.458ms
03-30 12:17:31.996 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:32.026 498-498/? I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 1.068ms total 25.024ms
03-30 12:17:32.026 498-498/? I/art: Forcing collection of SoftReferences for 36MB allocation
03-30 12:17:32.026 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:32.056 498-498/? I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 885us total 24.536ms
03-30 12:17:32.056 498-498/? W/art: Throwing OutOfMemoryError "Failed to allocate a 38125292 byte allocation with 16777216 free bytes and 21MB until OOM"
03-30 12:17:32.056 498-498/? D/skia: --- allocation failed for scaled bitmap
03-30 12:17:32.056 612-612/? I/KBattery: [PLACE] at com.ijinshan.kbatterydoctor.cloud.NewRemoteCloudConfigHelper.b(NewRemoteCloudConfigHelper.java:600)
                                     [NewRemoteCloudConfigHelper]isPackedNotification lastAid = 9
03-30 12:17:32.056 498-498/? E/InputEventReceiver: Exception dispatching input event.
03-30 12:17:32.066 498-498/? E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
03-30 12:17:32.086 612-612/? I/Choreographer: Skipped 81 frames!  The application may be doing too much work on its main thread.
03-30 12:17:32.096 498-498/? E/MessageQueue-JNI: java.lang.OutOfMemoryError: Failed to allocate a 38125292 byte allocation with 16777216 free bytes and 21MB until OOM
                                                 at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                                 at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
                                                 at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:856)
                                                 at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:675)
                                                 at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:2230)
                                                 at android.content.res.Resources.loadDrawableForCookie(Resources.java:4279)
                                                 at android.content.res.Resources.loadDrawable(Resources.java:4153)
                                                 at android.content.res.Resources.loadDrawable(Resources.java:3998)
                                                 at android.content.res.TypedArray.getDrawable(TypedArray.java:886)
                                                 at android.widget.ImageView.<init>(ImageView.java:157)
                                                 at android.widget.ImageView.<init>(ImageView.java:145)
                                                 at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:60)
                                                 at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:56)
                                                 at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1017)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1076)
                                                 at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:758)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
                                                 at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:380)
                                                 at com.miniproject32.writeup.MyPagerAdapter.instantiateItem(MyPagerAdapter.java:40)
                                                 at android.support.v4.view.PagerAdapter.instantiateItem(PagerAdapter.java:111)
                                                 at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1038)
                                                 at android.support.v4.view.ViewPager.populate(ViewPager.java:1252)
                                                 at android.support.v4.view.ViewPager.populate(ViewPager.java:1120)
                                                 at android.support.v4.view.ViewPager$3.run(ViewPager.java:277)
                                                 at android.support.v4.view.ViewPager.completeScroll(ViewPager.java:2029)
                                                 at android.support.v4.view.ViewPager.onInterceptTouchEvent(ViewPager.java:2159)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2371)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2866)
                                                 at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1861)
                                                 at android.app.Activity.dispatchTouchEvent(Activity.java:3061)
                                                 at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
                                                 at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2827)
                                                a
03-30 12:17:32.096 498-498/? D/AndroidRuntime: Shutting down VM
03-30 12:17:32.106 498-498/? E/AndroidRuntime: FATAL EXCEPTION: main
                                           Process: com.miniproject32.writeup, PID: 498
                                           java.lang.OutOfMemoryError: Failed to allocate a 38125292 byte allocation with 16777216 free bytes and 21MB until OOM
                                               at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                               at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
                                               at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:856)
                                               at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:675)
                                               at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:2230)
                                               at android.content.res.Resources.loadDrawableForCookie(Resources.java:4279)
                                               at android.content.res.Resources.loadDrawable(Resources.java:4153)
                                               at android.content.res.Resources.loadDrawable(Resources.java:3998)
                                               at android.content.res.TypedArray.getDrawable(TypedArray.java:886)
                                               at android.widget.ImageView.<init>(ImageView.java:157)
                                               at android.widget.ImageView.<init>(ImageView.java:145)
                                               at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:60)
                                               at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:56)
                                               at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
                                               at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1017)
                                               at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1076)
                                               at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
                                               at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:758)
                                               at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
                                               at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
                                               at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:380)
                                               at com.miniproject32.writeup.MyPagerAdapter.instantiateItem(MyPagerAdapter.java:40)
                                               at android.support.v4.view.PagerAdapter.instantiateItem(PagerAdapter.java:111)
                                               at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1038)
                                               at android.support.v4.view.ViewPager.populate(ViewPager.java:1252)
                                               at android.support.v4.view.ViewPager.populate(ViewPager.java:1120)
                                               at android.support.v4.view.ViewPager$3.run(ViewPager.java:277)
                                               at android.support.v4.view.ViewPager.completeScroll(ViewPager.java:2029)
                                               at android.support.v4.view.ViewPager.onInterceptTouchEvent(ViewPager.java:2159)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2371)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2866)
                                               at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1861)
                                               at android.app.Activity.dispatchTouchEvent(Activity.java:3061)
                                               at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
                                            at com.android.internal.policy.P
</code>```

How do I fix this? Please help

答:
java.lang.OutOfMemoryError: Failed to allocate a 38125292 byte allocation with 16777216 free bytes and 21MB until OOM

You are trying to allocate an image that weighs 38MB. It's too much.

Either you make the source image weigh less, or you have to downsample the image and then load it.

Body:
I am trying to implement paging in one activity but I keep running out of memory. The app runs till the 4th page but when it gets to the 5th it crashes. I've tried increasing the JVM heap size but the app still crashes at this one point where it runs out of memory to allocate.

This is my main file:

public class S1Intro extends AppCompatActivity {

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

    MyPagerAdapter adapter = new MyPagerAdapter();
    ViewPager myPager = (ViewPager) findViewById(R.id.intro_panels);
    myPager.setAdapter(adapter);
    myPager.setCurrentItem(0);
}

Intent intent = new Intent(S1Intro.this,S2CharacterIntro.class);

public void nextScreen(View view){
    startActivity(intent);
}

This is the PageAdapter Class:

public class MyPagerAdapter extends PagerAdapter {

public int getCount() {
    return 5;
}

public Object instantiateItem(View collection, int position) {

    LayoutInflater inflater = (LayoutInflater) collection.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    int resId = 0;
    switch (position) {
        case 0:
            resId = R.layout.s1a;
            break;
        case 1:
            resId = R.layout.s1b;
            break;
        case 2:
            resId = R.layout.s1c;
            break;
        case 3:
            resId = R.layout.s1d;
            break;
        case 4:
            resId = R.layout.s1e;
            break;
    }

    View view = inflater.inflate(resId, null);

    ((ViewPager) collection).addView(view, 0);

    return view;
}

@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
    ((ViewPager) arg0).removeView((View) arg2);

}

@Override
public boolean isViewFromObject(View arg0, Object arg1) {
    return arg0 == ((View) arg1);

}

@Override
public Parcelable saveState() {
    return null;
}

}

This is the 1st page's xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/a"/>
</LinearLayout>

All the other pages are just like this with different drawables. Except the 5th page, which looks like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_screen2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.miniproject32.writeup.S1Intro">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/e"/>
<Button
    style="@style/buttonStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button_s1"
    android:text="@string/start"
    android:onClick="nextScreen"/>
</RelativeLayout>

This is the logcat:

03-30 12:17:31.866 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.866 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.896 498-498/? I/art: Alloc sticky concurrent mark sweep GC freed 1003(75KB) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/89MB, paused 885us total 33.721ms
03-30 12:17:31.896 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.906 1139-1139/? D/ResourcesManager: For user 0 new overlays fetched Null
03-30 12:17:31.916 498-498/? I/art: Alloc partial concurrent mark sweep GC freed 71(2848B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 823us total 17.333ms
03-30 12:17:31.916 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.946 498-498/? I/art: Alloc concurrent mark sweep GC freed 115(20KB) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 885us total 24.108ms
03-30 12:17:31.946 498-498/? I/art: Forcing collection of SoftReferences for 36MB allocation
03-30 12:17:31.946 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.946 612-836/? D/ResourcesManager: For user 0 new overlays fetched Null
03-30 12:17:31.966 498-504/? W/art: Suspending all threads took: 19.805ms
03-30 12:17:31.966 498-498/? I/art: Alloc concurrent mark sweep GC freed 11(344B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 1.434ms total 23.834ms
03-30 12:17:31.966 498-498/? W/art: Throwing OutOfMemoryError "Failed to allocate a 38125292 byte allocation with 16777216 free bytes and 21MB until OOM"
03-30 12:17:31.976 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.976 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.976 612-836/? D/ResourcesManager: For user 0 new overlays fetched Null
03-30 12:17:31.986 498-498/? I/art: Alloc sticky concurrent mark sweep GC freed 3(1264B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 915us total 10.620ms
03-30 12:17:31.986 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:31.986 612-612/? I/IntowowAdapter: not wifi, stop request intowow ad
03-30 12:17:31.996 498-498/? I/art: Alloc partial concurrent mark sweep GC freed 10(320B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 885us total 13.458ms
03-30 12:17:31.996 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:32.026 498-498/? I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 1.068ms total 25.024ms
03-30 12:17:32.026 498-498/? I/art: Forcing collection of SoftReferences for 36MB allocation
03-30 12:17:32.026 498-498/? I/art: Starting a blocking GC Alloc
03-30 12:17:32.056 498-498/? I/art: Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 17% free, 74MB/90MB, paused 885us total 24.536ms
03-30 12:17:32.056 498-498/? W/art: Throwing OutOfMemoryError "Failed to allocate a 38125292 byte allocation with 16777216 free bytes and 21MB until OOM"
03-30 12:17:32.056 498-498/? D/skia: --- allocation failed for scaled bitmap
03-30 12:17:32.056 612-612/? I/KBattery: [PLACE] at com.ijinshan.kbatterydoctor.cloud.NewRemoteCloudConfigHelper.b(NewRemoteCloudConfigHelper.java:600)
                                     [NewRemoteCloudConfigHelper]isPackedNotification lastAid = 9
03-30 12:17:32.056 498-498/? E/InputEventReceiver: Exception dispatching input event.
03-30 12:17:32.066 498-498/? E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
03-30 12:17:32.086 612-612/? I/Choreographer: Skipped 81 frames!  The application may be doing too much work on its main thread.
03-30 12:17:32.096 498-498/? E/MessageQueue-JNI: java.lang.OutOfMemoryError: Failed to allocate a 38125292 byte allocation with 16777216 free bytes and 21MB until OOM
                                                 at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                                 at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
                                                 at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:856)
                                                 at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:675)
                                                 at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:2230)
                                                 at android.content.res.Resources.loadDrawableForCookie(Resources.java:4279)
                                                 at android.content.res.Resources.loadDrawable(Resources.java:4153)
                                                 at android.content.res.Resources.loadDrawable(Resources.java:3998)
                                                 at android.content.res.TypedArray.getDrawable(TypedArray.java:886)
                                                 at android.widget.ImageView.<init>(ImageView.java:157)
                                                 at android.widget.ImageView.<init>(ImageView.java:145)
                                                 at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:60)
                                                 at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:56)
                                                 at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1017)
                                                 at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1076)
                                                 at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:758)
                                                 at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
                                                 at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
                                                 at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
                                                 at android.view.LayoutInflater.inflate(LayoutInflater.java:380)
                                                 at com.miniproject32.writeup.MyPagerAdapter.instantiateItem(MyPagerAdapter.java:40)
                                                 at android.support.v4.view.PagerAdapter.instantiateItem(PagerAdapter.java:111)
                                                 at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1038)
                                                 at android.support.v4.view.ViewPager.populate(ViewPager.java:1252)
                                                 at android.support.v4.view.ViewPager.populate(ViewPager.java:1120)
                                                 at android.support.v4.view.ViewPager$3.run(ViewPager.java:277)
                                                 at android.support.v4.view.ViewPager.completeScroll(ViewPager.java:2029)
                                                 at android.support.v4.view.ViewPager.onInterceptTouchEvent(ViewPager.java:2159)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2371)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                                 at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                                 at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2866)
                                                 at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1861)
                                                 at android.app.Activity.dispatchTouchEvent(Activity.java:3061)
                                                 at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
                                                 at com.android.internal.policy.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2827)
                                                a
03-30 12:17:32.096 498-498/? D/AndroidRuntime: Shutting down VM
03-30 12:17:32.106 498-498/? E/AndroidRuntime: FATAL EXCEPTION: main
                                           Process: com.miniproject32.writeup, PID: 498
                                           java.lang.OutOfMemoryError: Failed to allocate a 38125292 byte allocation with 16777216 free bytes and 21MB until OOM
                                               at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                               at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
                                               at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:856)
                                               at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:675)
                                               at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:2230)
                                               at android.content.res.Resources.loadDrawableForCookie(Resources.java:4279)
                                               at android.content.res.Resources.loadDrawable(Resources.java:4153)
                                               at android.content.res.Resources.loadDrawable(Resources.java:3998)
                                               at android.content.res.TypedArray.getDrawable(TypedArray.java:886)
                                               at android.widget.ImageView.<init>(ImageView.java:157)
                                               at android.widget.ImageView.<init>(ImageView.java:145)
                                               at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:60)
                                               at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:56)
                                               at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
                                               at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1017)
                                               at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1076)
                                               at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
                                               at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:758)
                                               at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
                                               at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
                                               at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
                                               at android.view.LayoutInflater.inflate(LayoutInflater.java:380)
                                               at com.miniproject32.writeup.MyPagerAdapter.instantiateItem(MyPagerAdapter.java:40)
                                               at android.support.v4.view.PagerAdapter.instantiateItem(PagerAdapter.java:111)
                                               at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1038)
                                               at android.support.v4.view.ViewPager.populate(ViewPager.java:1252)
                                               at android.support.v4.view.ViewPager.populate(ViewPager.java:1120)
                                               at android.support.v4.view.ViewPager$3.run(ViewPager.java:277)
                                               at android.support.v4.view.ViewPager.completeScroll(ViewPager.java:2029)
                                               at android.support.v4.view.ViewPager.onInterceptTouchEvent(ViewPager.java:2159)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2371)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2844)
                                               at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2461)
                                               at com.android.internal.policy.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2866)
                                               at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1861)
                                               at android.app.Activity.dispatchTouchEvent(Activity.java:3061)
                                               at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:67)
                                            at com.android.internal.policy.P

How do I fix this? Please help


问:
Given this string input how could I make this given output?
```<code>s = """
ID# VALUE_1 VALUE_2
  1      0.1          300
  2   0.2             400 (11 - this text is part of C in row 2 but needs to be ignored / removed)
  3          0.9          600"""
</code>```

I am wanting to convert the above string into the formatted dictionary below. The spacing and extra text is like that on purpose. The spacing & noted text should be removed / stripped.

```<code>print(my_dict)
{'1': {'VALUE_1': '0.1', 'VALUE_2': '300'}, '2': {'VALUE_1': '0.2', 'VALUE_2': '400'}, '3': {'VALUE_1': '0.9', 'VALUE_2': '600'}}
</code>```

What I've tried so far:

```<code>s = """
ID# VALUE_1 VALUE_2
  1      0.1          300
  2   0.2             400 (11 - this text is part of C in row 2 but needs to be ignored / removed)
  3          0.9          600"""

#Get the columns and assign them to a variable.
columns = s.lstrip().splitlines()[0] #Print the first line of the string

dct = {}

rows = s.lstrip().splitlines()

for data in rows[1:]:
    row = data.split()
    dct[row[0]] = dict(zip(columns[1:], row[1:]))

print(dct)
</code>```

This ends up outputting an ugly unformatted looking dictionary :

```<code>{'1': {'D': '0.1', '#': '300'}, '2': {'D': '0.2', '#': '400', ' ': 'in', 'V': 'row', 'A': '2', 'L': 'but', 'U': 'needs', 'E': 'to', '_': 'be', '1': 'C', '2': 'ignored'}, '3': {'D': '0.9', '#': '600'}}
</code>```

I've been unable to incorporate a way to successfully strip out the spaces and extra chunk of data on row2 with my current loop process.

Body:
s = """
ID# VALUE_1 VALUE_2
  1      0.1          300
  2   0.2             400 (11 - this text is part of C in row 2 but needs to be ignored / removed)
  3          0.9          600"""

I am wanting to convert the above string into the formatted dictionary below. The spacing and extra text is like that on purpose. The spacing & noted text should be removed / stripped.

print(my_dict)
{'1': {'VALUE_1': '0.1', 'VALUE_2': '300'}, '2': {'VALUE_1': '0.2', 'VALUE_2': '400'}, '3': {'VALUE_1': '0.9', 'VALUE_2': '600'}}

What I've tried so far:

s = """
ID# VALUE_1 VALUE_2
  1      0.1          300
  2   0.2             400 (11 - this text is part of C in row 2 but needs to be ignored / removed)
  3          0.9          600"""

#Get the columns and assign them to a variable.
columns = s.lstrip().splitlines()[0] #Print the first line of the string

dct = {}

rows = s.lstrip().splitlines()

for data in rows[1:]:
    row = data.split()
    dct[row[0]] = dict(zip(columns[1:], row[1:]))

print(dct)

This ends up outputting an ugly unformatted looking dictionary :

{'1': {'D': '0.1', '#': '300'}, '2': {'D': '0.2', '#': '400', ' ': 'in', 'V': 'row', 'A': '2', 'L': 'but', 'U': 'needs', 'E': 'to', '_': 'be', '1': 'C', '2': 'ignored'}, '3': {'D': '0.9', '#': '600'}}

I've been unable to incorporate a way to successfully strip out the spaces and extra chunk of data on row2 with my current loop process.

Body:
A regex solution, seems more neat to me:

>>> from pprint import pprint
>>> pprint([{i[0]:{'VALUE_1': i[1], 'VALUE_2': i[2]}}
...     for i in re.findall(r'^\s*(\d+)\s+(\S+)\s+(\d+)', s, re.M)])
[{'1': {'VALUE_1': '0.1', 'VALUE_2': '300'}},
 {'2': {'VALUE_1': '0.2', 'VALUE_2': '400'}},
 {'3': {'VALUE_1': '0.9', 'VALUE_2': '600'}}]

Check how does the regex works here


问:
SELECT and JOIN column not in Group by function
I have to join two different table to get my result.
The table 'Resource' it is simple, while the table 'Dimension.[Code]' contains, among the others, a column with different values (i.e :

Code
 SILO
 GRADE
 OTHER 1
 OTHER2

This is the reason why a join twice that column to get two different columns called GRADE and SILO.

Now, I have a query that selects the maximum value of a grade within the group as follows:

```<code>`SELECT
R.[ID] -- If I inserted that here, it is not working obviously.
       -- This cannot But this is the additional column I need (see later)
 DD_SILO.[Value] DIR ,
 max(R.[GRADE]) GRADE_DIR
 FROM [Resource] R
LEFT JOIN
Dimension DD_SILO ON  R.[ID] = DD_SILO.[ID] AND DD_SILO.[Code] = 'SILO'
   group by DD_SILO.[Value]'
</code>```

What I need is basically to have, beside GRADE AND SILO, also the ID name, which is contained into the [Resource] table.
Please notice that [Resource].ID = [Dimension].ID

I would have solved the problem with ROW_NUMBER () to select the highest within the group, avoiding then then 'group by', but as the query has to be inserted in a bigger one, that would take too much time to run. I am using Microsoft SQL Server 2016.

答:
```<code>SELECT
MAX(R.[ID]) as ID ,
 DD_SILO.[Value] DIR ,
 max(R.[GRADE]) GRADE_DIR
 FROM [Resource] R
LEFT JOIN
Dimension DD_SILO ON  R.[ID] = DD_SILO.[ID] AND DD_SILO.[Code] = 'SILO'
   group by DD_SILO.[Value]
</code>```

Body:
I have to join two different table to get my result.
The table 'Resource' it is simple, while the table 'Dimension.[Code]' contains, among the others, a column with different values (i.e :

Code
 SILO
 GRADE
 OTHER 1
 OTHER2

This is the reason why a join twice that column to get two different columns called GRADE and SILO.

Now, I have a query that selects the maximum value of a grade within the group as follows:

`SELECT
R.[ID] -- If I inserted that here, it is not working obviously.
       -- This cannot But this is the additional column I need (see later)
 DD_SILO.[Value] DIR ,
 max(R.[GRADE]) GRADE_DIR
 FROM [Resource] R
LEFT JOIN
Dimension DD_SILO ON  R.[ID] = DD_SILO.[ID] AND DD_SILO.[Code] = 'SILO'
   group by DD_SILO.[Value]'

What I need is basically to have, beside GRADE AND SILO, also the ID name, which is contained into the [Resource] table.
Please notice that [Resource].ID = [Dimension].ID

I would have solved the problem with ROW_NUMBER () to select the highest within the group, avoiding then then 'group by', but as the query has to be inserted in a bigger one, that would take too much time to run. I am using Microsoft SQL Server 2016.


问:
How do I include a query parameter in a POST request using NelmioApiDocBundle?
I'm using (and new to) Symfony 3 and NelmioApiDocbundle. I want to handle a POST request that has optional query parameters. The url  would be something like:
http://example.com/api/updateusers?token=some_long_value

This is what I've tried for my annotations:

```<code>/**
 * Returns a JSON object.
 *
 * @ApiDoc(
 *  resource=true,
 *  description="Update a user's information.",
 *  requirements={
 *      {
 *          "name"="userid",
 *          "dataType"="string",
 *          "requirement"=".+",
 *          "description"="the user to update"
 *      }
 *  },
 *  parameters={
 *    {"name"="data", "dataType"="text area", "required"=true, "description"="Free form xml data."}
 *  },
 *  filters={
 *    {"name"="token", "dataType"="string", "required"=true, "description"="auth token for current user - user that you're making the request on behalf of."},
 *  },
 * )
 * @Route("api/updateusers")
 * @Method("POST")
 */
</code>```

Requirements, parameters, and filters are all showing up in the POST body in the API sandbox. Is there another definition type that I can use that will show a query parameter in the API sandbox? If I bypass the sandbox and send the request directly to the server, the token shows up properly as a GET value. But I'd like to be able to use the API sandbox for testing and documentation.

答:
Try to add this in your annotations, hope it helps you.</p>

```<code>@QueryParam(name="<your_name>", nullable=[true|false], requirements="\d+", description="<your_decription>")
</code>```

Body:
I'm using (and new to) Symfony 3 and NelmioApiDocbundle. I want to handle a POST request that has optional query parameters. The url  would be something like:
http://example.com/api/updateusers?token=some_long_value

This is what I've tried for my annotations:

/**
 * Returns a JSON object.
 *
 * @ApiDoc(
 *  resource=true,
 *  description="Update a user's information.",
 *  requirements={
 *      {
 *          "name"="userid",
 *          "dataType"="string",
 *          "requirement"=".+",
 *          "description"="the user to update"
 *      }
 *  },
 *  parameters={
 *    {"name"="data", "dataType"="text area", "required"=true, "description"="Free form xml data."}
 *  },
 *  filters={
 *    {"name"="token", "dataType"="string", "required"=true, "description"="auth token for current user - user that you're making the request on behalf of."},
 *  },
 * )
 * @Route("api/updateusers")
 * @Method("POST")
 */

Requirements, parameters, and filters are all showing up in the POST body in the API sandbox. Is there another definition type that I can use that will show a query parameter in the API sandbox? If I bypass the sandbox and send the request directly to the server, the token shows up properly as a GET value. But I'd like to be able to use the API sandbox for testing and documentation.

Body:
Try to add this in your annotations, hope it helps you.

@QueryParam(name="<your_name>", nullable=[true|false], requirements="\d+", description="<your_decription>")


问:
How to get a SQL Alchemy object of distinct items with filter on related objects
I am trying to get a SQL Alchemy query of distinct items below filtering on related objects, the equivalent of the below query:

```<code>SELECT distinct items.item_id, items.item_name
FROM items
INNER JOIN categories as cat on items.category_id = cat.category_id
INNER JOIN stores on cat.store_id = stores.store_id
WHERE store.store_id = 123
</code>```

I have created the models as below with foreign keys included but when I run the query below it does not filter correctly.

```<code>items_query = (db.session.query(Store, Item)
               .filter(Store.store_id == 123)
               ).all()

#SQL Alchemy Models
class Store(db.Model):
    __tablename__ = 'stores'
    store_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    store_name = db.Column(db.String(100), unique=True, nullable=False)

    def __repr__(self):
        return '<Store>'+str(self.store_name)

class Category(db.Model):
    __tablename__ = 'categories'
    category_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    category_name = db.Column(db.String(100), unique=True, nullable=False)
    store_id = db.Column(db.Integer, db.ForeignKey('stores.store_id'))
    store = db.relationship('Store', backref=db.backref('categories', lazy='dynamic'))

    def __repr__(self):
        return '<Category>'+str(self.category_name)

class Item(db.Model):
    __tablename__ = 'items'
    item_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    item_name = db.Column(db.String(150), unique=True, nullable=False)
    category_id = db.Column(db.Integer, db.ForeignKey('categories.category_id'))
    category = db.relationship('Category', backref=db.backref('items', lazy='dynamic'))

    def __repr__(self):
        return '<Item>'+str(self.item_name)
</code>```

Could anyone assist me to form the query better?

答:
With

```<code>(db.session.query(Store, Item)
 .filter(Store.store_id == 123)
 ).all()
</code>```

you'll get an implicit cross join between Store and Item, which is clearly not what you want.

First build the required joins either explicitly using the relationships:

```<code>query = db.session.query(Item.item_id, Item.item_name).\
    join(Item.category).\
    join(Category.store)
</code>```

or the shorthand form:

```<code>query = db.session.query(Item.item_id, Item.item_name).\
    join("category", "store")
</code>```

Then apply your WHERE clause:

```<code>query = query.filter(Store.store_id == 123)
</code>```

And then distinct():

```<code>query = query.distinct()
</code>```

To sum it up:

```<code>query = db.session.query(Item.item_id, Item.item_name).\
    join("category", "store").\
    filter(Store.store_id == 123).\
    distinct().\
    all()
</code>```

Also since you've unique constraint on Item.item_name and the joins should not produce multiple rows per Item because of the direction of the one to many relationships, the distinct() should be unnecessary.

Body:
I am trying to get a SQL Alchemy query of distinct items below filtering on related objects, the equivalent of the below query:

SELECT distinct items.item_id, items.item_name
FROM items
INNER JOIN categories as cat on items.category_id = cat.category_id
INNER JOIN stores on cat.store_id = stores.store_id
WHERE store.store_id = 123

I have created the models as below with foreign keys included but when I run the query below it does not filter correctly.

items_query = (db.session.query(Store, Item)
               .filter(Store.store_id == 123)
               ).all()

#SQL Alchemy Models
class Store(db.Model):
    __tablename__ = 'stores'
    store_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    store_name = db.Column(db.String(100), unique=True, nullable=False)

    def __repr__(self):
        return '<Store>'+str(self.store_name)

class Category(db.Model):
    __tablename__ = 'categories'
    category_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    category_name = db.Column(db.String(100), unique=True, nullable=False)
    store_id = db.Column(db.Integer, db.ForeignKey('stores.store_id'))
    store = db.relationship('Store', backref=db.backref('categories', lazy='dynamic'))

    def __repr__(self):
        return '<Category>'+str(self.category_name)

class Item(db.Model):
    __tablename__ = 'items'
    item_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    item_name = db.Column(db.String(150), unique=True, nullable=False)
    category_id = db.Column(db.Integer, db.ForeignKey('categories.category_id'))
    category = db.relationship('Category', backref=db.backref('items', lazy='dynamic'))

    def __repr__(self):
        return '<Item>'+str(self.item_name)

Could anyone assist me to form the query better?

Body:
With

(db.session.query(Store, Item)
 .filter(Store.store_id == 123)
 ).all()

you'll get an implicit cross join between Store and Item, which is clearly not what you want.

First build the required joins either explicitly using the relationships:

query = db.session.query(Item.item_id, Item.item_name).\
    join(Item.category).\
    join(Category.store)

or the shorthand form:

query = db.session.query(Item.item_id, Item.item_name).\
    join("category", "store")

Then apply your WHERE clause:

query = query.filter(Store.store_id == 123)

And then distinct():

query = query.distinct()

To sum it up:

query = db.session.query(Item.item_id, Item.item_name).\
    join("category", "store").\
    filter(Store.store_id == 123).\
    distinct().\
    all()

Also since you've unique constraint on Item.item_name and the joins should not produce multiple rows per Item because of the direction of the one to many relationships, the distinct() should be unnecessary.


问:
Cannot Connect to Server - A network-related or instance-specific error
I get the following error when trying to connect to SQL Server:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

This error is thrown when I try to configure my database to gridview in Visual Studio 2010. I'm at a loss as to how to debug this error.

How would you debug this error? What steps should I take in order to determine what is really going on here, in addition to the one mentioned in the error message?

答:
You can test the following methods.

a

Check the connection string of the project.

b

Go to services and restart SQLServer Instance.

c

Open 'SQLServer  Configuration Manager'

In the left panel select 'SQLServer Network Configuration' and expanding it

Select 'Protocols for MSSQLServer'

In the right panel dbl click on 'TCP/IP'

In the 'Protocol' tab set the 'Enabled' to 'Yes'

In the 'IP Addresses' tab scroll to down

In the 'IPAll' set 'TCP Port' to 1433

d

Open 'Firewall with advanced security'

In the right tab select 'Inbound Rules'

In the middle tab find the record that 'local Port' is 1433, If you can't found it try to created it with following levels

In the Start menu, click Run, type 'WF.msc', and then click OK

In the left panel click the 'Windows Firewall with Advanced Security'

In the right panel right-click 'Inbound Rules', and then click 'New Rule'

In the Rule Type dialog box, select 'Port', and then click Next

In the Protocol and Ports dialog box, select 'TCP', and select 'Specific Local Ports', and then type the port number 1433, Click Next

In the Action dialog box, select Allow the connection, and then click Next

In the 'Profile' dialog box, checking the Domain, Private and Public, Then click Next

In the 'Name' dialog box, type 'SQL 1433 Port' and for a description write description for own. Then click Finish

Then in the middle tab double click the found item(Instance) or created item of  'SQL 1433 Port' name by you.

Select 'Scope' tab in opened dialog box(SQL Server Properties)

In the Local PC Go to google.com in your Browser and search 'My IP'.

then copy of your 'IP'

Go to the remote server and in the 'SQL Server Properties' dialog box of 'Scope' tab, in the 'Remote IP Address' select the 'These IP Addresses' option and click 'Add' button

In the opened dialog box(IP Address) select 'This IP Address or Subnet' option and paste your 'IP', click OK button.

ContentLicense: CC BY-SA 4.0


问:
How do I use select with date condition?
In sqlserver, how do I compare dates?
For example:

Select * from Users where RegistrationDate >= '1/20/2009'

(RegistrationDate is datetime type)

Thanks

答:
```<code>select sysdate from dual
30-MAR-17

select count(1) from masterdata where to_date(inactive_from_date,'DD-MON-YY'
between '01-JAN-16' to '31-DEC-16'

12998 rows
</code>```

OwnerDisplayName: beytz

LastEditorDisplayName: Milen A. Radev

ContentLicense: CC BY-SA 2.5


问:
Android javax.annotation.processing Package missing
I would like to do some annotation processing based on the example in the following link: http://www.zdnetasia.com/writing-and-processing-custom-annotations-part-3-39362483.htm.

However, I would like to implement this in my Android project, and it seems I cannot use the package with the android platform. Do I need to add an external jar or is there something I'm missing?

Thanks.

答:
I find a method in butterknife. Add this in build.gradle:

```<code>compile files(org.gradle.internal.jvm.Jvm.current().getJre().homeDir.getAbsolutePath()+'/lib/rt.jar')
</code>```

Body:
I find a method in butterknife. Add this in build.gradle:

compile files(org.gradle.internal.jvm.Jvm.current().getJre().homeDir.getAbsolutePath()+'/lib/rt.jar')


问:
using loop to check and remove a className from class name string and add another className to the element which triggers the event
it is fairly simple.

I want to make a current class and put it on a link that is currently active

like this :
Link1

but before that, the JS should get all of element with class="li", loop through it and remove the class=" current" if any.

after looping end, then add class=" current" to the element which triggers the event.

for example if user clicks on link3 then JS should remove the class=" current" on link1 and then add class=" current" on link3

it would look like this :
link3

it looks like I cannot use getElementsByClassName() for event listener. what should I do to make an event listener then?

the HTML

document.addEventListener("DOMContentLoaded",function(){
 var et = document.getElementsByClassName("li");
 for(i=0; i <et.length; i++){
   et[i].addEventListener("click",function(){
    funclink(event);
   });
  };
});

function funclink(event){
 //first get all element with class "li" and remove class " current"
 //then add class " current" to the element which triggers the event
 var slink = document.getElementsByClassName("li");
 for(i =0; i < slink.length; i++){
  slink[i].className = slink[i].className.replace(" current","");
 }
 event.currentTarget.className += " current";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.current {
color : orange;
}</code>```

Home

Call Service

Rental

Sales

```

答:
Array of elements doesn't have to initialized two times.
Using li class is a useless. Modern browsers (IE8+) can use querySelector() (querySelectorAll()) (similiar functionality to the jQuery selector).
When document is ready we get array of links in #navmenu, we add listeners to them.

funclink function removes all classes from links and then sets class "current" to the element, that has triggered that function.

var slink; //prepare global scope var that will be filled with link elems
document.addEventListener("DOMContentLoaded", function() {//wait for document to be loaded
  slink = document.querySelectorAll("#navmenu li");//fill global var with array of link elems
  for (i = 0; i < slink.length; i++) {//add click listener to all link elems
    slink[i].addEventListener("click", function() {
      funclink(event);
    });
  }
});

function funclink(event) {
  for (i = 0; i < slink.length; i++)slink[i].className = ""; //remove all current classes
  event.currentTarget.className = "current"; //add current class to the element that triggered fnc
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>a {
  color: blue;
}

.current,
.current a {
  color: red;
}</code>```

Home

Call Service

Rental

Sales

```

Body:
it is fairly simple.

I want to make a current class and put it on a link that is currently active

like this :
Link1

but before that, the JS should get all of element with class="li", loop through it and remove the class=" current" if any.

after looping end, then add class=" current" to the element which triggers the event.

for example if user clicks on link3 then JS should remove the class=" current" on link1 and then add class=" current" on link3

it would look like this :
link3

it looks like I cannot use getElementsByClassName() for event listener. what should I do to make an event listener then?

the HTML

document.addEventListener("DOMContentLoaded",function(){
 var et = document.getElementsByClassName("li");
 for(i=0; i <et.length; i++){
   et[i].addEventListener("click",function(){
    funclink(event);
   });
  };
});

function funclink(event){
 //first get all element with class "li" and remove class " current"
 //then add class " current" to the element which triggers the event
 var slink = document.getElementsByClassName("li");
 for(i =0; i < slink.length; i++){
  slink[i].className = slink[i].className.replace(" current","");
 }
 event.currentTarget.className += " current";
}

.current {
color : orange;
}

Home

Call Service

Rental

Sales

Body:
Array of elements doesn't have to initialized two times.
Using li class is a useless. Modern browsers (IE8+) can use querySelector() (querySelectorAll()) (similiar functionality to the jQuery selector).
When document is ready we get array of links in #navmenu, we add listeners to them.

funclink function removes all classes from links and then sets class "current" to the element, that has triggered that function.

var slink; //prepare global scope var that will be filled with link elems
document.addEventListener("DOMContentLoaded", function() {//wait for document to be loaded
  slink = document.querySelectorAll("#navmenu li");//fill global var with array of link elems
  for (i = 0; i < slink.length; i++) {//add click listener to all link elems
    slink[i].addEventListener("click", function() {
      funclink(event);
    });
  }
});

function funclink(event) {
  for (i = 0; i < slink.length; i++)slink[i].className = ""; //remove all current classes
  event.currentTarget.className = "current"; //add current class to the element that triggered fnc
}

a {
  color: blue;
}

.current,
.current a {
  color: red;
}

<ul id="navmenu">
  <li class="current"><a href="#?module=home">Home</a></li>
  <li><a href="#?module=service">Call Service</a>
    <li><a class="a-left" href="#?module=rental">Rental</a></li>
    <li><a class="a-left" href="#?module=sales">Sales</a></li>
  </li>
</ul>


问:
autocomplete in vaadin?
I'm new to vaadin.  How do I do autocomplete (actually, more like google suggest) on a huge set of data that cannot be loaded in memory, but instead performing a JPA query on every key event.  Is it possible to capture key events on a textfield or combobox?</p>

答: You could check out Henrik Paul's SuperImmediateTextField, which is a Vaadin add-on that allows you to set the client-to-server post delay in seconds. From that on it's common Java stack to get the flow as smooth as possible. Caching, JPA requests or something else. A couple of second's delay will at least slightly lessen the load to server side.</p>

Title: autocomplete in vaadin?


答:
Try to load image using Glide or Picasso.

For Glide

into Project level build.gradle

```<code>dependencies {
    compile 'com.github.bumptech.glide:glide:3.5.2'
    compile 'com.android.support:support-v4:22.0.0'
}
</code>```

while displaying image,

```<code>Glide.with(context)
    .load("imageURL")
    .into(ivImg);
</code>```

For Piccaso

```<code>dependencies {
    compile 'com.squareup.picasso:picasso:2.5.1'
}
</code>```

while displaying image,

```<code>Picasso.with(context)
    .load(imageURL)
    .into(ivImg);
</code>```

Title: java.lang.OutOfMemoryError - How do I fix this?

Body:
Try to load image using Glide or Picasso.

For Glide

into Project level build.gradle

dependencies {
    compile 'com.github.bumptech.glide:glide:3.5.2'
    compile 'com.android.support:support-v4:22.0.0'
}

while displaying image,

Glide.with(context)
    .load("imageURL")
    .into(ivImg);

For Piccaso

dependencies {
    compile 'com.squareup.picasso:picasso:2.5.1'
}

while displaying image,

Picasso.with(context)
    .load(imageURL)
    .into(ivImg);


问:
connect shopify with carrier service
Sorry for this question, but I have no ideea how I supposed to do this:

I want to create a connection between shopify and one shipping carrier. I saw that shopify has connection with other carriers (FedEx, UPS) but I want to create another with romanian shipping.

My question is: Can somebody help me with a plan, ideeas or suggestive documentation on how to do this?

I mention that I red about this but I didn't understand very much. I need somebody's help who knows how this works.

Thank you a lot.

答: Contact Shopify support and put in a request for your shipping provider. Will get done.</p>

Title: connect shopify with carrier service


问:
Do compiled expression trees leak?
In my understanding, JIT-ed code never gets released from memory while the program is running. Does this mean that repeatedly calling .Compile() on expression trees leaks memory?

The implication of that would be to only compile expression trees in static constructors or cache them in some other way, which may not be as simple. Right?

答:
I tried testing this by continuously generating a expression trees in the background and then collecting all garbage and monitoring used space in the GUI thread.

It would seem memory usage stays steady at around 655000 bytes after a couple of hours. So I'd say it's safe to go wild with expression trees.

If anyone wants my hacky test code, here it is:

```<code>using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading;
using System.Windows.Forms;

namespace Experiments
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // Ensuring that always the same amount of memory is used for point storage.
            bytesUsed = new Queue<long>(1000);
            var points = chart1.Series[0].Points;
            for (var i = 0; i < 1000; ++i)
            {
                bytesUsed.Enqueue(0);
                points.Add(0);
            }

            thread = new Thread(ThreadMethod);
            thread.Start();
            timer1.Interval = 10000;
            timer1.Enabled = true;
            timer1_Tick(null, null);
        }

        private readonly Queue<long> bytesUsed;
        private void timer1_Tick(object sender, EventArgs e)
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            bytesUsed.Dequeue();
            bytesUsed.Enqueue(GC.GetTotalMemory(false));

            var points = chart1.Series[0].Points;
            points.Clear();
            foreach (var value in bytesUsed)
                points.Add(value);
        }

        private Thread thread;
        private volatile bool stopping;
        private void ThreadMethod()
        {
            var random = new Random();

            while (!stopping)
            {
                var constant = Expression.Constant(random.Next(), typeof(int));
                var param = Expression.Parameter(typeof(int));

                var mul = Expression.Multiply(param, constant);
                var add = Expression.Multiply(mul, param);
                var sub = Expression.Subtract(add, constant);

                var lambda = Expression.Lambda<Func<int, int>>(sub, param);
                var compiled = lambda.Compile();
            }
        }

        protected override void Dispose(bool disposing)
        {
            stopping = true;
            if (thread != null && disposing)
                thread.Join();

            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
</code>```

Title: Do compiled expression trees leak?

Body:
I tried testing this by continuously generating a expression trees in the background and then collecting all garbage and monitoring used space in the GUI thread.

It would seem memory usage stays steady at around 655000 bytes after a couple of hours. So I'd say it's safe to go wild with expression trees.

If anyone wants my hacky test code, here it is:

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading;
using System.Windows.Forms;

namespace Experiments
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // Ensuring that always the same amount of memory is used for point storage.
            bytesUsed = new Queue<long>(1000);
            var points = chart1.Series[0].Points;
            for (var i = 0; i < 1000; ++i)
            {
                bytesUsed.Enqueue(0);
                points.Add(0);
            }

            thread = new Thread(ThreadMethod);
            thread.Start();
            timer1.Interval = 10000;
            timer1.Enabled = true;
            timer1_Tick(null, null);
        }

        private readonly Queue<long> bytesUsed;
        private void timer1_Tick(object sender, EventArgs e)
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            bytesUsed.Dequeue();
            bytesUsed.Enqueue(GC.GetTotalMemory(false));

            var points = chart1.Series[0].Points;
            points.Clear();
            foreach (var value in bytesUsed)
                points.Add(value);
        }

        private Thread thread;
        private volatile bool stopping;
        private void ThreadMethod()
        {
            var random = new Random();

            while (!stopping)
            {
                var constant = Expression.Constant(random.Next(), typeof(int));
                var param = Expression.Parameter(typeof(int));

                var mul = Expression.Multiply(param, constant);
                var add = Expression.Multiply(mul, param);
                var sub = Expression.Subtract(add, constant);

                var lambda = Expression.Lambda<Func<int, int>>(sub, param);
                var compiled = lambda.Compile();
            }
        }

        protected override void Dispose(bool disposing)
        {
            stopping = true;
            if (thread != null && disposing)
                thread.Join();

            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}


问:
blueprintjs editable table cell tooltip or popover
Similar to How can i add add tooltips to column headers in blueprint js table?

I would like to be able to add Tooltips or Popovers to EditableCells to display validation error messages inline.

I am yet to find a workable solution.

答: Gees self RTM!!! Never mind me, just noticed the tooltip property lol.</p>


问:
understand and analyse the flink code, specially the scheduling part
I am working on improvement of the resource and tasks scheduling of apache flink, please share any tutorial or any document on the internal architecture of apache flink. Also share proper method of debuging the flink code.

Your help and experience of analyzing the flink code will be appreciated.

答: For how job scheduling works in Flink, I would start looking at https://ci.apache.org/projects/flink/flink-docs-release-1.2/internals/job_scheduling.html. Generally, the last part of the current Flink documentation contains some good information about the internals of Apache Flink.</p>


Title: Sort dates with their values in array object

Body:
Please help me to sort dates in ascending order with their value in JavaScript.

var arr = [{
  "3/10/2017": 52,
  "3/11/2017": 58,
  "3/12/2017": 70,
  "3/13/2017": 76,
  "3/14/2017": 88,
  "3/15/2017": 105,
  "3/16/2017": 113,
  "3/17/2017": 115,
  "3/18/2017": 125,
  "3/19/2017": 136,
  "3/20/2017": 139,
  "3/22/2017": 8,
  "3/23/2017": 13,
  "3/24/2017": 29,
  "3/25/2017": 36,
  "3/26/2017": 38,
  "3/27/2017": 56,
  "3/28/2017": 58,
  "3/29/2017": 68,
  "3/7/2017": 8,
  "3/8/2017": 21,
  "3/9/2017": 35
}]

Body:
Objects can't be sorted in javascript, but you could rewrite your code as follows:

var arr = [
  ["3/10/2017", 52],
  ["3/11/2017", 58],
  ["3/12/2017", 70],
  ["3/13/2017", 76],
  ["3/14/2017", 88],
  ["3/15/2017", 105],
  ["3/16/2017", 113],
  ["3/17/2017", 115],
  ["3/18/2017", 125],
  ["3/19/2017", 136],
  ["3/20/2017", 139],
  ["3/22/2017", 8],
  ["3/23/2017", 13],
  ["3/24/2017", 29],
  ["3/25/2017", 36],
  ["3/26/2017", 38],
  ["3/27/2017", 56],
  ["3/28/2017", 58],
  ["3/29/2017", 68],
  ["3/7/2017", 8],
  ["3/8/2017", 21],
  ["3/9/2017", 35]
]

arr.sort(function(a,b) {
  if (a[1] < b[1]) return -1;
  else if (a[1] > b[1]) return 1;
  return 0;
});


问:
powershell HttpListener http file server
I'm trying to create a basic Powershell script to share files through http, I've copied the code from some samples I've found on internet.
My code is more or less like this:

```<code>$listener = New-Object Net.HttpListener
$listener.Prefixes.Add("http://+:8000/")
$listener.Start()

$response.Headers.Add("Content-Type","text/plain")
$buffer = [Text.Encoding]::UTF8.GetBytes((GC (Join-Path $Pwd ($context.Request).RawUrl)))
$response.ContentLength64 = $buffer.Length
$response.OutputStream.Write($buffer, 0, $buffer.Length)
$response.Close()
$Context.Response.Close()
$listener.Stop()
</code>```

I'm able to get the file, but it's not downloaded into binary, for example when I try to download a Zip file, new/downloaded file is bigger than original. I guess that has been transformed in ascii.
How can I preserve original file format?

I guess that I should replace the following lines, but what are the right ones to allow me get the files in binary format?

```<code>$response.Headers.Add("Content-Type","text/plain")
$buffer = [Text.Encoding]::UTF8.GetBytes((GC (Join-Path $Pwd ($context.Request).RawUrl)))
</code>```

I just one to have a basic http file server to allow me get some 'zip', 'iso' files..

Thanks in advance.

答:
You should not use GC to read file content. GC(Get-Content) is used to read text files with options to specified encoding.

Use FileStream or others that read binary file content.

Body:
I'm trying to create a basic Powershell script to share files through http, I've copied the code from some samples I've found on internet.
My code is more or less like this:

$listener = New-Object Net.HttpListener
$listener.Prefixes.Add("http://+:8000/")
$listener.Start()

$response.Headers.Add("Content-Type","text/plain")
$buffer = [Text.Encoding]::UTF8.GetBytes((GC (Join-Path $Pwd ($context.Request).RawUrl)))
$response.ContentLength64 = $buffer.Length
$response.OutputStream.Write($buffer, 0, $buffer.Length)
$response.Close()
$Context.Response.Close()
$listener.Stop()

I'm able to get the file, but it's not downloaded into binary, for example when I try to download a Zip file, new/downloaded file is bigger than original. I guess that has been transformed in ascii.
How can I preserve original file format?

I guess that I should replace the following lines, but what are the right ones to allow me get the files in binary format?

$response.Headers.Add("Content-Type","text/plain")
$buffer = [Text.Encoding]::UTF8.GetBytes((GC (Join-Path $Pwd ($context.Request).RawUrl)))

I just one to have a basic http file server to allow me get some 'zip', 'iso' files..

Thanks in advance.


问:
Best Way to load Static Data in Apache Spark
I have a spark project that makes use of some static metadata about states/regions.  Currently the data is hardcoded like so:

```<code>object RegionUtil {
   val regionNames = Map("US-AL" -> "ALABAMA",
                  "US-AK" -> "ALASKA",
                  "US-AZ" -> "ARIZONA",
                  "US-AR" -> "ARKANSAS",
                  "US-CA" -> "CALIFORNIA",
                  "US-CO" -> "COLORADO",
                  // ... etc
                  "US-WY" -> "WYOMING")
 }
</code>```

And then region mappings are simply looked up from the map in RegionUtil.  This is just an example as there are a number of similar static mappings the application relies on.

But some of this metadata is occasionally (rarely) updated, and is already maintained in a MySQL database.  What I would like to do is initially load that data when spark starts up, and then look up a cached copy of that data from that point forward (ideally with each slave node maintaining its own copy) whenever metadata needs to be accessed.

Does anyone know how that can be accomplished?

答:
If you create /update the structure without using spark (e.g. using Slick or JDBC directly or whatever) before you write the spark specific code and the value holding the data will be in scope and used in the spark code, spark will serialize and broadcast it for you.

If you need these to be updated during the spark job run then you need to use broadcast

Body:
I have a spark project that makes use of some static metadata about states/regions.  Currently the data is hardcoded like so:

object RegionUtil {
   val regionNames = Map("US-AL" -> "ALABAMA",
                  "US-AK" -> "ALASKA",
                  "US-AZ" -> "ARIZONA",
                  "US-AR" -> "ARKANSAS",
                  "US-CA" -> "CALIFORNIA",
                  "US-CO" -> "COLORADO",
                  // ... etc
                  "US-WY" -> "WYOMING")
 }

And then region mappings are simply looked up from the map in RegionUtil.  This is just an example as there are a number of similar static mappings the application relies on.

But some of this metadata is occasionally (rarely) updated, and is already maintained in a MySQL database.  What I would like to do is initially load that data when spark starts up, and then look up a cached copy of that data from that point forward (ideally with each slave node maintaining its own copy) whenever metadata needs to be accessed.

Does anyone know how that can be accomplished?


问:
Upload more than 50 Videos using YouTube API
I have a new channel with no videos uploaded yet. When I tried uploading some 500 videos I had using the YouTube Data API, the upload process stopped after about 50 videos. I do not understand how my quota limit reached 300,000 (the per 100 second default limit) as the quota required for uploading 1 video is just 1600. I have to upload around 500-600 videos every day as the nature of my business is such. Please help.</p>

答:
```<code>[RequestError] Server response: {
 "error": {
  "errors": [
   {
    "domain": "youtube.video",
    "reason": "uploadLimitExceeded",
    "message": "The user has exceeded the number of videos they may upload."
   }
  ],
  "code": 400,
  "message": "The user has exceeded the number of videos they may upload."
 }
}
</code>```

This is a user based quota and not a project based quota. It has nothing to do with what you are seeing on the Google Developer console.

The quota used to be:

400 video uploads, 1500 write operations, and 50,000 read operations that each retrieve two resource parts.

Google has apparently changed how the quota works.  A user can upload 50 videos then only one video every 15 minutes until the quota resets.   Quota resets at midnight west cost USA time.

I have an email out to the team looking for feed back on this.

Body:
[RequestError] Server response: {
 "error": {
  "errors": [
   {
    "domain": "youtube.video",
    "reason": "uploadLimitExceeded",
    "message": "The user has exceeded the number of videos they may upload."
   }
  ],
  "code": 400,
  "message": "The user has exceeded the number of videos they may upload."
 }
}

This is a user based quota and not a project based quota. It has nothing to do with what you are seeing on the Google Developer console.

The quota used to be:

400 video uploads, 1500 write operations, and 50,000 read operations that each retrieve two resource parts.

Google has apparently changed how the quota works.  A user can upload 50 videos then only one video every 15 minutes until the quota resets.   Quota resets at midnight west cost USA time.

I have an email out to the team looking for feed back on this.


问:
Is there some kind of tool to look at the encoding of Intel x86 instructions?
Forgive me if this might be a dumb question but, I'm in an assembly class that was mostly taught using an emulated CPU that was supposed to teach the concepts of assembly code. We haven't even written an Intel program, so I'm trying to adjust. In our emulated CPU, we were able to generate a symbol table file that gave the bytes equivalent for instructions:

http://imgur.com/tw5S8.png

Would I be able to do such a thing with Intel x86 instructions?

答: There is a demo program shipped with fasm.dll which has an editor and hex-viewer:


问:
How to tell sympy to keep exact numbers as exact in integrate?
When I typed

```<code>>python
> from sympy import *
> x=symbols('x')
> integrate(1/4/sin(1/3*x),x)
</code>```

The output was

```<code>0.375*log(cos(0.333333333333333*x) - 1) - 0.375*log(cos(0.333333333333333*x) + 1)
</code>```

What should one do to tell sympy not to convert exact input to floating point? I know I could type the following instead

```<code>integrate(S('1/4')/sin(S('1/3')*x),x)
</code>```

And now the result is

```<code> 3*log(cos(x/3) - 1)/8 - 3*log(cos(x/3) + 1)/8
</code>```

But I'd like to get this result, without having to wrap each number with S('') as in the above.

Is there an option or module one needs to import for this?

Using

```<code>>conda list sympy
sympy                     1.0                      py36_0
</code>```

On linux.

答:
One option is to use isympy -i as your interpreter. This will start an interactive SymPy session where integers are automatically wrapped using S, so that you don't need to worry about dividing integers. But note that this only works interactively. If you want to write code using SymPy in a file, it is recommend to wrap divided integers with S or use Rational.

By the way, you can usually avoid this issue by writing your expression in such a way that you don't have integer/integer. For instance, instead of 1/4/sin(1/3*x) you could write 1/(4*sin(x/3)) (or 1/sin(x/3)/4). You only really need to use S when you have a rational number by itself, like S(1)/2 + x.

Body:
When I typed

>python
> from sympy import *
> x=symbols('x')
> integrate(1/4/sin(1/3*x),x)

The output was

0.375*log(cos(0.333333333333333*x) - 1) - 0.375*log(cos(0.333333333333333*x) + 1)

What should one do to tell sympy not to convert exact input to floating point? I know I could type the following instead

integrate(S('1/4')/sin(S('1/3')*x),x)

And now the result is

 3*log(cos(x/3) - 1)/8 - 3*log(cos(x/3) + 1)/8

But I'd like to get this result, without having to wrap each number with S('') as in the above.

Is there an option or module one needs to import for this?

Using

>conda list sympy
sympy                     1.0                      py36_0

On linux.


问:
CSS: keep image aspect ratio as viewport width decreases
At this page, there are 3 "doorway" graphics:

```<code><div class="textwidget">
    <div class="one-third first">
        <div id="doorway1" class="doorway">
            <h3>The Best Core Exercise Ever</h3>
            <div class="doorway-action">
                <a href="http://vmpersonal.com/product/core-strength-level-1/"><img src="http://vmpersonal.com/wp-content/themes/vmpersonal/images/doorway-action.png" alt="Watch Video Now" title="Watch Video Now" /> Watch Video Now</a>
            </div>
        </div>
    </div>
    <div class="one-third">
        <div id="doorway2" class="doorway">
            <h3>Core Strength Level 1 Program</h3>
            <div class="doorway-action">
                <a href="http://vmpersonal.com/product/core-strength-level-1/"><img src="http://vmpersonal.com/wp-content/themes/vmpersonal/images/doorway-action.png" alt="Watch Video Now" title="Watch Video Now" /> Watch Video Now</a>
            </div>
        </div>
    </div>
    <div class="one-third">
        <div id="doorway3" class="doorway">
            <h3>Cardio Program</h3>
            <div class="doorway-action">
                <a href="http://vmpersonal.com/product/cardio-fitness-level-1/"><img src="http://vmpersonal.com/wp-content/themes/vmpersonal/images/doorway-action.png" alt="Watch Video Now" title="Watch Video Now" /> Watch Video Now</a>
            </div>
        </div>
    </div>
</div>
</code>```

I'd like to make the graphics and the divs that contain them responsive.

They are contained in div.one-third containers.

The images are 409px x 292px, meaning the height is 71.39364303% of the width.

I thought if I used CSS:

```<code>#doorway1 {background-image: url('images/doorway1.png'); height: 71.39364303%;}
#doorway2 {background-image: url('images/doorway2.png'); height: 71.39364303%;}
#doorway3 {background-image: url('images/doorway3.png'); height: 71.39364303%;}
</code>```

they would scale down with the div.one-third as the viewport decreased in width, but they don't, the images are cut off.

How can I keep the images aspect ration consistent as the viewport width decreases?

Help appreciated.

Update: AJ Funk has helped me make the background images scale down, but how do I make the divs that contain them scale down proportionally too?

答:
You have two choices :

This working for responsive (You keep the full image, no crop) :

```<code>img {
    max-width: 100%;
    height: auto;
}
</code>```

This working for backgroud image (The image will crop) :

```<code>div { background-size: contain; }
</code>```

Else you can have a look to some jquery plugins that auto resize an html element depending the window height/width.

Body:
At this page, there are 3 "doorway" graphics:

The Best Core Exercise Ever

                 Watch Video Now

Core Strength Level 1 Program

                 Watch Video Now

Cardio Program

                 Watch Video Now

I'd like to make the graphics and the divs that contain them responsive.

They are contained in div.one-third containers.

The images are 409px x 292px, meaning the height is 71.39364303% of the width.

I thought if I used CSS:

#doorway1 {background-image: url('images/doorway1.png'); height: 71.39364303%;}
#doorway2 {background-image: url('images/doorway2.png'); height: 71.39364303%;}
#doorway3 {background-image: url('images/doorway3.png'); height: 71.39364303%;}

they would scale down with the div.one-third as the viewport decreased in width, but they don't, the images are cut off.

How can I keep the images aspect ration consistent as the viewport width decreases?

Help appreciated.

Update: AJ Funk has helped me make the background images scale down, but how do I make the divs that contain them scale down proportionally too?

Body:
You have two choices :

This working for responsive (You keep the full image, no crop) :

img {
    max-width: 100%;
    height: auto;
}

This working for backgroud image (The image will crop) :

div { background-size: contain; }

Else you can have a look to some jquery plugins that auto resize an html element depending the window height/width.


答:
As commented before, you will have to loop over elements to add eventListener. document.getElementsByClassName  will return a NodeList.

Also, if you are only calling your function with event param, you can just pass function ref instead.

Also, instead again fetching all lis, just fetch those lis that has class current. This will reduce number of iterations.

You should use classList instead of className. It has many helpful methods like add, remove and toggle.

Edit 1

As you need to retain the selected li even after refresh, you will have to use client storage or query param to tell your JS about the selected element.

For security reasons, SO does not provide access to localStorage, so you will have to copy code and debug on local files.

document.addEventListener("DOMContentLoaded", function() {
  var lis = document.getElementsByClassName("li")
  for (var i = 0; i < lis.length; i++) {
    lis[i].addEventListener("click", funclink.bind(lis[i], i));
  }

  initializeUI();
});

function funclink(index, event) {
  var lis = document.querySelectorAll('.li.current');
  for(var i = 0; i< lis.length; i++){
    lis[i].classList.remove('current');
  }
  this.classList.add('current');
  setIndex(index)
}

function initializeUI(){
  var lis = document.querySelectorAll('.li');
  var index = parseInt(locatStorage.getItem('liIndex'));
  lis[index || 0].classList.add("current");
}

function setIndex(index){
  localStorage.setItem("liIndex", index);
}

function blockAnchors(){
  var as = document.querySelectorAll('a');
  for(var i = 0; i< as.length; i++){
    as[i].onclick = function(){
      return false
    }
  }
}
blockAnchors();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.current{
  background: #ddd;
}</code>```

Home

Call Service

Rental

Sales

```

Note: I have added a blockAnchors to stop navigation on a's click.  This is just for demonstration.

Title: using loop to check and remove a className from class name string and add another className to the element which triggers the event

Body:
As commented before, you will have to loop over elements to add eventListener. document.getElementsByClassName  will return a NodeList.

Also, if you are only calling your function with event param, you can just pass function ref instead.

Also, instead again fetching all lis, just fetch those lis that has class current. This will reduce number of iterations.

You should use classList instead of className. It has many helpful methods like add, remove and toggle.

Edit 1

As you need to retain the selected li even after refresh, you will have to use client storage or query param to tell your JS about the selected element.

For security reasons, SO does not provide access to localStorage, so you will have to copy code and debug on local files.

document.addEventListener("DOMContentLoaded", function() {
  var lis = document.getElementsByClassName("li")
  for (var i = 0; i < lis.length; i++) {
    lis[i].addEventListener("click", funclink.bind(lis[i], i));
  }

  initializeUI();
});

function funclink(index, event) {
  var lis = document.querySelectorAll('.li.current');
  for(var i = 0; i< lis.length; i++){
    lis[i].classList.remove('current');
  }
  this.classList.add('current');
  setIndex(index)
}

function initializeUI(){
  var lis = document.querySelectorAll('.li');
  var index = parseInt(locatStorage.getItem('liIndex'));
  lis[index || 0].classList.add("current");
}

function setIndex(index){
  localStorage.setItem("liIndex", index);
}

function blockAnchors(){
  var as = document.querySelectorAll('a');
  for(var i = 0; i< as.length; i++){
    as[i].onclick = function(){
      return false
    }
  }
}
blockAnchors();

.current{
  background: #ddd;
}

<ul id="navmenu">
  <li class="li"><a href="?module=home">Home</a></li>
  <li class="li"><a href="?module=service">Call Service</a>
    <li class="li"><a class="a-left" href="?module=rental">Rental</a></li>
    <li class="li"><a class="a-left" href="?module=sales">Sales</a></li>

  </li>
</ul>

Note: I have added a blockAnchors to stop navigation on a's click.  This is just for demonstration.