问:
tag-it autocomplete - codeigniter
so I would like to ask why is it that my autocomplete function is not working, I want to get data from my database which is inside my controller and it's not giving me results. here are the codes.

JS

```<code>$(document).on('show.bs.modal', '#searchmusic', function() {
$('#searchtags').tagit({
    allowSpaces: true,
    placeholderText: 'Search Tags',
    autocomplete: ({
        source: function(request, response) {
            $.ajax({
                url: base_url + '/songtags/search_tags',
                type: "GET",
                success: function(data) {
                    var songtagdata = JSON.parse(data);
                    response($.map(songtagdata, function(key, value) {
                        return {
                            label: value.tag_name,
                            value: value.tag_name
                        }
                        console.log(songtagdata);
                    }));
                },
                error: function(request, status, error) {
                    alert(error);
                }
            })
        },
        minLength: 2
    })
});
});
</code>```

Controller

```<code>    public function search_tags(){
    $song_tags = $this->song_tags_model->get_tags();
    $encode = json_encode($song_tags);
    echo $encode;
    }
</code>```

答:
You could try the following code example that just sets data to a fixed object:

$(document).ready(function () {
    $("#suggest").autocomplete({
        delay: 100,
        source: function (request, response) {
            Promise.resolve(
                [1,2,3,4,5,6]
            )
            .then(function(data){
                console.log(
                  "got data:"
                  ,JSON.stringify(
                    data,
                    undefined,
                    2
                  )
                )
                response(data);
            });
        }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/jquery-ui-git.js"></script>
<input type="text" placeholder="type something ..." id="suggest" /></code>```

If that works but the ajax version doesn't then the problem is with the request or format of the request so you'll need to update your answer with the output of the console.

You did not understand the example, here is the example applied to your code, it does not use AJAX but just sets the values according to what you are expecting your ajax to be:

```<code>$(document).ready(function () {
    $("#suggest").autocomplete({
        delay: 100,
        source: function (request, response) {
            Promise.resolve(
                `[{"tag_name":"helo"},{"tag_name":"world"}]`
            )
            .then(function(data){
                console.log(
                  "got data:"
                  ,data
                )
                response(
                  JSON.parse(data)
                  .map(
                    item => ({
                      label:item.tag_name
                      ,value:item.tag_name
                    })
                  )
                );
            });
        }
    });
});
</code>```

The working example can be found here. If it does not work in your page then maybe it's a css problem, if it does work then your problem is likely a xhr problem or the format of the response is not what you expected.

Title: tag-it autocomplete - codeigniter

Body:
so I would like to ask why is it that my autocomplete function is not working, I want to get data from my database which is inside my controller and it's not giving me results. here are the codes.

JS

$(document).on('show.bs.modal', '#searchmusic', function() {
$('#searchtags').tagit({
    allowSpaces: true,
    placeholderText: 'Search Tags',
    autocomplete: ({
        source: function(request, response) {
            $.ajax({
                url: base_url + '/songtags/search_tags',
                type: "GET",
                success: function(data) {
                    var songtagdata = JSON.parse(data);
                    response($.map(songtagdata, function(key, value) {
                        return {
                            label: value.tag_name,
                            value: value.tag_name
                        }
                        console.log(songtagdata);
                    }));
                },
                error: function(request, status, error) {
                    alert(error);
                }
            })
        },
        minLength: 2
    })
});
});

Controller

    public function search_tags(){
    $song_tags = $this->song_tags_model->get_tags();
    $encode = json_encode($song_tags);
    echo $encode;
    }

Body:
You could try the following code example that just sets data to a fixed object:

$(document).ready(function () {
    $("#suggest").autocomplete({
        delay: 100,
        source: function (request, response) {
            Promise.resolve(
                [1,2,3,4,5,6]
            )
            .then(function(data){
                console.log(
                  "got data:"
                  ,JSON.stringify(
                    data,
                    undefined,
                    2
                  )
                )
                response(data);
            });
        }
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/jquery-ui-git.js"></script>
<input type="text" placeholder="type something ..." id="suggest" />

If that works but the ajax version doesn't then the problem is with the request or format of the request so you'll need to update your answer with the output of the console.

You did not understand the example, here is the example applied to your code, it does not use AJAX but just sets the values according to what you are expecting your ajax to be:

$(document).ready(function () {
    $("#suggest").autocomplete({
        delay: 100,
        source: function (request, response) {
            Promise.resolve(
                `[{"tag_name":"helo"},{"tag_name":"world"}]`
            )
            .then(function(data){
                console.log(
                  "got data:"
                  ,data
                )
                response(
                  JSON.parse(data)
                  .map(
                    item => ({
                      label:item.tag_name
                      ,value:item.tag_name
                    })
                  )
                );
            });
        }
    });
});

The working example can be found here. If it does not work in your page then maybe it's a css problem, if it does work then your problem is likely a xhr problem or the format of the response is not what you expected.


来源: stackexchange

问:
bitmap size exceeds VM budget
I've read many of the posts regarding this issue and I can't find one that would apply to my code (or at least that I can make the relation to).

I have a homescreen widget that displays in both landscape and portrait.  If I continuously change the orientation of the device I get this in my logcat:

03-08 10:41:35.793: ERROR/dalvikvm-heap(1159): 4707316-byte external allocation too large for this process.

  03-08 10:41:35.793: ERROR/GraphicsJNI(1159): VM won't let us allocate 4707316 bytes

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159): updateAppWidget couldn't find any view, using error view

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159): android.view.InflateException: Binary XML file line #1: Error inflating class android.widget.LinearLayout

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.view.LayoutInflater.createView(LayoutInflater.java:513)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.view.LayoutInflater.inflate(LayoutInflater.java:385)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.widget.RemoteViews.apply(RemoteViews.java:930)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.appwidget.AppWidgetHostView.updateAppWidget(AppWidgetHostView.java:219)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.appwidget.AppWidgetHostView.updateAppWidget(AppWidgetHostView.java:155)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.appwidget.AppWidgetHost.createView(AppWidgetHost.java:218)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at com.android.launcher2.Launcher.bindAppWidget(Launcher.java:2393)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at com.android.launcher2.LauncherModel$Loader$LoaderThread$7.run(LauncherModel.java:1051)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at com.android.launcher2.DeferredHandler$Impl.handleMessage(DeferredHandler.java:48)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.os.Handler.dispatchMessage(Handler.java:99)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.os.Looper.loop(Looper.java:123)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.app.ActivityThread.main(ActivityThread.java:4645)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at java.lang.reflect.Method.invokeNative(Native Method)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at java.lang.reflect.Method.invoke(Method.java:521)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at dalvik.system.NativeStart.main(Native Method)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159): Caused by: java.lang.reflect.InvocationTargetException

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.widget.LinearLayout.(LinearLayout.java:115)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at java.lang.reflect.Constructor.constructNative(Native Method)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at java.lang.reflect.Constructor.newInstance(Constructor.java:446)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.view.LayoutInflater.createView(LayoutInflater.java:500)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     ... 19 more

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159): Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.graphics.Bitmap.nativeCreate(Native Method)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.graphics.Bitmap.createBitmap(Bitmap.java:468)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.graphics.Bitmap.createBitmap(Bitmap.java:435)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:340)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.graphics.BitmapFactory.finishDecode(BitmapFactory.java:488)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:462)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:323)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:697)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.content.res.Resources.loadDrawable(Resources.java:1718)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.content.res.TypedArray.getDrawable(TypedArray.java:601)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.view.View.(View.java:1885)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.view.View.(View.java:1834)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.view.ViewGroup.(ViewGroup.java:285)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     ... 23 more

My code is this which utilizes remoteViews:

```<code>    public class WidgetLayoutBuilder {

 public static final String DEG = "\u00B0";

 public static final int LAYOUT_CURRENT  = 1000;
 public static final int LAYOUT_FORECAST = 1001;

 /**
  * Constructs current conditions layout.
  *
  * @param context
  * @param wd
  * @return
  */
 public static RemoteViews buildCurrentLayout(Context context, int appWidgetId, ACCUWX_WeatherData wd){
  Log.d("########", "remoteViews buildCurrentLayout");
  // Return object
  RemoteViews toRet = new RemoteViews(context.getPackageName(), R.layout.widget_current_layout);

  String cityText = wd.getCityName();
  String tempUnits = wd.getMetric() == 0 ? "F" : "C";
  String iconId   = "icon_" + wd.getCurrentIconCode();

  // Populate views with weather data
  toRet.setTextViewText  (R.id.current_location_text,  cityText);
  toRet.setTextViewText  (R.id.current_temp_text,   wd.getCurrentTemperature() + DEG + tempUnits);
  toRet.setTextViewText  (R.id.current_conditions_text, wd.getCurrentConditions());
  toRet.setImageViewResource (R.id.current_condition_image,  ACCUWX.getDrawableId(iconId));
  toRet.setTextViewText  (R.id.current_hi_temp,    context.getString(R.string.hi) + ": " + wd.getForecast().get(0).getDailyHigh() + DEG);
  toRet.setTextViewText  (R.id.current_lo_temp,    context.getString(R.string.lo) +": " + wd.getForecast().get(0).getDailyLow() + DEG);

  // Make alert icon visible if necessary.
  int visibility = wd.getAlertIsActive() == 0 ? View.INVISIBLE : View.VISIBLE;
  toRet.setViewVisibility(R.id.alert_icon, visibility);

  if (MainActivity.mLocations == null)
   MainActivity.mLocations = new ArrayList<String>();
  if (MainActivity.mLocName == null)
   MainActivity.mLocName = new String("");

  if (!MainActivity.mLocations.contains(wd.getZipCode()) || !MainActivity.mLocName.contains(wd.getCityName()))
   MainActivity.mLocations.add(wd.getZipCode());

  MainActivity.isFromLocationSearchActivity = false;

  // Launch SimpleWeather application intent
  Intent intentAppLaunch = new Intent(context, MainActivity.class);
  intentAppLaunch.putExtra(ACCUWX.Extras.LOCATION_CODE, wd.getZipCode());
  intentAppLaunch.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
  PendingIntent pendingAppLaunch = PendingIntent.getActivity(context, appWidgetId, intentAppLaunch, PendingIntent.FLAG_CANCEL_CURRENT);
  toRet.setOnClickPendingIntent(R.id.current_layout, pendingAppLaunch);

  return toRet;
 }

 /**
  * Returns pretty names for display purposes in the form 'city name, state name' for the US and 'cityname, countryname (region)' for other countries.
  * @return
  */
 public static String getPrettyName(ACCUWX_WeatherData wd){
         String prettyName = "null";

         String state = wd.getStateName();
         String city = wd.getCityName();
         String country = wd.getCountryName();
         String countryCode = wd.getCountryCode();

         if (countryCode.equalsIgnoreCase("us"))
          prettyName = city + ", " + state;
         else
          prettyName = city + ", " + country + " (" + state + ")";

         return prettyName;
 }

 /**
  * Constructs deleted layout.
  *
  * @param context
  * @return
  */
 public static RemoteViews buildDeletedLayout(Context context){
  Log.d("########", "remoteViews buildDeletedLayout");
  return new RemoteViews(context.getPackageName(), R.layout.widget_deleted_layout);

 }

}
</code>```

Could the bitmap error be coming from the device itself and not an issue of my application?

Any help or direction is greatly appreciated!

答:
This line:

```<code>ACCUWX.getDrawableId(iconId)
</code>```

Make sure your drawable is not larger than it needs to be. When you load a Bitmap, you can load the boundaries first, then scale it, and load the scaled down version.

On Orientation change:

Recycle the old Bitmap

Only load the scaled version

ContentLicense: CC BY-SA 3.0

Title: bitmap size exceeds VM budget

Body:
I've read many of the posts regarding this issue and I can't find one that would apply to my code (or at least that I can make the relation to).

I have a homescreen widget that displays in both landscape and portrait.  If I continuously change the orientation of the device I get this in my logcat:

03-08 10:41:35.793: ERROR/dalvikvm-heap(1159): 4707316-byte external allocation too large for this process.

  03-08 10:41:35.793: ERROR/GraphicsJNI(1159): VM won't let us allocate 4707316 bytes

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159): updateAppWidget couldn't find any view, using error view

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159): android.view.InflateException: Binary XML file line #1: Error inflating class android.widget.LinearLayout

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.view.LayoutInflater.createView(LayoutInflater.java:513)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.view.LayoutInflater.inflate(LayoutInflater.java:385)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.widget.RemoteViews.apply(RemoteViews.java:930)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.appwidget.AppWidgetHostView.updateAppWidget(AppWidgetHostView.java:219)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.appwidget.AppWidgetHostView.updateAppWidget(AppWidgetHostView.java:155)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.appwidget.AppWidgetHost.createView(AppWidgetHost.java:218)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at com.android.launcher2.Launcher.bindAppWidget(Launcher.java:2393)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at com.android.launcher2.LauncherModel$Loader$LoaderThread$7.run(LauncherModel.java:1051)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at com.android.launcher2.DeferredHandler$Impl.handleMessage(DeferredHandler.java:48)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.os.Handler.dispatchMessage(Handler.java:99)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.os.Looper.loop(Looper.java:123)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.app.ActivityThread.main(ActivityThread.java:4645)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at java.lang.reflect.Method.invokeNative(Native Method)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at java.lang.reflect.Method.invoke(Method.java:521)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at dalvik.system.NativeStart.main(Native Method)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159): Caused by: java.lang.reflect.InvocationTargetException

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.widget.LinearLayout.(LinearLayout.java:115)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at java.lang.reflect.Constructor.constructNative(Native Method)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at java.lang.reflect.Constructor.newInstance(Constructor.java:446)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.view.LayoutInflater.createView(LayoutInflater.java:500)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     ... 19 more

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159): Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.graphics.Bitmap.nativeCreate(Native Method)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.graphics.Bitmap.createBitmap(Bitmap.java:468)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.graphics.Bitmap.createBitmap(Bitmap.java:435)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:340)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.graphics.BitmapFactory.finishDecode(BitmapFactory.java:488)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:462)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:323)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:697)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.content.res.Resources.loadDrawable(Resources.java:1718)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.content.res.TypedArray.getDrawable(TypedArray.java:601)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.view.View.(View.java:1885)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.view.View.(View.java:1834)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     at android.view.ViewGroup.(ViewGroup.java:285)

  03-08 10:41:35.793: WARN/AppWidgetHostView(1159):     ... 23 more

My code is this which utilizes remoteViews:

    public class WidgetLayoutBuilder {

 public static final String DEG = "\u00B0";

 public static final int LAYOUT_CURRENT  = 1000;
 public static final int LAYOUT_FORECAST = 1001;

 /**
  * Constructs current conditions layout.
  *
  * @param context
  * @param wd
  * @return
  */
 public static RemoteViews buildCurrentLayout(Context context, int appWidgetId, ACCUWX_WeatherData wd){
  Log.d("########", "remoteViews buildCurrentLayout");
  // Return object
  RemoteViews toRet = new RemoteViews(context.getPackageName(), R.layout.widget_current_layout);

  String cityText = wd.getCityName();
  String tempUnits = wd.getMetric() == 0 ? "F" : "C";
  String iconId   = "icon_" + wd.getCurrentIconCode();

  // Populate views with weather data
  toRet.setTextViewText  (R.id.current_location_text,  cityText);
  toRet.setTextViewText  (R.id.current_temp_text,   wd.getCurrentTemperature() + DEG + tempUnits);
  toRet.setTextViewText  (R.id.current_conditions_text, wd.getCurrentConditions());
  toRet.setImageViewResource (R.id.current_condition_image,  ACCUWX.getDrawableId(iconId));
  toRet.setTextViewText  (R.id.current_hi_temp,    context.getString(R.string.hi) + ": " + wd.getForecast().get(0).getDailyHigh() + DEG);
  toRet.setTextViewText  (R.id.current_lo_temp,    context.getString(R.string.lo) +": " + wd.getForecast().get(0).getDailyLow() + DEG);

  // Make alert icon visible if necessary.
  int visibility = wd.getAlertIsActive() == 0 ? View.INVISIBLE : View.VISIBLE;
  toRet.setViewVisibility(R.id.alert_icon, visibility);

  if (MainActivity.mLocations == null)
   MainActivity.mLocations = new ArrayList<String>();
  if (MainActivity.mLocName == null)
   MainActivity.mLocName = new String("");

  if (!MainActivity.mLocations.contains(wd.getZipCode()) || !MainActivity.mLocName.contains(wd.getCityName()))
   MainActivity.mLocations.add(wd.getZipCode());

  MainActivity.isFromLocationSearchActivity = false;

  // Launch SimpleWeather application intent
  Intent intentAppLaunch = new Intent(context, MainActivity.class);
  intentAppLaunch.putExtra(ACCUWX.Extras.LOCATION_CODE, wd.getZipCode());
  intentAppLaunch.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
  PendingIntent pendingAppLaunch = PendingIntent.getActivity(context, appWidgetId, intentAppLaunch, PendingIntent.FLAG_CANCEL_CURRENT);
  toRet.setOnClickPendingIntent(R.id.current_layout, pendingAppLaunch);

  return toRet;
 }

 /**
  * Returns pretty names for display purposes in the form 'city name, state name' for the US and 'cityname, countryname (region)' for other countries.
  * @return
  */
 public static String getPrettyName(ACCUWX_WeatherData wd){
         String prettyName = "null";

         String state = wd.getStateName();
         String city = wd.getCityName();
         String country = wd.getCountryName();
         String countryCode = wd.getCountryCode();

         if (countryCode.equalsIgnoreCase("us"))
          prettyName = city + ", " + state;
         else
          prettyName = city + ", " + country + " (" + state + ")";

         return prettyName;
 }

 /**
  * Constructs deleted layout.
  *
  * @param context
  * @return
  */
 public static RemoteViews buildDeletedLayout(Context context){
  Log.d("########", "remoteViews buildDeletedLayout");
  return new RemoteViews(context.getPackageName(), R.layout.widget_deleted_layout);

 }

}

Could the bitmap error be coming from the device itself and not an issue of my application?

Any help or direction is greatly appreciated!

Body:
This line:

ACCUWX.getDrawableId(iconId)

Make sure your drawable is not larger than it needs to be. When you load a Bitmap, you can load the boundaries first, then scale it, and load the scaled down version.

On Orientation change:

Recycle the old Bitmap

Only load the scaled version

ContentLicense: CC BY-SA 2.5


问:
PowerShell display duplicates in CSV
I have a csv with headers like this

ID,Name,IP,Details

There are some value will be duplicated like this

```<code>1,John,192.168.1.1,Details1
2,Mary,192.168.1.2,Details2
3,John,192.168.1.3,Details3
4,Dick,192.168.1.1,Details4
5,Kent,192.168.1.4,Details5
</code>```

Is there anyway I can select all lines with duplicated values?

Desired Output:

```<code>1,John,192.168.1.1,Details1
3,John,192.168.1.3,Details3
4,Dick,192.168.1.1,Details4
</code>```

So far I have tried

```<code>Import-csv file | group | sort -des | select -f 10
</code>```

but the result only group those with whole lines matching

I will be appreciate if anyone could lend a hand or show direction for me to solve this question. Thanks in advance for any reply

答:
I'm not sure if I've understood your problem up to 100%, but as far as I've understood you want something like this:

# ID Name IP          Detail
#-- ---- --          ------
#1  John 192.168.1.1 Details1
#2  Mary 192.168.1.2 Details2
#3  John 192.168.1.3 Details3
#4  Dick 192.168.1.1 Details4
#5  Kent 192.168.1.4 Details5

$input = Import-csv .\input.csv
$input

$uniqueNames = $input.Name | select -Unique
$duplicateNames = Compare-Object -ReferenceObject $input.Name -DifferenceObject $uniqueNames | ? { $_.SideIndicator -like "<=" } | select -ExpandProperty InputObject

$uniqueIps = $input.IP | select -Unique
$duplicateIps = Compare-Object -ReferenceObject $input.IP -DifferenceObject $uniqueIps | ? { $_.SideIndicator -like "<=" } | select -ExpandProperty InputObject

Write-Output ""
Write-Output "========================="

Write-Output "Duplicate Names: $duplicateNames"
Write-Output "Duplicate IPs: $duplicateIps"```
</div>
</div>
</p>

<p>Output:</p>

```ID Name IP          Detail
-- ---- --          ------
1  John 192.168.1.1 Details1
2  Mary 192.168.1.2 Details2
3  John 192.168.1.3 Details3
4  Dick 192.168.1.1 Details4
5  Kent 192.168.1.4 Details5

=========================
Duplicate Names: John
Duplicate Names: 192.168.1.1
```

Hope that helps.

Title: PowerShell display duplicates in CSV

Body:
I have a csv with headers like this

ID,Name,IP,Details

There are some value will be duplicated like this

1,John,192.168.1.1,Details1
2,Mary,192.168.1.2,Details2
3,John,192.168.1.3,Details3
4,Dick,192.168.1.1,Details4
5,Kent,192.168.1.4,Details5

Is there anyway I can select all lines with duplicated values?

Desired Output:

1,John,192.168.1.1,Details1
3,John,192.168.1.3,Details3
4,Dick,192.168.1.1,Details4

So far I have tried

Import-csv file | group | sort -des | select -f 10

but the result only group those with whole lines matching

I will be appreciate if anyone could lend a hand or show direction for me to solve this question. Thanks in advance for any reply

Body:
I'm not sure if I've understood your problem up to 100%, but as far as I've understood you want something like this:

# ID Name IP          Detail
#-- ---- --          ------
#1  John 192.168.1.1 Details1
#2  Mary 192.168.1.2 Details2
#3  John 192.168.1.3 Details3
#4  Dick 192.168.1.1 Details4
#5  Kent 192.168.1.4 Details5

$input = Import-csv .\input.csv
$input

$uniqueNames = $input.Name | select -Unique
$duplicateNames = Compare-Object -ReferenceObject $input.Name -DifferenceObject $uniqueNames | ? { $_.SideIndicator -like "<=" } | select -ExpandProperty InputObject

$uniqueIps = $input.IP | select -Unique
$duplicateIps = Compare-Object -ReferenceObject $input.IP -DifferenceObject $uniqueIps | ? { $_.SideIndicator -like "<=" } | select -ExpandProperty InputObject

Write-Output ""
Write-Output "========================="

Write-Output "Duplicate Names: $duplicateNames"
Write-Output "Duplicate IPs: $duplicateIps"

Output:

ID Name IP          Detail
-- ---- --          ------
1  John 192.168.1.1 Details1
2  Mary 192.168.1.2 Details2
3  John 192.168.1.3 Details3
4  Dick 192.168.1.1 Details4
5  Kent 192.168.1.4 Details5

=========================
Duplicate Names: John
Duplicate Names: 192.168.1.1

Hope that helps.


问:
Derivatives using indexed variables
As an example I want to try to find the partial derivatives of

```<code>f(x) = \sum_{i=1}^n x_i^2
</code>```

in Maxima. (The expected output would be \frac{\partial f}{\partial x_k} = 2x_k) I have tried following, but it seems the indexed variables are not handled as I expected, can anyone explain what I am doing wrong?

The same command works if you replace n and k with actual numbers, but not in this form:

```<code>f(x) := 1/2 * sum( x[i]^2, i, 1, n);
print(diff(f(x),x[k]));
</code>```

Try it online!

答:
Maxima can't handle derivative with respect to a indexed variable by default. I wrote a couple of small packages to handle these problems. Perhaps this is useful to you.

See: https://pastebin.com/MmYJRqCq (sum_kron_delta, summation of Kronecker delta)
and: https://pastebin.com/UGCPgvAn (diff_sum, derivative of summation wrt indexed variable)

Here's an example applied to your problem. I'll assume you have downloaded the code above to your computer.

```<code>(%i1) load ("sum_kron_delta.mac");
(%o1)                         sum_kron_delta.mac
(%i2) load ("diff_sum.mac");
(%o2)                            diff_sum.mac
(%i3) 'diff ('sum (x[i]^2, i, 1, n), x[j]);
                             n
                            ====
                            \
(%o3)                     2  >    x  kron_delta(i, j)
                            /      i
                            ====
                            i = 1
</code>```

Note that you have to write 'diff('sum(... that is, with the quote mark ' to indicate that diff and sum are nouns (formal expressions) instead of verbs (functions which are called). This is necessary in the implementation of diff_sum and sum_kron_delta because they work with simplification rules. (It's a long story, which I can explain if there's interest.)

I see we got the kron_delta summation, but we need to cause the simplification rules to be applied. We could also write expand(%, 0, 0) here instead of ''%.

```<code>(%i4) ''%;
(%o4) 2 (if (1 <= j) and (j <= n) and %elementp(j, integers) then x  else 0)
                                                                   j
</code>```

At this point we have the final result, which we can simplify further with additional data.

```<code>(%i5) assume (j >= 1, j <= n);
(%o5)                          [j >= 1, n >= j]
(%i6) ''%o4;
(%o6)            2 (if %elementp(j, integers) then x  else 0)
                                                    j
(%i7) declare (j, integer);
(%o7)                                done

(%i8) ''%o6;
(%o8)                                2 x
                                        j
</code>```

If this seems fruitful to you, I'll be happy to go into details.

Title: Derivatives using indexed variables

Body:
As an example I want to try to find the partial derivatives of

f(x) = \sum_{i=1}^n x_i^2

in Maxima. (The expected output would be \frac{\partial f}{\partial x_k} = 2x_k) I have tried following, but it seems the indexed variables are not handled as I expected, can anyone explain what I am doing wrong?

The same command works if you replace n and k with actual numbers, but not in this form:

f(x) := 1/2 * sum( x[i]^2, i, 1, n);
print(diff(f(x),x[k]));

Try it online!

Body:
Maxima can't handle derivative with respect to a indexed variable by default. I wrote a couple of small packages to handle these problems. Perhaps this is useful to you.

See: https://pastebin.com/MmYJRqCq (sum_kron_delta, summation of Kronecker delta)
and: https://pastebin.com/UGCPgvAn (diff_sum, derivative of summation wrt indexed variable)

Here's an example applied to your problem. I'll assume you have downloaded the code above to your computer.

(%i1) load ("sum_kron_delta.mac");
(%o1)                         sum_kron_delta.mac
(%i2) load ("diff_sum.mac");
(%o2)                            diff_sum.mac
(%i3) 'diff ('sum (x[i]^2, i, 1, n), x[j]);
                             n
                            ====
                            \
(%o3)                     2  >    x  kron_delta(i, j)
                            /      i
                            ====
                            i = 1

Note that you have to write 'diff('sum(... that is, with the quote mark ' to indicate that diff and sum are nouns (formal expressions) instead of verbs (functions which are called). This is necessary in the implementation of diff_sum and sum_kron_delta because they work with simplification rules. (It's a long story, which I can explain if there's interest.)

I see we got the kron_delta summation, but we need to cause the simplification rules to be applied. We could also write expand(%, 0, 0) here instead of ''%.

(%i4) ''%;
(%o4) 2 (if (1 <= j) and (j <= n) and %elementp(j, integers) then x  else 0)
                                                                   j

At this point we have the final result, which we can simplify further with additional data.

(%i5) assume (j >= 1, j <= n);
(%o5)                          [j >= 1, n >= j]
(%i6) ''%o4;
(%o6)            2 (if %elementp(j, integers) then x  else 0)
                                                    j
(%i7) declare (j, integer);
(%o7)                                done

(%i8) ''%o6;
(%o8)                                2 x
                                        j

If this seems fruitful to you, I'll be happy to go into details.


问:
Can python's dir() return attributes that are not in the object?
When running the following line of code:

```<code>variables = [at for at in dir(prev.m) if (not at.startswith('__') and (getattr(prev.m, at)==None or not callable(getattr(prev.m, at))))]
</code>```

I get the following error:

```<code>AttributeError: 'UserClientDocument' object has no attribute 'profile'
</code>```

which from the python documentation seems to mean that it's not a member of the object. However:
1. Printing dir(prev.m) in the line above shows 'profile' as one of the members
2. The line itself seems to be checking that all attributes checked should be in dir(prev.m)

My only guess is that dir() must give 'profile' as one of the attributes, when it is not. Is that correct? Any other options?

The python documentation making me suspect that dir() may not be 100% exact:

Note Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

答:
Yeah, easily. Simple example:

```<code>class Example(object):
    @property
    def attr(self):
        return self._attr

x = Example()
print('attr' in dir(x))  # prints True
getattr(x, 'attr')       # raises an AttributeError
</code>```

And really, dir can return any names at all:

```<code>class Example(object):
    def __dir__(self):
        return ['foo', 'bar', 'potatoes']

print(dir(Example()))  # prints ['bar', 'foo', 'potatoes'] (sorted, because dir does that)
</code>```

Body:
When running the following line of code:

variables = [at for at in dir(prev.m) if (not at.startswith('__') and (getattr(prev.m, at)==None or not callable(getattr(prev.m, at))))]

I get the following error:

AttributeError: 'UserClientDocument' object has no attribute 'profile'

which from the python documentation seems to mean that it's not a member of the object. However:
1. Printing dir(prev.m) in the line above shows 'profile' as one of the members
2. The line itself seems to be checking that all attributes checked should be in dir(prev.m)

My only guess is that dir() must give 'profile' as one of the attributes, when it is not. Is that correct? Any other options?

The python documentation making me suspect that dir() may not be 100% exact:

Note Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

Body:
Yeah, easily. Simple example:

class Example(object):
    @property
    def attr(self):
        return self._attr

x = Example()
print('attr' in dir(x))  # prints True
getattr(x, 'attr')       # raises an AttributeError

And really, dir can return any names at all:

class Example(object):
    def __dir__(self):
        return ['foo', 'bar', 'potatoes']

print(dir(Example()))  # prints ['bar', 'foo', 'potatoes'] (sorted, because dir does that)


问:
Convert specific number of rows to columns in R and repeat the process for a large dataset
I'm having a dataset of 15 million rows with single column. It looks like,

```<code>x_raw
A1
A2
A3
A4
B1
B2
B3
B4
C1
C2

I want to convert it to

A1 A2 A3 A4
B1 B2 B3 B4
C1 C2 C3 C4
</code>```

I was trying with 'for' loop, that will transpose every 4 rows, and add them to a 'final' dataframe, but as the dataset is too large, it'll iterate almost 2.7 million times which is not working that efficiently. Is there any other method or anything that I can use to do it efficiently?

答:
Here is one option with tidyverse where the separate the 'x_raw' into two column and then spread to 'wide' format

```<code>library(dplyr)
library(tidyr)
separate(df1, x_raw, into = c('x', 'rn'), sep="(?=\\d+)", remove = FALSE) %>%
       spread(rn, x_raw) %>%
       select(-x)
#   1  2    3    4
#1 A1 A2   A3   A4
#2 B1 B2   B3   B4
#3 C1 C2 <NA> <NA>
</code>```

Or if the number of elements are always 4, then we can also do

```<code>as.data.frame(matrix(df1$x_raw, ncol =4, byrow = TRUE), stringsAsFactors=FALSE)
</code>```

Body:
I'm having a dataset of 15 million rows with single column. It looks like,

x_raw
A1
A2
A3
A4
B1
B2
B3
B4
C1
C2

I want to convert it to

A1 A2 A3 A4
B1 B2 B3 B4
C1 C2 C3 C4

I was trying with 'for' loop, that will transpose every 4 rows, and add them to a 'final' dataframe, but as the dataset is too large, it'll iterate almost 2.7 million times which is not working that efficiently. Is there any other method or anything that I can use to do it efficiently?

Body:
Here is one option with tidyverse where the separate the 'x_raw' into two column and then spread to 'wide' format

library(dplyr)
library(tidyr)
separate(df1, x_raw, into = c('x', 'rn'), sep="(?=\\d+)", remove = FALSE) %>%
       spread(rn, x_raw) %>%
       select(-x)
#   1  2    3    4
#1 A1 A2   A3   A4
#2 B1 B2   B3   B4
#3 C1 C2 <NA> <NA>

Or if the number of elements are always 4, then we can also do

as.data.frame(matrix(df1$x_raw, ncol =4, byrow = TRUE), stringsAsFactors=FALSE)


问:
User Input Date Comparison in Javascript and moment.js
I'm trying to compare two user input dates which is not related to the current or today's date with moment.js. I want to display the color based on the date difference.Help me reach out.

Here is my code:

function compare() {
 var firstDate = moment($("#date1").val(), "MM-DD-YYYY");
  var secondDate = moment($("#date2").val(), "MM-DD-YYYY");

  console.log(firstDate.inspect(), secondDate.inspect());

  if (firstDate.isValid() && secondDate.isValid()) {
    // you need a validation before using diff function of momentjs
    var diff = Math.abs(firstDate.diff(secondDate, 'days'));
    console.log(diff);
    // you also need to remove all classes before adding new class
    $("#status").removeClass("redBg").removeClass("greenBg").removeClass("yellowBg");
    if (diff => 14) {
      $("#status").addClass('redBg');
    } else if (7 < diff =< 9) {
      $("#status").addClass('greenBg');
    } else if(diff >= 6) {
      $("#status").addClass('yellowBg');
    }
  } else {
    $("#status").addClass('yellowBg');
  }

    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.greenBg {
    background: green;
}

.yellowBg {
    background: yellow;
}

.redBg {
    background: red;
}</code>```

    <input type="text" id="date1" onchange=/>
<input type="text" id="date2" onchange='compare()'/>
<input  readonly type="text" id="status"/>

```

what is the mistake I have made?

答:
what you do wrong is on onclick=function()

you cannot assign a non-named function in onclick that way

if you want to attach the function without naming it, you should consider addEventListener or using jQuery .on('click', function(){}) way

http://api.jquery.com/on/

update:

after your update, your problem is that you are always checking for positive values. moment diff will result negative values when:

```<code>d1.diff(d2)
</code>```

and d1 is earlier than d2

therefore you need to Math.abs() it first

Body:
I'm trying to compare two user input dates which is not related to the current or today's date with moment.js. I want to display the color based on the date difference.Help me reach out.

Here is my code:

function compare() {
 var firstDate = moment($("#date1").val(), "MM-DD-YYYY");
  var secondDate = moment($("#date2").val(), "MM-DD-YYYY");

  console.log(firstDate.inspect(), secondDate.inspect());

  if (firstDate.isValid() && secondDate.isValid()) {
    // you need a validation before using diff function of momentjs
    var diff = Math.abs(firstDate.diff(secondDate, 'days'));
    console.log(diff);
    // you also need to remove all classes before adding new class
    $("#status").removeClass("redBg").removeClass("greenBg").removeClass("yellowBg");
    if (diff => 14) {
      $("#status").addClass('redBg');
    } else if (7 < diff =< 9) {
      $("#status").addClass('greenBg');
    } else if(diff >= 6) {
      $("#status").addClass('yellowBg');
    }
  } else {
    $("#status").addClass('yellowBg');
  }

    });

.greenBg {
    background: green;
}

.yellowBg {
    background: yellow;
}

.redBg {
    background: red;
}

    <input type="text" id="date1" onchange=/>
<input type="text" id="date2" onchange='compare()'/>
<input  readonly type="text" id="status"/>

what is the mistake I have made?

Body:
what you do wrong is on onclick=function()

you cannot assign a non-named function in onclick that way

if you want to attach the function without naming it, you should consider addEventListener or using jQuery .on('click', function(){}) way

http://api.jquery.com/on/

update:

after your update, your problem is that you are always checking for positive values. moment diff will result negative values when:

d1.diff(d2)

and d1 is earlier than d2

therefore you need to Math.abs() it first


问:
How to print ajax response to span class
I wanted to show ajax response to following  HTML where initially 0 available slot which could be changed on ajax response.
and based on data response dropdown_wrapper class
 will come automatically.
How do i make it dynamic?

```<code><span class="selected_item">0 available Slots</span>
<div class="form_item_dropdown">
    <div class="dropdown_wrapper">
        <li class="timeSlot" id="time1">
            <i class="icon fa fa-clock-o" aria-hidden="true">
            </i>
            <span class="item_title">10am - 4pm (value comes through Ajax)</span>
        </li>
    </div>
</div>
</code>```

Ajax code :

```<code>   $(".school_title").on("click", function (argument) {
        var id = $(this).attr('id');
        var info=$.get("{{url('school-slot')}}",{id:id});
        info.done(function(data){
            console.log(data.length);
  /*        $.each(data,function(index,subcatObj){
            });  */
        });
    });
</code>```

Here is the response :

```<code>{id: 3, school_id: 3, break_time: "10am - 8pm"}

{id: 4, school_id: 3, break_time: "10am - 4:30pm"}
</code>```

答:
change ajax code Like this . use javascrpt string concatenate +=

```<code> `$(".school_title").on("click", function (argument) {
 var id = $(this).attr('id');
 var info=$.get("{{url('school-slot')}}",{id:id});
 info.done(function(data){
 data= JSON.parse(data);
 console.log(data.length);
 html="";
 $.each(data,function(index,subcatObj){
 html +="<li class="timeSlot" id="time'+subcatObj+'"><i class="icon fa fa-
 clock-o" aria-hidden="true"></i> ";
 });
 $(".dropdown_wrapper").append(html);
 });
 });
</code>```

`

Body:
I wanted to show ajax response to following  HTML where initially 0 available slot which could be changed on ajax response.
and based on data response dropdown_wrapper class
 will come automatically.
How do i make it dynamic?

0 available Slots

            10am - 4pm (value comes through Ajax)

Ajax code :

   $(".school_title").on("click", function (argument) {
        var id = $(this).attr('id');
        var info=$.get("{{url('school-slot')}}",{id:id});
        info.done(function(data){
            console.log(data.length);
  /*        $.each(data,function(index,subcatObj){
            });  */
        });
    });

Here is the response :

{id: 3, school_id: 3, break_time: "10am - 8pm"}

{id: 4, school_id: 3, break_time: "10am - 4:30pm"}

Body:
change ajax code Like this . use javascrpt string concatenate +=

 `$(".school_title").on("click", function (argument) {
 var id = $(this).attr('id');
 var info=$.get("{{url('school-slot')}}",{id:id});
 info.done(function(data){
 data= JSON.parse(data);
 console.log(data.length);
 html="";
 $.each(data,function(index,subcatObj){
 html +="<li class="timeSlot" id="time'+subcatObj+'"><i class="icon fa fa-
 clock-o" aria-hidden="true"></i> ";
 });
 $(".dropdown_wrapper").append(html);
 });
 });

`


问:
No keyword with name 'Remove String' found
I am trying to get the number 70 from the below mentioned string:

Showing 1 to 50 of 70 entries

I have tried the below code:

```<code>${text} = Get Text xpath=//div[@id='DataTables_Table']
Page Should Contain Showing 1 to
${edited_text} = Remove String ${text} Showing 1 to 50 of
</code>```

But i am getting the below mentioned error:

No keyword with name 'Remove String' found.

I am getting the same error even if I use the following keywords:

Get Substring, Replace String

答:
When keywords aren't found, this typically means that the library has not been loaded. With the exception of the BuiltIn library, all others need to be declared. A full working example of your code is below:

```<code>*** Setting ***
Library    String

*** Test Cases ***
tc
    ${text}           Set Variable    Showing 1 to 50 of 70 entries
    ${edited_text}    Remove String     ${text}     Showing 1 to 50 of

    ${matches}        String.Get Regexp Matches    ${text}    [0-9]{1,2}
    Log               "Max is:" ${matches[2]}
</code>```

As you're intention is to match the 3rd digit group, the regular expression match seems like the cleanest approach.

Body:
I am trying to get the number 70 from the below mentioned string:

Showing 1 to 50 of 70 entries

I have tried the below code:

${text} = Get Text xpath=//div[@id='DataTables_Table']
Page Should Contain Showing 1 to
${edited_text} = Remove String ${text} Showing 1 to 50 of

But i am getting the below mentioned error:

No keyword with name 'Remove String' found.

I am getting the same error even if I use the following keywords:

Get Substring, Replace String

Body:
When keywords aren't found, this typically means that the library has not been loaded. With the exception of the BuiltIn library, all others need to be declared. A full working example of your code is below:

*** Setting ***
Library    String

*** Test Cases ***
tc
    ${text}           Set Variable    Showing 1 to 50 of 70 entries
    ${edited_text}    Remove String     ${text}     Showing 1 to 50 of

    ${matches}        String.Get Regexp Matches    ${text}    [0-9]{1,2}
    Log               "Max is:" ${matches[2]}

As you're intention is to match the 3rd digit group, the regular expression match seems like the cleanest approach.


问:
Issue with AMP default height values being toggled
I have an amp carousel with some hide/show content at the bottom.  I am using amp-bind to dynamically hide and show some extra content as well as adjust the height value of the carousel itself so that the content can be seen.

The markup is something like this, but with a couple more slides with similar content:

```<code><amp-carousel
   [height]="visible ? 720 : 550"
   height="550"
   width="400"
   layout="responsive"
   type="slides">
    <div class="carousel__slide">
       <p>Text content here</p>
       <button [text]="visible ? 'See Less' : 'See More'"
           on="tap:AMP.setState({visible: !visible})">See More</button>
       <ul [class]="visible ? 'show' : 'hide'" class="hide">
          <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</li>
          <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</li>
          <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</li>
       </ul>
    </div>
</amp-carousel>
</code>```

With that mark I get the following error:

```<code>amp-bind: Default value for [height] does not match first expression result (550). This can result in unexpected behavior after the next state change.
</code>```

I tried adding a default value for height before the carousel but that didn't seem to help

```<code><amp-state id="props">
    <script type="application/json">
      {
        "height": "550"
      }
    </script>
  </amp-state>
</code>```

I tried passing it both a number and string, with brackets and without but none of it seems to work

答:
After discussing with the AMP team, they informed me that's it's actually a bug with the validation in developer mode

Bug has been filed here: https://github.com/ampproject/amphtml/issues/12028

Body:
I have an amp carousel with some hide/show content at the bottom.  I am using amp-bind to dynamically hide and show some extra content as well as adjust the height value of the carousel itself so that the content can be seen.

The markup is something like this, but with a couple more slides with similar content:

<amp-carousel
   [height]="visible ? 720 : 550"
   height="550"
   width="400"
   layout="responsive"
   type="slides">

Text content here

       <button [text]="visible ? 'See Less' : 'See More'"
           on="tap:AMP.setState({visible: !visible})">See More</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

</amp-carousel>

With that mark I get the following error:

amp-bind: Default value for [height] does not match first expression result (550). This can result in unexpected behavior after the next state change.

I tried adding a default value for height before the carousel but that didn't seem to help

<amp-state id="props">

  </amp-state>

I tried passing it both a number and string, with brackets and without but none of it seems to work


问:
Meteor/React/React-Router4 - redirect in HoC withTracker
I have a collection which includes public and private object. Those which are public should be able to be seen by everyone, private ones — only by their owner. I have the following routes in react-router v4:

const Routes = () => (
<BrowserRouter>

        <Sidebar />
        <Switch>
            <Route path="/" component={Index} exact={true} />
            <Route path="/admin" component={Admin} />
            <Route path="/list/:id" component={OneList} />
            <Route path="/dashboard" component={Dashboard} />
            <Route path="/login" component={Login} />
            <Route path="/signup" component={Signup} />
        </Switch>

</BrowserRouter>
);
```

<p>And I'd like to redirect if someone goes to a <code>/list/:id</code> link if there is no list (or the user doesn't have the right to see it cause it's private and owned by someone else).</p>

<p>I've tried to manage it in my <code>OneList</code> component which uses <code>withTracker</code> to get its data:</p>

<pre class="lang-js prettyprint-override"><code>export default withTracker((props) => {
  const data = Meteor.subscribe('database');
  const myLists = Meteor.subscribe('myLists');
  const publicLists = Meteor.subscribe('publicLists');

  const list = List.findOne({_id: props.match.params.id});
  if (list === undefined){
    props.history.push('/');
  } else {
    return {
      currentUser: Meteor.user(),
      listLoading: !publicLists.ready() && !data.ready() && !myLists.ready(),
      list,
      database: Database.find({}).fetch(),
    };
  }
})(OneList);
</code>```

But when I do this I get the follwing error:

```<code>es5-shim.js?hash=c070fc7…:1240 Uncaught TypeError: Cannot convert undefined or null to object
    at keys (<anonymous>)
    at Function.keys (es5-shim.js?hash=c070fc7…:1240)
    at MeteorDataManager.calculateData (ReactMeteorData.jsx:85)
    at ReactMeteorDataComponent.componentWillMount (ReactMeteorData.jsx:130)
    at callComponentWillMount (modules.js?hash=abbf998…:14583)
    at mountClassInstance (modules.js?hash=abbf998…:14640)
    at updateClassComponent (modules.js?hash=abbf998…:15022)
    at beginWork (modules.js?hash=abbf998…:15411)
    at performUnitOfWork (modules.js?hash=abbf998…:17379)
    at workLoop (modules.js?hash=abbf998…:17488)

modules.js?hash=abbf998…:13111 The above error occurred in the <ReactMeteorDataComponent> component:
    in ReactMeteorDataComponent (created by Route)
    in Route (created by Routes)
    in Switch (created by Routes)
    in div (created by Routes)
    in Router (created by BrowserRouter)
    in BrowserRouter (created by Routes)
    in Routes

Consider adding an error boundary to your tree to customize error handling behavior.
You can learn more about error boundaries at /react-error-boundaries.

modules.js?hash=abbf998…:17685 Uncaught TypeError: Cannot convert undefined or null to object
    at keys (<anonymous>)
    at Function.keys (es5-shim.js?hash=c070fc7…:1240)
    at MeteorDataManager.calculateData (ReactMeteorData.jsx:85)
    at ReactMeteorDataComponent.componentWillMount (ReactMeteorData.jsx:130)
    at callComponentWillMount (modules.js?hash=abbf998…:14583)
    at mountClassInstance (modules.js?hash=abbf998…:14640)
    at updateClassComponent (modules.js?hash=abbf998…:15022)
    at beginWork (modules.js?hash=abbf998…:15411)
    at performUnitOfWork (modules.js?hash=abbf998…:17379)
    at workLoop (modules.js?hash=abbf998…:17488)
</code>```

From my research it may be because I don't return an object from withTracker, but I don't want to, as I want to redirect.

Any idea how to solve this? Maybe my check and redirect should be done inside the router?

答:
To redirect run

```<code>meteor npm install react-router
</code>```

To redirect in react-router v4 you have to do it in the render function.

```<code>(list === undefined) &&
  <Redirect to={'/Home'}/>
</code>```

This is a normal if statement or you can do

```<code>(list === undefined) ?
  <Redirect to={'/Home'}/>
:
  <Redirect to={'/Login'}/>
</code>```

Body:
I have a collection which includes public and private object. Those which are public should be able to be seen by everyone, private ones — only by their owner. I have the following routes in react-router v4:

const Routes = () => (
<BrowserRouter>

        <Sidebar />
        <Switch>
            <Route path="/" component={Index} exact={true} />
            <Route path="/admin" component={Admin} />
            <Route path="/list/:id" component={OneList} />
            <Route path="/dashboard" component={Dashboard} />
            <Route path="/login" component={Login} />
            <Route path="/signup" component={Signup} />
        </Switch>

</BrowserRouter>
);

And I'd like to redirect if someone goes to a /list/:id link if there is no list (or the user doesn't have the right to see it cause it's private and owned by someone else).

I've tried to manage it in my OneList component which uses withTracker to get its data:

export default withTracker((props) => {
  const data = Meteor.subscribe('database');
  const myLists = Meteor.subscribe('myLists');
  const publicLists = Meteor.subscribe('publicLists');

  const list = List.findOne({_id: props.match.params.id});
  if (list === undefined){
    props.history.push('/');
  } else {
    return {
      currentUser: Meteor.user(),
      listLoading: !publicLists.ready() && !data.ready() && !myLists.ready(),
      list,
      database: Database.find({}).fetch(),
    };
  }
})(OneList);

But when I do this I get the follwing error:

es5-shim.js?hash=c070fc7…:1240 Uncaught TypeError: Cannot convert undefined or null to object
    at keys (<anonymous>)
    at Function.keys (es5-shim.js?hash=c070fc7…:1240)
    at MeteorDataManager.calculateData (ReactMeteorData.jsx:85)
    at ReactMeteorDataComponent.componentWillMount (ReactMeteorData.jsx:130)
    at callComponentWillMount (modules.js?hash=abbf998…:14583)
    at mountClassInstance (modules.js?hash=abbf998…:14640)
    at updateClassComponent (modules.js?hash=abbf998…:15022)
    at beginWork (modules.js?hash=abbf998…:15411)
    at performUnitOfWork (modules.js?hash=abbf998…:17379)
    at workLoop (modules.js?hash=abbf998…:17488)

modules.js?hash=abbf998…:13111 The above error occurred in the <ReactMeteorDataComponent> component:
    in ReactMeteorDataComponent (created by Route)
    in Route (created by Routes)
    in Switch (created by Routes)
    in div (created by Routes)
    in Router (created by BrowserRouter)
    in BrowserRouter (created by Routes)
    in Routes

Consider adding an error boundary to your tree to customize error handling behavior.
You can learn more about error boundaries at /react-error-boundaries.

modules.js?hash=abbf998…:17685 Uncaught TypeError: Cannot convert undefined or null to object
    at keys (<anonymous>)
    at Function.keys (es5-shim.js?hash=c070fc7…:1240)
    at MeteorDataManager.calculateData (ReactMeteorData.jsx:85)
    at ReactMeteorDataComponent.componentWillMount (ReactMeteorData.jsx:130)
    at callComponentWillMount (modules.js?hash=abbf998…:14583)
    at mountClassInstance (modules.js?hash=abbf998…:14640)
    at updateClassComponent (modules.js?hash=abbf998…:15022)
    at beginWork (modules.js?hash=abbf998…:15411)
    at performUnitOfWork (modules.js?hash=abbf998…:17379)
    at workLoop (modules.js?hash=abbf998…:17488)

From my research it may be because I don't return an object from withTracker, but I don't want to, as I want to redirect.

Any idea how to solve this? Maybe my check and redirect should be done inside the router?

Body:
To redirect run

meteor npm install react-router

To redirect in react-router v4 you have to do it in the render function.

(list === undefined) &&
  <Redirect to={'/Home'}/>

This is a normal if statement or you can do

(list === undefined) ?
  <Redirect to={'/Home'}/>
:
  <Redirect to={'/Login'}/>


问:
how to use the debug library to interact with a required lua file's upvalues
If I have a Lua function f I can look at all the upvalues in f's closure by using the debug.getupvalue function. Similarly if I have a file foo.lua I can look at the upvalues by first doing foo = loadfile(foo) then using debug.getupvalue in the same way that you would for f. If I require foo.lua is there anyway I can figure out what the upvalues for the closure of foo.lua are?

答:
The module loaded by require is not preserved by require's standard loaders. Only the return value from the execution of that module is preserved.

So while you can inspect any upvalues for any function exported by the module, you cannot inspect upvalues that are only accessed by non-accessible functions.


问:
Character Pawn sliding back when picking up objects
I am using Unreal Engine to create a puzzle game. In this game, the player has to pick up a chair/table and place it on a pressure plate in another part of the room in order to unlock a door.

When play testing, picking up objects causes my character to slide back. Once the sliding starts, there is no way to make the character stop sliding. I suspect that this issue may be caused by the object's collision volume entering the character's. However, when I release the object, my character keeps gliding backwards even though by then, the object's collision volume is out of reach.

On my character's blueprint I have locked rotation on all axes, so that it won't randomly start rolling backwards after picking up an object. This solves part of the issue but there is still the gliding that just won't stop.

I am new to UE and I have no idea what may be causing this issue. If you have any previous experience in this or simply want to chime in, please do!

答: Dont know why this is happening exactly unless we see the actual settings you are using and the BP but when you pick up the object , disable its physics and collision and when you put it back enable it after a delay of 0.5 or 1 second . Hope this helps. </p>


问:
create-react-app command not found in ubuntu 16.04 LTS
I tried to install create react app using sudo npm install -g create-react-app on my terminal, then this message appeared:

/home/mahi/.npm-global/bin/create-react-app -> /home/mahi/.npm-global/lib/node_modules/create-react-app/index.js
+ create-react-app@1.4.3
updated 1 package in 11.7s

Then when I am going to run the command create-react-app hello-world, it says create-react-app command not found. Then I searched for many solutions, I tried almost all of them, but nothing improved, showing the command not found again and again.

答: are you using create-react-app with sudo? because if you installed the package using sudo npm install create-react-app then it is installed for this user, try sudo create-react-app and if it works then you should change ownership to your user


问:
What happens to Java runtime errors
Following on from this question https://softwareengineering.stackexchange.com/questions/37294/logging-why-and-what

I was wondering what actually happens to an error that occurs during the runtime of a Java Enterprise Edition applicaiton.
Does the JVM store a log of all the errors?
Or are the errors forgotten?

答: It is contingent where the output is directed. If output is getting pushed to a console window then yes...it is all but lost. An enterprise application however would be making use of a logging framework to deal with all output thus rendering any exception available within the logs provided by the framework.</p>

OwnerDisplayName: Steve

Title: What happens to Java runtime errors

OwnerDisplayName: Aaron


问:
Angular 2 | How to sort numeric value using pipe?
Good day,

How can i sort numeric value in angular 2 using pipes? or is their any builtin pipes for sorting numbers?

```<code><div class="group group1">
<div *ngFor="let apidata of data">
  <div *ngIf="apidata.AssignmentNumber[0] == 1" class="box">
      <div class="box-assignmentnumber-holder">
        <span id="AssignmentNumber" [ngStyle]="{'color': apidata.AssignmentNumber[1] == 1 ? '#FF8C00' : 'green'}">{{apidata.AssignmentNumber | desc}}</span>
      </div>
      <div id="arrow" (click)="this.clickMe =! this.clickMe"></div>
  </div>
</div>
</code>```

above is my code in displaying number, but i want to sort them in ascending order.

答:
Angular does not ship a sort pipe because they seem to think it degrades performance to an unacceptable degree. However, I have employed them and found them to be useful. You just need to write one.

```<code>import {Pipe} from '@angular/core';

@Pipe({name: 'sortBy'}) export class SortBy {
  transform<T>(
    values: T[] | undefined,
    by: keyof T | ((x: T) => any),
    direction?: 'ascending' | 'descending'
  ) {
   const thrust = direction || 'ascending';

   const getKey = typeof by === 'function' ? by : ((x: T) => x[by]);

   return values && values.slice().sort((x, y) => {
     const xKey = String(getKey(x));
     const yKey = String(getKey(y));
     return thrust === 'ascending'
       ? xKey.localeCompare(yKey)
       : yKey.localeCompare(xKey);
     });
  }
}
</code>```

Now you have a generic sorting pipe that can take the property name is a string or a function that returns a property value, and optionally a direction.

Body:
Good day,

How can i sort numeric value in angular 2 using pipes? or is their any builtin pipes for sorting numbers?

        {{apidata.AssignmentNumber | desc}}

above is my code in displaying number, but i want to sort them in ascending order.

Body:
Angular does not ship a sort pipe because they seem to think it degrades performance to an unacceptable degree. However, I have employed them and found them to be useful. You just need to write one.

import {Pipe} from '@angular/core';

@Pipe({name: 'sortBy'}) export class SortBy {
  transform<T>(
    values: T[] | undefined,
    by: keyof T | ((x: T) => any),
    direction?: 'ascending' | 'descending'
  ) {
   const thrust = direction || 'ascending';

   const getKey = typeof by === 'function' ? by : ((x: T) => x[by]);

   return values && values.slice().sort((x, y) => {
     const xKey = String(getKey(x));
     const yKey = String(getKey(y));
     return thrust === 'ascending'
       ? xKey.localeCompare(yKey)
       : yKey.localeCompare(xKey);
     });
  }
}

Now you have a generic sorting pipe that can take the property name is a string or a function that returns a property value, and optionally a direction.


问:
Angular4 *ngFor how to loop nested array using its key name
I have the following data sample:

for now i have two nested loop, but what i want to do is, Is it possible to loop through specific key, such as *ngFor="let key of myArray.functionalArea"

My current code is:

```<code><span *ngFor="let jobByField of countOfJobsByFields">
  <span  *ngFor="let jobByWorkType of countOfJobsByFields?.workType">
    <li (click)="searchByWorkType(jobByWorkType?._id)"><a>{{ jobByWorkType?._id }}<span class="badge badge-default pull-right item-plus-icon-custom-style">{{ jobByWorkType.total }}</span></a></li>
 </span>
</code>```

and for second key i have this:

```<code><span *ngFor="let jobByField of countOfJobsByFields">
  <span  *ngFor="let jobByFunctionalArea of countOfJobsByFields?.functionalArea">
    <li (click)="searchByFunctionalArea(jobByFunctionalArea?._id)"><a>{{ jobByWorkType?._id }}<span class="badge badge-default pull-right item-plus-icon-custom-style">{{ jobByFunctionalArea.total }}</span></a></li>
 </span>
</code>```

Note i can not use the same  for both because they are separate element in my html.

答:
Use following code

```<code> <span *ngFor="let jobByField of countOfJobsByFields">
<div *ngIf='jobByField.workType'>
    <span  *ngFor="let jobByWorkType of jobByField.workType">
        {{jobByWorkType._id}}
    </span>
</div>

<div  *ngIf='jobByField.functionalArea'>
    <span  *ngFor="let jobByWorkType of jobByField.functionalArea">
        {{jobByWorkType._id}}
    </span>
</div>
</code>```

where JSON:-

```<code>countOfJobsByFields = [
      {
        workType: [{'_id':'Part Time', 'total':10}, {'_id': 'Full Time', 'total': 20}]
      },
      {
        functionalArea: [{'_id':'IT', 'total':10}, {'_id': 'Management', 'total': 20}]
      }

    ]
</code>```

Plunker

Body:
I have the following data sample:

for now i have two nested loop, but what i want to do is, Is it possible to loop through specific key, such as *ngFor="let key of myArray.functionalArea"

My current code is:

{{ jobByWorkType?._id }}{{ jobByWorkType.total }}

and for second key i have this:

{{ jobByWorkType?._id }}{{ jobByFunctionalArea.total }}

Note i can not use the same  for both because they are separate element in my html.

Body:
Use following code

 <span *ngFor="let jobByField of countOfJobsByFields">
<div *ngIf='jobByField.workType'>
    <span  *ngFor="let jobByWorkType of jobByField.workType">
        {{jobByWorkType._id}}
    </span>
</div>

<div  *ngIf='jobByField.functionalArea'>
    <span  *ngFor="let jobByWorkType of jobByField.functionalArea">
        {{jobByWorkType._id}}
    </span>
</div>

where JSON:-

countOfJobsByFields = [
      {
        workType: [{'_id':'Part Time', 'total':10}, {'_id': 'Full Time', 'total': 20}]
      },
      {
        functionalArea: [{'_id':'IT', 'total':10}, {'_id': 'Management', 'total': 20}]
      }

    ]

Plunker


问:
C: why does pointer address set to null in function, have a non-null address in main?
I am a beginner in C. I am working on an assignment to create a tree data structure. I have an if in main where I check if top is NULL before doing some action. Within my function to create the top pointer, it returns NULL right after being created (as expected, I haven't pointed it at anything yet). However when execution goes back to main, it returns an address even though I haven't assigned it one. So, my if doesn't work like I want it to.

I have noticed, if I set top to NULL from within main, then it sticks.

My question is, why does the address of top change from NULL to something else when execution returns to main? Have I done something in my code to unknowingly give point top to an unintended address?

```<code>//struct for org chart tree
    typedef struct org_tree{
        struct employee *top;
    } org_tree;

//create org tree
    void CreateTree(org_tree *t)
    {
        org_tree *temp;
        temp = malloc(sizeof(org_tree));
        t = temp;
        printf("%p\n", t->top); **here returns (nil) as expected
    }

//main program
    int main(void)
    {
        FILE *file;
        file = fopen("employee.list", "r");
        printf("file opened\n");
        org_tree t;

        CreateTree(&t);
        printf("%p\n", t.top) **here returns a memory location

        t.top = NULL **if I add this, then if below works.

        char mgr[20], st1[20], st2[20], st3[20], st4[20];

        while(fscanf(file, "%s %s %s %s %s\n", mgr, st1, st2, st3, st4)!=EOF)
        {
            employee *m;
            if (t.top !=NULL) **this if not working like I want it to because NULL doesn't "stick" unless set in main.
            {
             ///remaining code not relevant to question//
            }
         }
         ...
</code>```

答:
It's because your top variable in the function is a local variable and it's scope is only valid in the function and is not available to other functions.

The variable top is redeclared n main function is a individual variable and is not related to the variable in the function. It has non null value cause it contains a garbage value.

To fix your problem  you can make the top variable global .
That is declare it once at before the functions .
You can't have to declare it again in function and main function. Now this variable will shared by all the functions.

Body:
I am a beginner in C. I am working on an assignment to create a tree data structure. I have an if in main where I check if top is NULL before doing some action. Within my function to create the top pointer, it returns NULL right after being created (as expected, I haven't pointed it at anything yet). However when execution goes back to main, it returns an address even though I haven't assigned it one. So, my if doesn't work like I want it to.

I have noticed, if I set top to NULL from within main, then it sticks.

My question is, why does the address of top change from NULL to something else when execution returns to main? Have I done something in my code to unknowingly give point top to an unintended address?

//struct for org chart tree
    typedef struct org_tree{
        struct employee *top;
    } org_tree;

//create org tree
    void CreateTree(org_tree *t)
    {
        org_tree *temp;
        temp = malloc(sizeof(org_tree));
        t = temp;
        printf("%p\n", t->top); **here returns (nil) as expected
    }

//main program
    int main(void)
    {
        FILE *file;
        file = fopen("employee.list", "r");
        printf("file opened\n");
        org_tree t;

        CreateTree(&t);
        printf("%p\n", t.top) **here returns a memory location

        t.top = NULL **if I add this, then if below works.

        char mgr[20], st1[20], st2[20], st3[20], st4[20];

        while(fscanf(file, "%s %s %s %s %s\n", mgr, st1, st2, st3, st4)!=EOF)
        {
            employee *m;
            if (t.top !=NULL) **this if not working like I want it to because NULL doesn't "stick" unless set in main.
            {
             ///remaining code not relevant to question//
            }
         }
         ...


问:
new Random().nextInt(999999) sometimes generates 5 digit number
I am using new Random().nextInt(999999) to generate a 6 digit random number. But sometimes it generates 5 digit numbers. And I explicitly have to check if generated number is not 6 digit.

Why this method does that? And is there any other way to be pretty sure it generate only 6 digit random number.

答:
Random().nextInt(999999) generates number between 0 and 999998, so you have ~10% chance to get number smaller than 100000 (5 and less digits).

Try

```<code>100000 + Random().nextInt(900000)
</code>```

you will get number in range 100000 - 999999

Body:
Random().nextInt(999999) generates number between 0 and 999998, so you have ~10% chance to get number smaller than 100000 (5 and less digits).

Try

100000 + Random().nextInt(900000)

you will get number in range 100000 - 999999


问:
load multiple csv files into Dataframe: columns names issue
I have multiple csv files with the same format (14 rows 4 columns).
I tried to load all of them into a single dataFrame, and use file's name to rename the values of the first column (1-14)

```<code>    1   500 0   0
    2   350 0   1
    3   500 1   0
    .............
    13  600 0   0
    14  800 0   0
</code>```

I tried the following code but I am not getting what I am expecting:

```<code>    filenames = os.listdir('Threshold/')
    Y = pd.DataFrame () #empty df
    # file name are in the following foramt "subx_ICA_thre.csv"
    # need to get x (subject number to be used later for renaming columns values)
    Sub_list=[]
    for filename in filenames:
    s= int(''.join(filter(str.isdigit, filename)))
    Sub_list.append(int(s))
    S_Sub_list= sorted(Sub_list)

    for x in S_Sub_list: # get the file according to the subject number
    temp = pd.read_csv('sub' +str(x)+'_ICA_thre.csv' )
    df = pd.concat([Y, temp])  # concat the obtained frame with the empty frame
    df.columns = ['id', 'data', 'isEB', 'isEM']
    #  replace the column values using subject id
         for sub in range(1,15):
           df['id'].replace(sub, 'sub' +str(x)+'_ICA_'+str(sub) ,inplace=True)
    print (df)
</code>```

output:

```<code>                id  data  isEB  isEM
   0    sub1_ICA_2   200     0     0
   1    sub1_ICA_3   275     0     0
   2    sub1_ICA_4   500     1     0
   ................................
   11  sub1_ICA_13   275     0     0
   12  sub1_ICA_14   300     0     0
                id  data  isEB  isEM
   0    sub2_ICA_2   275     0     0
   1    sub2_ICA_3   500     0     0
   2    sub2_ICA_4   400     0     0
   .................................
   11  sub2_ICA_13   300     0     0
   12  sub2_ICA_14   450     0     0
</code>```

First, it seems that the code makes different dataFrame not a single one.Second,  the first row is removed (sub1_ICA_1 is missing, may be replaced with column names).
I couldn't find the problem in the loop that I am using

答:
I think you need create list of DataFrames first, then concat with parameter keys for new values by range in MultiIndex, then modify column id and last remove MultiIndex by reset_index:

Also was added parameter names to read_csv for custom columns names.

```<code>Y = []
for x in S_Sub_list:
    n = ['id', 'data', 'isEB', 'isEM']
    temp = pd.read_csv('sub' + str(x) +'_ICA_thre.csv', names = n)
    Y.append(temp)

#list comprehension alternative
#n = ['id', 'data', 'isEB', 'isEM']
#Y = [pd.read_csv('sub' + str(x) +'_ICA_thre.csv', names = n) for x in S_Sub_list]

df = pd.concat(Y, keys=range(1,len(S_Sub_list) + 1))

df['id'] = 'sub' + df.index.get_level_values(0).astype(str) +'_ICA_'+ df['id'].astype(str)
df = df.reset_index(drop=True)
</code>```

Body:
I have multiple csv files with the same format (14 rows 4 columns).
I tried to load all of them into a single dataFrame, and use file's name to rename the values of the first column (1-14)

    1   500 0   0
    2   350 0   1
    3   500 1   0
    .............
    13  600 0   0
    14  800 0   0

I tried the following code but I am not getting what I am expecting:

    filenames = os.listdir('Threshold/')
    Y = pd.DataFrame () #empty df
    # file name are in the following foramt "subx_ICA_thre.csv"
    # need to get x (subject number to be used later for renaming columns values)
    Sub_list=[]
    for filename in filenames:
    s= int(''.join(filter(str.isdigit, filename)))
    Sub_list.append(int(s))
    S_Sub_list= sorted(Sub_list)

    for x in S_Sub_list: # get the file according to the subject number
    temp = pd.read_csv('sub' +str(x)+'_ICA_thre.csv' )
    df = pd.concat([Y, temp])  # concat the obtained frame with the empty frame
    df.columns = ['id', 'data', 'isEB', 'isEM']
    #  replace the column values using subject id
         for sub in range(1,15):
           df['id'].replace(sub, 'sub' +str(x)+'_ICA_'+str(sub) ,inplace=True)
    print (df)

output:

                id  data  isEB  isEM
   0    sub1_ICA_2   200     0     0
   1    sub1_ICA_3   275     0     0
   2    sub1_ICA_4   500     1     0
   ................................
   11  sub1_ICA_13   275     0     0
   12  sub1_ICA_14   300     0     0
                id  data  isEB  isEM
   0    sub2_ICA_2   275     0     0
   1    sub2_ICA_3   500     0     0
   2    sub2_ICA_4   400     0     0
   .................................
   11  sub2_ICA_13   300     0     0
   12  sub2_ICA_14   450     0     0

First, it seems that the code makes different dataFrame not a single one.Second,  the first row is removed (sub1_ICA_1 is missing, may be replaced with column names).
I couldn't find the problem in the loop that I am using

Body:
I think you need create list of DataFrames first, then concat with parameter keys for new values by range in MultiIndex, then modify column id and last remove MultiIndex by reset_index:

Also was added parameter names to read_csv for custom columns names.

Y = []
for x in S_Sub_list:
    n = ['id', 'data', 'isEB', 'isEM']
    temp = pd.read_csv('sub' + str(x) +'_ICA_thre.csv', names = n)
    Y.append(temp)

#list comprehension alternative
#n = ['id', 'data', 'isEB', 'isEM']
#Y = [pd.read_csv('sub' + str(x) +'_ICA_thre.csv', names = n) for x in S_Sub_list]

df = pd.concat(Y, keys=range(1,len(S_Sub_list) + 1))

df['id'] = 'sub' + df.index.get_level_values(0).astype(str) +'_ICA_'+ df['id'].astype(str)
df = df.reset_index(drop=True)


问:
Trouble in Controller Query foreach loop in laravel
Hello Again everyone,

can anyone help me with this code.

```<code>public function submitranking(Request $req){
    $dataCandidate = Candidate::all();

    foreach($dataCandidate as $Candidate){
        $judgeRate = Score::where('canId',$Candidate->id )
        ->where('catId',$req->catId )
        ->where('judgeId',$req->judgeId)
        ->sum('score');
        dd($judgeRate);
    }

}
</code>```

It is supposed to display all the scores of the candidates when I dd($judgeRate) it only display one record? How can I make it loop and display all the total sum scores of the candidates... Please help

答:
You can use pluck function to get all ids of candidates and use whereIn.

So, there is no need to use loop, use group by and simple raw query.

Just change your function like,

```<code>public function submitranking(Request $req){

    $dataCandidate = Candidate::all()->pluck('canId');

    $judgeRate = Score::whereIn('canId',$dataCandidate)
                 ->where('catId',$req->catId )
                 ->where('judgeId',$req->judgeId)
                 ->select('catId',DB::raw('COUNT(score) as total_score'))
                 ->groupBy('catId')
                 ->get();
    dd($judgeRate);
}
</code>```

You can see docs here: https://laravel.com/docs/5.5/queries#where-clauses

Hope you understand.

Body:
Hello Again everyone,

can anyone help me with this code.

public function submitranking(Request $req){
    $dataCandidate = Candidate::all();

    foreach($dataCandidate as $Candidate){
        $judgeRate = Score::where('canId',$Candidate->id )
        ->where('catId',$req->catId )
        ->where('judgeId',$req->judgeId)
        ->sum('score');
        dd($judgeRate);
    }

}

It is supposed to display all the scores of the candidates when I dd($judgeRate) it only display one record? How can I make it loop and display all the total sum scores of the candidates... Please help

Body:
You can use pluck function to get all ids of candidates and use whereIn.

So, there is no need to use loop, use group by and simple raw query.

Just change your function like,

public function submitranking(Request $req){

    $dataCandidate = Candidate::all()->pluck('canId');

    $judgeRate = Score::whereIn('canId',$dataCandidate)
                 ->where('catId',$req->catId )
                 ->where('judgeId',$req->judgeId)
                 ->select('catId',DB::raw('COUNT(score) as total_score'))
                 ->groupBy('catId')
                 ->get();
    dd($judgeRate);
}

You can see docs here: https://laravel.com/docs/5.5/queries#where-clauses

Hope you understand.


问:
How to set Validation for all controls in a user control?
I am looking for the best way to set the validation group for all of the controls contained in a user control.  Most of the controls in the control are created dynamically when the control is loaded.  It has quite a few input fields and validators.

I would like to save time by setting the validation for all the controls and validators with some sort of function that could just loop through everything and set it.

It seems though that there is no consistent interface that includes validation group for all of the different controls that have the property.

Should I use reflection to check for Validation group, I know I can do this, but is there a better way?

We are using C# by the way.

Any help would be appreciated.  Thanks!

EDIT:  I put the answer down below for anyone who wants the code.

答:
Just wanted to mark this answered.

Here is the code I used to set the validation group.  I decided to go with using reflection, since I could check types for those I know have ValidationGroup, and cast and set, but there are a lot of types to check, and it could miss new controls that may be added in the future.  Would have been sweet if the ValidationGroup were part of some kind of interface that things had to implement.

```<code>/// <summary>
/// this is an extension method to iterate though all controls in a control collection
/// put this in some static library somewhere
/// </summary>
/// <param name="controls"></param>
/// <returns></returns>
public static IEnumerable<Control> All(this ControlCollection controls)
{
    foreach (Control control in controls)
    {
        foreach (Control grandChild in control.Controls.All())
            yield return grandChild;

        yield return control;
    }
}

/// <summary>
/// this function uses reflection to check if the validation group exists, and then set it to the
/// specified string
/// </summary>
/// <param name="ValidationGroup"></param>
private void SetValidationGroup(string ValidationGroup)
{
    //set the validation group for all controls
    if (ValidationGroup.IsNotNullOrEmpty())
    {
        foreach (Control c in Controls.All())
        {
            var Properties = c.GetType().GetProperties();
            var vg = Properties.Where(p => p.Name == "ValidationGroup").SingleOrDefault();
            if (vg != null)
            {
                vg.SetValue(c, ValidationGroup, null);
            }

        }

    }
}
</code>```

Body:
Just wanted to mark this answered.

Here is the code I used to set the validation group.  I decided to go with using reflection, since I could check types for those I know have ValidationGroup, and cast and set, but there are a lot of types to check, and it could miss new controls that may be added in the future.  Would have been sweet if the ValidationGroup were part of some kind of interface that things had to implement.

/// <summary>
/// this is an extension method to iterate though all controls in a control collection
/// put this in some static library somewhere
/// </summary>
/// <param name="controls"></param>
/// <returns></returns>
public static IEnumerable<Control> All(this ControlCollection controls)
{
    foreach (Control control in controls)
    {
        foreach (Control grandChild in control.Controls.All())
            yield return grandChild;

        yield return control;
    }
}

/// <summary>
/// this function uses reflection to check if the validation group exists, and then set it to the
/// specified string
/// </summary>
/// <param name="ValidationGroup"></param>
private void SetValidationGroup(string ValidationGroup)
{
    //set the validation group for all controls
    if (ValidationGroup.IsNotNullOrEmpty())
    {
        foreach (Control c in Controls.All())
        {
            var Properties = c.GetType().GetProperties();
            var vg = Properties.Where(p => p.Name == "ValidationGroup").SingleOrDefault();
            if (vg != null)
            {
                vg.SetValue(c, ValidationGroup, null);
            }

        }

    }
}


问:
Angular filter with multiple dropdown
I am trying to filter with multiple dropdowns.
For example, when narrowing down by two numbers of value and num, there is no corresponding data when searching with "value = 1, num = 5", but data of "id = '000'" is displayed It will result.
Where should I fix it?

plunker:http://plnkr.co/edit/IBRDuHYtSCUFV1xNxjh4?p=preview

HTML

```<code><body ng-controller="MainCtrl">
<div>
    <div>
        <div>
            <span>value</span>
            <select class="form-control" ng-model="value_1">
                <option ng-repeat="value in product_value" value="{{value}}">{{value}}</option>
            </select>
            <span>num</span>
            <select class="form-control" ng-model="num_1">
                <option ng-repeat="num in product_num" value="{{num}}">{{num}}</option>
            </select>
        </div>
        <div>
            <span>value</span>
            <select class="form-control" ng-model="value_2">
                <option ng-repeat="value in product_value" value="{{value}}">{{value}}</option>
            </select>
            <span>num</span>
            <select class="form-control" ng-model="num_2">
                <option ng-repeat="num in product_num" value="{{num}}">{{num}}</option>
            </select>
        </div>
    </div>
      <table>
        <tr>
          <th>
            id
          </th>
          <th>
            name
          </th>
        </tr>
        <tr ng-repeat="products in products | filter:{main:{value:value_1}} | filter:{main:{num:num_1}} |
         filter:{main:{value:value_2}} | filter:{main:{num:num_2}}">
          <td>{{products.id}}</td>
          <td>{{products.name}}</td>
        </tr>
      </table>
</div>
</code>```

JS

```<code>var app = angular.module('TestMode', []);

app.controller('MainCtrl', function($scope, $filter) {
  $scope.product_value = ["1", "2", "3", "4", "5"];
  $scope.product_num = ["1", "2", "3", "4", "5"];
  $scope.products = [
      {
        id: "000",
        name:'A',
        main:[
            {
              value: "1",
              num: "1"
            },{
              value: "1",
              num: "2"
            },{
              value: "1",
              num: "3"
            },{
              value: "2",
              num: "4"
            },{
              value: "2",
              num: "5"
            }
        ]
      },{
        id: "001",
        name:'B',
        main:[
            {
              value: "5",
              num: "5"
            },{
              value: "5",
              num: "4"
            },{
              value: "5",
              num: "3"
            },{
              value: "4",
              num: "2"
            },{
              value: "4",
              num: "1"
            }
        ]
      }
    ];

});
</code>```

答:
Change products to product.

Always filter by 2 properties instead of 1.

```<code><tr ng-repeat="product in products | filter:{main:{value:value_1,num:num_1}} | filter:{main:{value:value_1,num:num_1}}">
  <td>{{product.id}}</td>
  <td>{{product.name}}</td>
</tr>
</code>```

http://plnkr.co/edit/VXz8h5y8273rgHL7uMgS?p=preview

Title: Angular filter with multiple dropdown

Body:
I am trying to filter with multiple dropdowns.
For example, when narrowing down by two numbers of value and num, there is no corresponding data when searching with "value = 1, num = 5", but data of "id = '000'" is displayed It will result.
Where should I fix it?

plunker:http://plnkr.co/edit/IBRDuHYtSCUFV1xNxjh4?p=preview

HTML

            value
            <select class="form-control" ng-model="value_1">
                <option ng-repeat="value in product_value" value="{{value}}">{{value}}</option>
            </select>
            num
            <select class="form-control" ng-model="num_1">
                <option ng-repeat="num in product_num" value="{{num}}">{{num}}</option>
            </select>

            value
            <select class="form-control" ng-model="value_2">
                <option ng-repeat="value in product_value" value="{{value}}">{{value}}</option>
            </select>
            num
            <select class="form-control" ng-model="num_2">
                <option ng-repeat="num in product_num" value="{{num}}">{{num}}</option>
            </select>

            id

            name

          {{products.id}}
          {{products.name}}

JS

var app = angular.module('TestMode', []);

app.controller('MainCtrl', function($scope, $filter) {
  $scope.product_value = ["1", "2", "3", "4", "5"];
  $scope.product_num = ["1", "2", "3", "4", "5"];
  $scope.products = [
      {
        id: "000",
        name:'A',
        main:[
            {
              value: "1",
              num: "1"
            },{
              value: "1",
              num: "2"
            },{
              value: "1",
              num: "3"
            },{
              value: "2",
              num: "4"
            },{
              value: "2",
              num: "5"
            }
        ]
      },{
        id: "001",
        name:'B',
        main:[
            {
              value: "5",
              num: "5"
            },{
              value: "5",
              num: "4"
            },{
              value: "5",
              num: "3"
            },{
              value: "4",
              num: "2"
            },{
              value: "4",
              num: "1"
            }
        ]
      }
    ];

});

Body:
Change products to product.

Always filter by 2 properties instead of 1.

<tr ng-repeat="product in products | filter:{main:{value:value_1,num:num_1}} | filter:{main:{value:value_1,num:num_1}}">
  <td>{{product.id}}</td>
  <td>{{product.name}}</td>
</tr>

http://plnkr.co/edit/VXz8h5y8273rgHL7uMgS?p=preview


问:
Add filter on column which subtract to columns
i have long store procedure in whcih i want Add filter on this Column

```<code>select (PaymentAmount-PaymentPosted) as Unapplied, BalancDue from ERAMaster
 where Unapplied = 22
</code>```

but i run the query they give me error invalid column name. any one tell me the write way to Add filter on Unapplied Column

答:
It should be like this:

```<code>select (PaymentAmount-PaymentPosted) as Unapplied, BalancDue from ERAMaster
 where (PaymentAmount-PaymentPosted) = 22
</code>```

'Unapplied' is not a column name it is only alias.

Body:
i have long store procedure in whcih i want Add filter on this Column

select (PaymentAmount-PaymentPosted) as Unapplied, BalancDue from ERAMaster
 where Unapplied = 22

but i run the query they give me error invalid column name. any one tell me the write way to Add filter on Unapplied Column

Body:
It should be like this:

select (PaymentAmount-PaymentPosted) as Unapplied, BalancDue from ERAMaster
 where (PaymentAmount-PaymentPosted) = 22

'Unapplied' is not a column name it is only alias.


问:
Convert specific number of rows to columns in R and repeat the process for a large dataset
I'm having a dataset of 15 million rows with single column. It looks like,

```<code>x_raw
A1
A2
A3
A4
B1
B2
B3
B4
C1
C2

I want to convert it to

A1 A2 A3 A4
B1 B2 B3 B4
C1 C2 C3 C4
</code>```

I was trying with 'for' loop, that will transpose every 4 rows, and add them to a 'final' dataframe, but as the dataset is too large, it'll iterate almost 2.7 million times which is not working that efficiently. Is there any other method or anything that I can use to do it efficiently?

答:
if you just want to convert to a four column data frame:</p>

```<code>as.data.frame(matrix(df$x_raw,ncol=4,byrow = T))
</code>```

Body:
I'm having a dataset of 15 million rows with single column. It looks like,

x_raw
A1
A2
A3
A4
B1
B2
B3
B4
C1
C2

I want to convert it to

A1 A2 A3 A4
B1 B2 B3 B4
C1 C2 C3 C4

I was trying with 'for' loop, that will transpose every 4 rows, and add them to a 'final' dataframe, but as the dataset is too large, it'll iterate almost 2.7 million times which is not working that efficiently. Is there any other method or anything that I can use to do it efficiently?

Body:
if you just want to convert to a four column data frame:

as.data.frame(matrix(df$x_raw,ncol=4,byrow = T))


问:
Move multiple files and sub directories into single directory bat
I'm trying to move everything (every folder and file) in 'test' to 'test2' with a bat script.

This works only for folders, i need it to copy files aswell.

for /D %%D in ("C:\directory\*.*") do (
        move "%%~D" "D:\directory"
)
```

I also cant use xcopy/robocopy as I need to move not copy.

Any help would be appreciated.

答:
this seems to work.
first command moves only files, second moves only folders. </p>

<pre class="lang-dos prettyprint-override"><code> move C:\test\1\* C:\test\2
    for /D %%D in ("C:\test\1\*") do (
            echo %%~D
            move "%%~D" "C:\test\2"
        )
</code>```

Body:
I'm trying to move everything (every folder and file) in 'test' to 'test2' with a bat script.

This works only for folders, i need it to copy files aswell.

for /D %%D in ("C:\directory\*.*") do (
        move "%%~D" "D:\directory"
)

I also cant use xcopy/robocopy as I need to move not copy.

Any help would be appreciated.

Body:
this seems to work.
first command moves only files, second moves only folders.

 move C:\test\1\* C:\test\2
    for /D %%D in ("C:\test\1\*") do (
            echo %%~D
            move "%%~D" "C:\test\2"
        )