问:
Div with nowrap still wraps
I want to make the div stay the same size while I resize the window.
My css for the div:

```<code>.header {
    white-space: nowrap;
    color: #fff;
    padding: 0.5em;
    background: linear-gradient(90deg, #B71C1C, #0D47A1, #0D47A1);
  }
</code>```

and here is the output before the wrap:

and after the wrap:

what I want is to header div always stay the same size no matter the browser's width.

答: I think the white-space: nowrap property is used to stop text from wrapping. In your case you might want to set a fixed width for that div so that it will not change based on the window size.

Title: Div with nowrap still wraps

Body:
I want to make the div stay the same size while I resize the window.
My css for the div:

.header {
    white-space: nowrap;
    color: #fff;
    padding: 0.5em;
    background: linear-gradient(90deg, #B71C1C, #0D47A1, #0D47A1);
  }

and here is the output before the wrap:

and after the wrap:

what I want is to header div always stay the same size no matter the browser's width.


来源: stackexchange

问:
Angular2 error after updating to Typescript 2.1
I have just uploaded my Angular2 project to the latest version of Typescript (from 2.0.3 to 2.1.4).
When launching my app I do get the following error :

```<code>zone.js:242 Error: (SystemJS) Unexpected token ;
    SyntaxError: Unexpected token ;
        at eval (<anonymous>)
        at ZoneDelegate.invoke (http://localhost:9000/assets/lib/zone.js/dist/zone.js:242:26)
        at Zone.run (http://localhost:9000/assets/lib/zone.js/dist/zone.js:113:43)
        at http://localhost:9000/assets/lib/zone.js/dist/zone.js:520:57
        at ZoneDelegate.invokeTask (http://localhost:9000/assets/lib/zone.js/dist/zone.js:275:35)
        at Zone.runTask (http://localhost:9000/assets/lib/zone.js/dist/zone.js:151:47)
        at drainMicroTaskQueue (http://localhost:9000/assets/lib/zone.js/dist/zone.js:418:35)
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:9000/assets/lib/zone.js/dist/zone.js:349:25)
    Evaluating http://localhost:9000/assets/lib/angular__platform-browser-dynamic/index.js
    Error loading http://localhost:9000/assets/lib/angular__platform-browser-dynamic/index.js as "@angular/platform-browser-dynamic" from http://localhost:9000/assets/app/bootstrap.ts
        at eval (<anonymous>)
        at ZoneDelegate.invoke (http://localhost:9000/assets/lib/zone.js/dist/zone.js:242:26)
        at Zone.run (http://localhost:9000/assets/lib/zone.js/dist/zone.js:113:43)
        at http://localhost:9000/assets/lib/zone.js/dist/zone.js:520:57
        at ZoneDelegate.invokeTask (http://localhost:9000/assets/lib/zone.js/dist/zone.js:275:35)
        at Zone.runTask (http://localhost:9000/assets/lib/zone.js/dist/zone.js:151:47)
        at drainMicroTaskQueue (http://localhost:9000/assets/lib/zone.js/dist/zone.js:418:35)
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:9000/assets/lib/zone.js/dist/zone.js:349:25)
    Evaluating http://localhost:9000/assets/lib/angular__platform-browser-dynamic/index.js
    Error loading http://localhost:9000/assets/lib/angular__platform-browser-dynamic/index.js as "@angular/platform-browser-dynamic" from http://localhost:9000/assets/app/bootstrap.ts
</code>```

I have no idea what's wrong here though

EDIT:
My bootstrap.ts file

```<code>import { enableProdMode } from '@angular/core'
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'
import { AppModule } from './app.module'

// enableProdMode()
platformBrowserDynamic().bootstrapModule(AppModule)
</code>```

答:
I received this error after updating Typescript (from 2.0.3 to 2.1.4).

The error was caused by some commented out code at the bottom of the .ts file. I was able to see the syntax error in the .js file that it was transpiled to.

Removing the commented out code from the bottom of the affected .ts file fixed the issue for me.

ContentLicense: CC BY-SA 3.0

Body:
I have just uploaded my Angular2 project to the latest version of Typescript (from 2.0.3 to 2.1.4).
When launching my app I do get the following error :

zone.js:242 Error: (SystemJS) Unexpected token ;
    SyntaxError: Unexpected token ;
        at eval (<anonymous>)
        at ZoneDelegate.invoke (http://localhost:9000/assets/lib/zone.js/dist/zone.js:242:26)
        at Zone.run (http://localhost:9000/assets/lib/zone.js/dist/zone.js:113:43)
        at http://localhost:9000/assets/lib/zone.js/dist/zone.js:520:57
        at ZoneDelegate.invokeTask (http://localhost:9000/assets/lib/zone.js/dist/zone.js:275:35)
        at Zone.runTask (http://localhost:9000/assets/lib/zone.js/dist/zone.js:151:47)
        at drainMicroTaskQueue (http://localhost:9000/assets/lib/zone.js/dist/zone.js:418:35)
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:9000/assets/lib/zone.js/dist/zone.js:349:25)
    Evaluating http://localhost:9000/assets/lib/angular__platform-browser-dynamic/index.js
    Error loading http://localhost:9000/assets/lib/angular__platform-browser-dynamic/index.js as "@angular/platform-browser-dynamic" from http://localhost:9000/assets/app/bootstrap.ts
        at eval (<anonymous>)
        at ZoneDelegate.invoke (http://localhost:9000/assets/lib/zone.js/dist/zone.js:242:26)
        at Zone.run (http://localhost:9000/assets/lib/zone.js/dist/zone.js:113:43)
        at http://localhost:9000/assets/lib/zone.js/dist/zone.js:520:57
        at ZoneDelegate.invokeTask (http://localhost:9000/assets/lib/zone.js/dist/zone.js:275:35)
        at Zone.runTask (http://localhost:9000/assets/lib/zone.js/dist/zone.js:151:47)
        at drainMicroTaskQueue (http://localhost:9000/assets/lib/zone.js/dist/zone.js:418:35)
        at XMLHttpRequest.ZoneTask.invoke (http://localhost:9000/assets/lib/zone.js/dist/zone.js:349:25)
    Evaluating http://localhost:9000/assets/lib/angular__platform-browser-dynamic/index.js
    Error loading http://localhost:9000/assets/lib/angular__platform-browser-dynamic/index.js as "@angular/platform-browser-dynamic" from http://localhost:9000/assets/app/bootstrap.ts

I have no idea what's wrong here though

EDIT:
My bootstrap.ts file

import { enableProdMode } from '@angular/core'
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'
import { AppModule } from './app.module'

// enableProdMode()
platformBrowserDynamic().bootstrapModule(AppModule)


问:
Finding the max value in an array, however being less than the first number in the array
I need to find out how to find the max value in an array, being less than the first index of the array. So far, I have only found out how to find the maximum value in my array (shown below), but I need help only returning the max value less than the first number in my array from my method.

```<code>public static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {

if (endIndex == startIndex) {

    return numbers[endIndex];

}

else {

    int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);   //Calling method using recursion.

    if (max < numbers[endIndex]) {

        return numbers[endIndex];

    }

    else {

        return max;

    }

}
</code>```

}

答:
Seems like a recursive method is way overkill.

```<code>int maxLessThanFirst( int[] arr ) {
   int max = Integ3er.MIN_VALUE;
   for ( int i=1; i < arr.length; i++ ) {
      if ( arr[i] < arr[0] ) {
         <Do normal max value check here>
      }
   }
   return max;
}
</code>```

Note that after the loop, if max=MIN_VALUE you need to have a check that there was at least one value < arr[0] (for example, if all other values are MIN_VALUE, the maximum is MIN_VALUE. If all other values are >= arr[0], you need to throw an exception to show that there is no solution.

Body:
I need to find out how to find the max value in an array, being less than the first index of the array. So far, I have only found out how to find the maximum value in my array (shown below), but I need help only returning the max value less than the first number in my array from my method.

public static int findMaxOfLessThanFirst(int[] numbers, int startIndex, int endIndex, int firstNumber) {

if (endIndex == startIndex) {

    return numbers[endIndex];

}

else {

    int max = findMaxOfLessThanFirst(numbers, startIndex, endIndex - 1, firstNumber);   //Calling method using recursion.

    if (max < numbers[endIndex]) {

        return numbers[endIndex];

    }

    else {

        return max;

    }

}

}

Body:
Seems like a recursive method is way overkill.

int maxLessThanFirst( int[] arr ) {
   int max = Integ3er.MIN_VALUE;
   for ( int i=1; i < arr.length; i++ ) {
      if ( arr[i] < arr[0] ) {
         <Do normal max value check here>
      }
   }
   return max;
}

Note that after the loop, if max=MIN_VALUE you need to have a check that there was at least one value < arr[0] (for example, if all other values are MIN_VALUE, the maximum is MIN_VALUE. If all other values are >= arr[0], you need to throw an exception to show that there is no solution.


问:
C# - Splitting the string when there are 3 chars and adding the values to the dictionary
I have a string like this:

```<code>var totalOrders = "Beans - 1\nMeat balls - 1\nBrown bread - 2\nBeans - 2\nBanana slice - 1\nSteak with rice - 1\nBrown bread - 1\n";
</code>```

It's dynamically created, so this one is just for the sake of example. Numbers represent how many portions are ordered. I need to split it to dictionary by the name of food as a key and count how many portions are ordered which would be a value.

I've tried this for spliting the string, first by '\n' then by ' - ':

```<code>count = totalOrders.Split('\n').ToDictionary(item => item.Split(" - ")[0], item => int.Parse(item.Split(" - ")[1]));
</code>```

but I get an error "cannot convert from string to char. I had to use double quotes, because " - " this has 3 chars (2 spaces and a dash) and it's not recognized as a char.

Also, I think the problem will be when I start adding food, because it will report that keys won't be unique, considering that food appears more than once. How to solve this?

EDIT:

When I try this:

```<code>string[] countOrders = totalOrders.Split('\n');
string[] parts1 = countOrders.Split(new string[] { " - " }, StringSplitOptions.None);
</code>```

I get error at .Split

```<code>'string[]' does not contain a definition for 'Split' and no extension method 'Split' accepting a first argument of type 'string[]' could be found
</code>```

and if I try this "string countOrders =" (so without []) I get

```<code>Cannot implicitly convert type 'string[]' to 'string'
</code>```

I don't understand how am I suppose to split the string by '\n' and then to split it by " - ", when it gives me errors in both cases?

答:
Here is a non linq option since it was requested by the OP, I for one would prefer the linq way however this yeilds the same result</p>

```<code> var totalOrders = "Beans - 1\nMeat balls - 1\nBrown bread - 2\nBeans - 2\nBanana slice - 1\nSteak with rice - 1\nBrown bread - 1\n";
 var DictionaryHolder = new Dictionary<string, int>();
 //Split initial string into array and remove empties
 string[] initialArray = totalOrders.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

        foreach (var item in initialArray)
        {
            // Get the string Key or Entree
            string key = item.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries)[0].Trim();
            //  Get the Count of Portions
            int count = int.Parse(item.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries)[1].Trim());

            // check if Dictionary has the key already if not add it
            if (!DictionaryHolder.ContainsKey(key))
            {
                DictionaryHolder.Add(key, count);
            }
            else
            {
                // If the dictionary already had that key increase portion count by amount ordered.
                DictionaryHolder[key] = DictionaryHolder[key] + count;
            }
        }
</code>```

Body:
I have a string like this:

var totalOrders = "Beans - 1\nMeat balls - 1\nBrown bread - 2\nBeans - 2\nBanana slice - 1\nSteak with rice - 1\nBrown bread - 1\n";

It's dynamically created, so this one is just for the sake of example. Numbers represent how many portions are ordered. I need to split it to dictionary by the name of food as a key and count how many portions are ordered which would be a value.

I've tried this for spliting the string, first by '\n' then by ' - ':

count = totalOrders.Split('\n').ToDictionary(item => item.Split(" - ")[0], item => int.Parse(item.Split(" - ")[1]));

but I get an error "cannot convert from string to char. I had to use double quotes, because " - " this has 3 chars (2 spaces and a dash) and it's not recognized as a char.

Also, I think the problem will be when I start adding food, because it will report that keys won't be unique, considering that food appears more than once. How to solve this?

EDIT:

When I try this:

string[] countOrders = totalOrders.Split('\n');
string[] parts1 = countOrders.Split(new string[] { " - " }, StringSplitOptions.None);

I get error at .Split

'string[]' does not contain a definition for 'Split' and no extension method 'Split' accepting a first argument of type 'string[]' could be found

and if I try this "string countOrders =" (so without []) I get

Cannot implicitly convert type 'string[]' to 'string'

I don't understand how am I suppose to split the string by '\n' and then to split it by " - ", when it gives me errors in both cases?

Body:
Here is a non linq option since it was requested by the OP, I for one would prefer the linq way however this yeilds the same result

 var totalOrders = "Beans - 1\nMeat balls - 1\nBrown bread - 2\nBeans - 2\nBanana slice - 1\nSteak with rice - 1\nBrown bread - 1\n";
 var DictionaryHolder = new Dictionary<string, int>();
 //Split initial string into array and remove empties
 string[] initialArray = totalOrders.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

        foreach (var item in initialArray)
        {
            // Get the string Key or Entree
            string key = item.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries)[0].Trim();
            //  Get the Count of Portions
            int count = int.Parse(item.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries)[1].Trim());

            // check if Dictionary has the key already if not add it
            if (!DictionaryHolder.ContainsKey(key))
            {
                DictionaryHolder.Add(key, count);
            }
            else
            {
                // If the dictionary already had that key increase portion count by amount ordered.
                DictionaryHolder[key] = DictionaryHolder[key] + count;
            }
        }


问:
Random Access in Array
I was reading this, advantages of java, where it states that random access is an advantage of arrays in java. I do not understand how can accessing a random element of an array is an advantage. Shouldn't it be a disadvantage?

Why is java allowing to access elements of an array randomly, if the data is stored continuously, shouldn't the data be accessed in an orderly manner?

答:
Random(direct) access implies the ability to access any entry in a array in constant time (independent of its position in the array and of array's size). And that is big advantage.

It is typically contrasted to sequential access. Datastructure has sequential access if we can only visit the values it contains in one particular order.

Title: Random Access in Array


问:
Generate ID on before insert trigger
I'm having trouble with AUTO_INCREMENT of a table so I created a trigger to try to solve the problem

```<code>CREATE DEFINER=`medplantoes01`@`%` TRIGGER `medplantoes01`.`MEDICO_BEFORE_INSERT` BEFORE INSERT ON `MEDICO` FOR EACH ROW
BEGIN
   SET NEW.id_medico = (select max(id_medico) + 1 from MEDICO);
END
</code>```

But I'm getting this message when inserting:

Error Number: 1062 Duplicate entry '0' for key 'PRIMARY'

AUTO_INCREMENT option is unchecked on column ID_MEDICO but even with this option I get the same message.

using MySQL 5.7

PS: sorry for my english :P

答:
OK, I don't speak portuguese, but I can decode this...

```<code>NEW.id_medico = (select max(id_medico) + 1 from MEDICO);
</code>```

This will not work. If two clients attempt insert at the same time, they will get duplicate id. This is a very, very bad idea. Don't do this.

AUTO_INCREMENT is designed to solve this problem. Use it. You say it does not work: explain how.

In English......

Title: Generate ID on before insert trigger

Body:
I'm having trouble with AUTO_INCREMENT of a table so I created a trigger to try to solve the problem

CREATE DEFINER=`medplantoes01`@`%` TRIGGER `medplantoes01`.`MEDICO_BEFORE_INSERT` BEFORE INSERT ON `MEDICO` FOR EACH ROW
BEGIN
   SET NEW.id_medico = (select max(id_medico) + 1 from MEDICO);
END

But I'm getting this message when inserting:

Error Number: 1062 Duplicate entry '0' for key 'PRIMARY'

AUTO_INCREMENT option is unchecked on column ID_MEDICO but even with this option I get the same message.

using MySQL 5.7

PS: sorry for my english :P

Body:
OK, I don't speak portuguese, but I can decode this...

NEW.id_medico = (select max(id_medico) + 1 from MEDICO);

This will not work. If two clients attempt insert at the same time, they will get duplicate id. This is a very, very bad idea. Don't do this.

AUTO_INCREMENT is designed to solve this problem. Use it. You say it does not work: explain how.

In English......


问:
Delete[] operator makes *.exe trigger a breakpoint and wntdll.pdb not loaded to appear
Delete[]fName in decode() causes this error, delete in encode() works fine. Without that delete, each new call of decode() results in 1 more MB wasted, which is expected, buy why adding delete causes crash there, but not in encode() ? MAX_STRING_LENGTH constant is 1048576 (1 MB of chars)

```<code>  void encode()
    {
        char* usrChars = new char[MAX_STRING_LENGTH];
        memset(usrChars, 0, MAX_STRING_LENGTH);
        cin.get();
        cin.getline(usrChars, MAX_STRING_LENGTH);
        ofstream f("E:/fc/enc_test.txt");
        //do stuff
        f.close();
        delete[]usrChars; //works fine
        decode();
        cout << endl;
    }
    void decode()
    {
        char* fName = new char[MAX_STRING_LENGTH];
        memset(fName, 0, MAX_STRING_LENGTH);
        fName = "e:/fc/enc_test.txt";
        ifstream f(fName);
        delete[]fName; //causes crash
        //do stuff
    }
</code>```

答:
fName = "e:/fc/enc_test.txt"; causes fName to point to the location where the string literal "e:/fc/enc_test.txt" is stored. You then try to delete that location which was not allocated with new. You need to use std::strcpy to copy a c string. You can save yourself quite a bit of headache by using std::string instead.

```<code>#include <string>
#include <fstream>

void decode()
{
    std::string fName = "e:/fc/enc_test.txt";
    std::ifstream f(fName);
    // do stuff (no delete required for fName)
}
</code>```

Body:
Delete[]fName in decode() causes this error, delete in encode() works fine. Without that delete, each new call of decode() results in 1 more MB wasted, which is expected, buy why adding delete causes crash there, but not in encode() ? MAX_STRING_LENGTH constant is 1048576 (1 MB of chars)

  void encode()
    {
        char* usrChars = new char[MAX_STRING_LENGTH];
        memset(usrChars, 0, MAX_STRING_LENGTH);
        cin.get();
        cin.getline(usrChars, MAX_STRING_LENGTH);
        ofstream f("E:/fc/enc_test.txt");
        //do stuff
        f.close();
        delete[]usrChars; //works fine
        decode();
        cout << endl;
    }
    void decode()
    {
        char* fName = new char[MAX_STRING_LENGTH];
        memset(fName, 0, MAX_STRING_LENGTH);
        fName = "e:/fc/enc_test.txt";
        ifstream f(fName);
        delete[]fName; //causes crash
        //do stuff
    }

Body:
fName = "e:/fc/enc_test.txt"; causes fName to point to the location where the string literal "e:/fc/enc_test.txt" is stored. You then try to delete that location which was not allocated with new. You need to use std::strcpy to copy a c string. You can save yourself quite a bit of headache by using std::string instead.

#include <string>
#include <fstream>

void decode()
{
    std::string fName = "e:/fc/enc_test.txt";
    std::ifstream f(fName);
    // do stuff (no delete required for fName)
}


问:
Scrollview not scrolling
I'm using a scroll view which is having only one child linearlayout.
Linearlayout contains listview and some other items also, but only listview is scrolling. what should i do ?
Here is my layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fresco="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/beco_white"
android:orientation="vertical">

<include layout="@layout/toolbar" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ViewSwitcher
            android:id="@+id/view_switcher"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white"
                android:orientation="horizontal">

                <Button
                    android:id="@+id/button_sign_in"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="@dimen/dp20"
                    android:background="@drawable/dark_blue_round_corner"
                    android:fontFamily="sans-serif-normal"
                    android:text="Login to beCo"
                    android:textAllCaps="false"
                    android:textColor="@android:color/white"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_sign_up"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="@dimen/dp20"
                    android:background="@drawable/customborder"
                    android:fontFamily="sans-serif-normal"
                    android:text="Create New Account"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent"
                    android:textSize="14sp" />

            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white">

                <com.facebook.drawee.view.SimpleDraweeView
                    android:id="@+id/image_profile"
                    android:layout_width="@dimen/dp88"
                    android:layout_height="@dimen/dp88"
                    android:layout_gravity="left"
                    android:layout_marginBottom="@dimen/dp10"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_marginTop="@dimen/dp10"
                    fresco:actualImageScaleType="centerCrop"
                    fresco:placeholderImage="@drawable/no_profile_pic"
                    fresco:roundAsCircle="true"
                    fresco:roundingBorderColor="@color/white"
                    fresco:roundingBorderWidth="@dimen/dp2" />

                <TextView
                    android:id="@+id/user_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="John Doe"
                    android:textColor="@android:color/black"
                    android:textSize="25sp" />

                <TextView
                    android:id="@+id/email"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/user_name"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toEndOf="@+id/image_profile"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="johndoe@mail.com"
                    android:textColor="@android:color/black"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_edit"
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_alignTop="@+id/image_profile"
                    android:background="@drawable/customborder"
                    android:text="Edit Profile"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent" />

            </RelativeLayout>

        </ViewSwitcher>

        <View
            android:layout_width="wrap_content"
            android:layout_height="1dp"
            android:background="@color/grey_200" />

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>
</ScrollView>
</LinearLayout>
</code>```

Any one please help me?

答:
Use NestedScrollView instead of ScrollView.

NestedScrollView is just like ScrollView, but it supports acting
  as both a nested scrolling parent and child on both new and old
  versions of Android.

See the Documentation

Update your XML as below:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/beco_white"
    android:orientation="vertical">

    <include layout="@layout/toolbar" />

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/layout_scorll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:descendantFocusability="blocksDescendants">

            <ViewSwitcher
                android:id="@+id/view_switcher"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="125dp"
                    android:background="@android:color/white"
                    android:orientation="horizontal">

                    <Button
                        android:id="@+id/button_sign_in"
                        android:layout_width="150dp"
                        android:layout_height="40dp"
                        android:layout_gravity="center"
                        android:layout_marginLeft="@dimen/dp20"
                        android:background="@drawable/dark_blue_round_corner"
                        android:fontFamily="sans-serif-normal"
                        android:text="Login to beCo"
                        android:textAllCaps="false"
                        android:textColor="@android:color/white"
                        android:textSize="14sp" />

                    <Button
                        android:id="@+id/button_sign_up"
                        android:layout_width="150dp"
                        android:layout_height="40dp"
                        android:layout_gravity="center"
                        android:layout_marginLeft="20dp"
                        android:layout_marginRight="@dimen/dp20"
                        android:background="@drawable/customborder"
                        android:fontFamily="sans-serif-normal"
                        android:text="Create New Account"
                        android:textAllCaps="false"
                        android:textColor="@color/colorAccent"
                        android:textSize="14sp" />

                </LinearLayout>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="125dp"
                    android:background="@android:color/white">

                    <com.facebook.drawee.view.SimpleDraweeView
                        android:id="@+id/image_profile"
                        android:layout_width="@dimen/dp88"
                        android:layout_height="@dimen/dp88"
                        android:layout_gravity="left"
                        android:layout_marginBottom="@dimen/dp10"
                        android:layout_marginLeft="@dimen/dp10"
                        android:layout_marginTop="@dimen/dp10"
                        fresco:actualImageScaleType="centerCrop"
                        fresco:placeholderImage="@drawable/no_profile_pic"
                        fresco:roundAsCircle="true"
                        fresco:roundingBorderColor="@color/white"
                        fresco:roundingBorderWidth="@dimen/dp2" />

                    <TextView
                        android:id="@+id/user_name"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_marginLeft="@dimen/dp10"
                        android:layout_toRightOf="@+id/image_profile"
                        android:fontFamily="sans-serif-normal"
                        android:text="John Doe"
                        android:textColor="@android:color/black"
                        android:textSize="25sp" />

                    <TextView
                        android:id="@+id/email"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/user_name"
                        android:layout_marginLeft="@dimen/dp10"
                        android:layout_toEndOf="@+id/image_profile"
                        android:layout_toRightOf="@+id/image_profile"
                        android:fontFamily="sans-serif-normal"
                        android:text="johndoe@mail.com"
                        android:textColor="@android:color/black"
                        android:textSize="14sp" />

                    <Button
                        android:id="@+id/button_edit"
                        android:layout_width="wrap_content"

                        android:layout_height="wrap_content"
                        android:layout_alignParentEnd="true"
                        android:layout_alignParentRight="true"
                        android:layout_alignTop="@+id/image_profile"
                        android:background="@drawable/customborder"
                        android:text="Edit Profile"
                        android:textAllCaps="false"
                        android:textColor="@color/colorAccent" />

                </RelativeLayout>

            </ViewSwitcher>

            <View
                android:layout_width="wrap_content"
                android:layout_height="1dp"
                android:background="@color/grey_200" />

            <ListView
                android:id="@+id/list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>
</LinearLayout>
</code>```

Title: Scrollview not scrolling

Body:
I'm using a scroll view which is having only one child linearlayout.
Linearlayout contains listview and some other items also, but only listview is scrolling. what should i do ?
Here is my layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fresco="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/beco_white"
android:orientation="vertical">

<include layout="@layout/toolbar" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ViewSwitcher
            android:id="@+id/view_switcher"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white"
                android:orientation="horizontal">

                <Button
                    android:id="@+id/button_sign_in"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="@dimen/dp20"
                    android:background="@drawable/dark_blue_round_corner"
                    android:fontFamily="sans-serif-normal"
                    android:text="Login to beCo"
                    android:textAllCaps="false"
                    android:textColor="@android:color/white"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_sign_up"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="@dimen/dp20"
                    android:background="@drawable/customborder"
                    android:fontFamily="sans-serif-normal"
                    android:text="Create New Account"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent"
                    android:textSize="14sp" />

            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white">

                <com.facebook.drawee.view.SimpleDraweeView
                    android:id="@+id/image_profile"
                    android:layout_width="@dimen/dp88"
                    android:layout_height="@dimen/dp88"
                    android:layout_gravity="left"
                    android:layout_marginBottom="@dimen/dp10"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_marginTop="@dimen/dp10"
                    fresco:actualImageScaleType="centerCrop"
                    fresco:placeholderImage="@drawable/no_profile_pic"
                    fresco:roundAsCircle="true"
                    fresco:roundingBorderColor="@color/white"
                    fresco:roundingBorderWidth="@dimen/dp2" />

                <TextView
                    android:id="@+id/user_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="John Doe"
                    android:textColor="@android:color/black"
                    android:textSize="25sp" />

                <TextView
                    android:id="@+id/email"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/user_name"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toEndOf="@+id/image_profile"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="johndoe@mail.com"
                    android:textColor="@android:color/black"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_edit"
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_alignTop="@+id/image_profile"
                    android:background="@drawable/customborder"
                    android:text="Edit Profile"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent" />

            </RelativeLayout>

        </ViewSwitcher>

        <View
            android:layout_width="wrap_content"
            android:layout_height="1dp"
            android:background="@color/grey_200" />

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>
</ScrollView>
</LinearLayout>

Any one please help me?

Body:
Use NestedScrollView instead of ScrollView.

NestedScrollView is just like ScrollView, but it supports acting
  as both a nested scrolling parent and child on both new and old
  versions of Android.

See the Documentation

Update your XML as below:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/beco_white"
    android:orientation="vertical">

    <include layout="@layout/toolbar" />

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/layout_scorll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:descendantFocusability="blocksDescendants">

            <ViewSwitcher
                android:id="@+id/view_switcher"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="125dp"
                    android:background="@android:color/white"
                    android:orientation="horizontal">

                    <Button
                        android:id="@+id/button_sign_in"
                        android:layout_width="150dp"
                        android:layout_height="40dp"
                        android:layout_gravity="center"
                        android:layout_marginLeft="@dimen/dp20"
                        android:background="@drawable/dark_blue_round_corner"
                        android:fontFamily="sans-serif-normal"
                        android:text="Login to beCo"
                        android:textAllCaps="false"
                        android:textColor="@android:color/white"
                        android:textSize="14sp" />

                    <Button
                        android:id="@+id/button_sign_up"
                        android:layout_width="150dp"
                        android:layout_height="40dp"
                        android:layout_gravity="center"
                        android:layout_marginLeft="20dp"
                        android:layout_marginRight="@dimen/dp20"
                        android:background="@drawable/customborder"
                        android:fontFamily="sans-serif-normal"
                        android:text="Create New Account"
                        android:textAllCaps="false"
                        android:textColor="@color/colorAccent"
                        android:textSize="14sp" />

                </LinearLayout>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="125dp"
                    android:background="@android:color/white">

                    <com.facebook.drawee.view.SimpleDraweeView
                        android:id="@+id/image_profile"
                        android:layout_width="@dimen/dp88"
                        android:layout_height="@dimen/dp88"
                        android:layout_gravity="left"
                        android:layout_marginBottom="@dimen/dp10"
                        android:layout_marginLeft="@dimen/dp10"
                        android:layout_marginTop="@dimen/dp10"
                        fresco:actualImageScaleType="centerCrop"
                        fresco:placeholderImage="@drawable/no_profile_pic"
                        fresco:roundAsCircle="true"
                        fresco:roundingBorderColor="@color/white"
                        fresco:roundingBorderWidth="@dimen/dp2" />

                    <TextView
                        android:id="@+id/user_name"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_marginLeft="@dimen/dp10"
                        android:layout_toRightOf="@+id/image_profile"
                        android:fontFamily="sans-serif-normal"
                        android:text="John Doe"
                        android:textColor="@android:color/black"
                        android:textSize="25sp" />

                    <TextView
                        android:id="@+id/email"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/user_name"
                        android:layout_marginLeft="@dimen/dp10"
                        android:layout_toEndOf="@+id/image_profile"
                        android:layout_toRightOf="@+id/image_profile"
                        android:fontFamily="sans-serif-normal"
                        android:text="johndoe@mail.com"
                        android:textColor="@android:color/black"
                        android:textSize="14sp" />

                    <Button
                        android:id="@+id/button_edit"
                        android:layout_width="wrap_content"

                        android:layout_height="wrap_content"
                        android:layout_alignParentEnd="true"
                        android:layout_alignParentRight="true"
                        android:layout_alignTop="@+id/image_profile"
                        android:background="@drawable/customborder"
                        android:text="Edit Profile"
                        android:textAllCaps="false"
                        android:textColor="@color/colorAccent" />

                </RelativeLayout>

            </ViewSwitcher>

            <View
                android:layout_width="wrap_content"
                android:layout_height="1dp"
                android:background="@color/grey_200" />

            <ListView
                android:id="@+id/list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>
</LinearLayout>


答:
The reason decode crashes and encode does not is because you are trying to delete a pointer that was not allocated with new.  You did allocate with new to begin with but when you do fName = "e:/fc/enc_test.txt"; you change fname to point to a string literal instead of the memory you originally allocated.  Trying to delete it after that is why you crash.

You should turn up the warnings on your compiler as

```<code>fName = "e:/fc/enc_test.txt";
</code>```

Should be an error since "e:/fc/enc_test.txt" has the type const char[] and you should not be able to assign it to a char*.

Title: Delete[] operator makes *.exe trigger a breakpoint and wntdll.pdb not loaded to appear

Body:
The reason decode crashes and encode does not is because you are trying to delete a pointer that was not allocated with new.  You did allocate with new to begin with but when you do fName = "e:/fc/enc_test.txt"; you change fname to point to a string literal instead of the memory you originally allocated.  Trying to delete it after that is why you crash.

You should turn up the warnings on your compiler as

fName = "e:/fc/enc_test.txt";

Should be an error since "e:/fc/enc_test.txt" has the type const char[] and you should not be able to assign it to a char*.


问:
Bootstrap Alert in Jumbotron wrong margins
I am creating a part of my website which includes a Jumbotron and a collapsable alert message, both from the Bootstrap Framework. I am having problems with the margins from the alert box. I use the standard CSS for the Jumbotron with adjusted paddings, which do not interfere with my problem though.

This is how it looks like unmodified:

I want the alert box to fit with the alignment of the selection boxes. I tried override the properties of the alert class with this:

```<code>.alert-custom-style {
    margin-left: 15px;
    margin-right: 15px;
    width: 100%;
}
</code>```

The result of it is here:

This does work fine for the left side, but the margin-right property somehow does not get considered. I tested this by putting margin-left back to 0px but then it just looked like in the first picture. I am really scratching my head around why the left margin property works, but not the right one. Any suggestions or help is very appreciated.

Here is the HTML-Code:

```<code>        <div class="jumbotron jumbotron-custom">
            <div class="row">
                <div class="col-lg-5 col-md-5 col-sm-12 col-xs-12 top-buffer">
                    <!-- Dropdown List for the first country -->
                    <select id="country1" name="Country Selection 1" class="selectpicker" data-width="100%" data-style="btn-default" data-live-search="true" title="Choose..."></select>
                </div>

                <div class="col-lg-2 col-md-2 col-sm-12 col-xs-12 top-buffer">
                    <!-- Compare Button -->
                    <button id="btnSubmit" type="Submit" class="btn btn-success btn-block">Compare</button>
                </div>

                <div class="col-lg-5 col-md-5 col-sm-12 col-xs-12 top-buffer">
                    <!-- Dropdown List for the second country -->
                    <select id="country2" name="Country Selection 2" class="selectpicker" data-width="100%" data-style="btn-default" data-live-search="true" title="Choose..."></select>
                </div>

                <!-- JavaScript file to handle the data management -->
                <script src="js/compare.js"></script>
                <!-- JavaScript file to handle the selection lists -->
                <script src="js/lists.js"></script>
            </div>

            <div class="row top-buffer">
                <div id="alert" class="collapse alert alert-custom-style col-lg-12 col-md-12 col-sm-12 col-xs-12" role="alert"> <!-- Collapsed by default -->
                    <strong>Warning: </strong><span id="alert-span">Please select at least two different countries</span>
                </div>
            </div>
        </div>
</code>```

答:
For row that holds the alert with the class top-buffer try adding:

```<code>margin-left: 15px;
margin-right: 15px;
</code>```

I don't have all your css, but here is a rough version that I think approximates what you want.

Use the "full page" button at the bottom of the snippet to see the result in a wider view.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

        <select id="country1" name="Country Selection 1" class="selectpicker" style="width:100%;" data-width="100%" data-style="btn-default" data-live-search="true" title="Choose...">
        </select>

        <button id="btnSubmit" type="Submit" class="btn btn-success btn-block" style="width:100%;">
          Compare
        </button>

        <select id="country2" name="Country Selection 2" class="selectpicker" style="width:100%;" data-width="100%" data-style="btn-default" data-live-search="true" title="Choose...">
        </select>

        Warning: Please select at least two different countries

```

Body:
I am creating a part of my website which includes a Jumbotron and a collapsable alert message, both from the Bootstrap Framework. I am having problems with the margins from the alert box. I use the standard CSS for the Jumbotron with adjusted paddings, which do not interfere with my problem though.

This is how it looks like unmodified:

I want the alert box to fit with the alignment of the selection boxes. I tried override the properties of the alert class with this:

.alert-custom-style {
    margin-left: 15px;
    margin-right: 15px;
    width: 100%;
}

The result of it is here:

This does work fine for the left side, but the margin-right property somehow does not get considered. I tested this by putting margin-left back to 0px but then it just looked like in the first picture. I am really scratching my head around why the left margin property works, but not the right one. Any suggestions or help is very appreciated.

Here is the HTML-Code:

                    <select id="country1" name="Country Selection 1" class="selectpicker" data-width="100%" data-style="btn-default" data-live-search="true" title="Choose..."></select>

                    <button id="btnSubmit" type="Submit" class="btn btn-success btn-block">Compare</button>

                    <select id="country2" name="Country Selection 2" class="selectpicker" data-width="100%" data-style="btn-default" data-live-search="true" title="Choose..."></select>

                    Warning: Please select at least two different countries

Body:
For row that holds the alert with the class top-buffer try adding:

margin-left: 15px;
margin-right: 15px;

I don't have all your css, but here is a rough version that I think approximates what you want.

Use the "full page" button at the bottom of the snippet to see the result in a wider view.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">
    <div class="jumbotron">
      <div class="col-lg-5 col-md-5 col-sm-12 col-xs-12 top-buffer">
        <!-- Dropdown List for the first country -->
        <select id="country1" name="Country Selection 1" class="selectpicker" style="width:100%;" data-width="100%" data-style="btn-default" data-live-search="true" title="Choose...">
        </select>
      </div>
      <div class="col-lg-2 col-md-2 col-sm-12 col-xs-12 top-buffer">
        <!-- Compare Button -->
        <button id="btnSubmit" type="Submit" class="btn btn-success btn-block" style="width:100%;">
          Compare
        </button>
      </div>
      <div class="col-lg-5 col-md-5 col-sm-12 col-xs-12 top-buffer">
        <!-- Dropdown List for the second country -->
        <select id="country2" name="Country Selection 2" class="selectpicker" style="width:100%;" data-width="100%" data-style="btn-default" data-live-search="true" title="Choose...">
        </select>
      </div>
      <div class="row top-buffer" style="margin-left: 15px; margin-right: 15px;">
      <div id="alert" class="collapse in alert alert-custom-style col-lg-12 col-md-12 col-sm-12 col-xs-12" role="alert" style="background-color: red;"> <!-- Collapsed by default -->
        <strong>Warning: </strong><span id="alert-span">Please select at least two different countries</span>
      </div>
    </div>
  </div>
</div>


问:
MongoDB match all documents if input is blank
I'm using aggregate and match to grab data from the database. This is a simplified version:

```<code>Palette.aggregate([
    {"$match": {
      type: paletteType,
      numberOfColors: {[colorNumberFilterTypeOperator]: colorNumber},
      tags: paletteTag
    }]);
</code>```

Tags is an array.

I want to make it so if paletteTag is blank, it will return documents with anything in the tags field, but right now it returns none, as it's trying to match blank tags, which don't exist.

I could do an if statement to check the value of paletteTag and if it's blank set it to something that will match all tags, but I'm not sure what it would be. Doing something like /.*/g works to return anything with tags, but if the tag array is blank (equal to []), then it won't be returned. I want to return anything, whether it has tags in that field or not.

答:
```<code>var match = {
  type: paletteType,
  numberOfColors: {[colorNumberFilterTypeOperator]: colorNumber}
}

paletteTag? match.tags =  paletteTag : null;  //add tag criteria only if palletTag exists
Palette.aggregate(
  [{
    "$match": match
  }]);
</code>```

Body:
I'm using aggregate and match to grab data from the database. This is a simplified version:

Palette.aggregate([
    {"$match": {
      type: paletteType,
      numberOfColors: {[colorNumberFilterTypeOperator]: colorNumber},
      tags: paletteTag
    }]);

Tags is an array.

I want to make it so if paletteTag is blank, it will return documents with anything in the tags field, but right now it returns none, as it's trying to match blank tags, which don't exist.

I could do an if statement to check the value of paletteTag and if it's blank set it to something that will match all tags, but I'm not sure what it would be. Doing something like /.*/g works to return anything with tags, but if the tag array is blank (equal to []), then it won't be returned. I want to return anything, whether it has tags in that field or not.


问:
Change obj model material in three.js
I have a 3D model with UV mapping created in blender. I applied the UV mapping in a way that the texture is only applied on one side of the model. I exported the model as obj and mtl. When I import this model on three.js it works as intended and the loader automatically applies the image defined in the mtl file as the texture.

Now I want to change this texture programatically in three.js. The model has multiple materials (I think it's because of multiple faces). How do I reapply the material maintaining the UV mapping and just changing the texture applied? I want to apply a map and a envMap to the model.

```<code>                       var m = new THREE.MeshPhongMaterial({
                            envMap: cubemap,
                            reflectivity: 0.9
                        });
                        var m2 = new THREE.MeshPhongMaterial({
                            envMap: cubemap,
                            color: parseInt(material.color, 16),
                            reflectivity: 0.9,
                            map: THREE.ImageUtils.loadTexture('/textures/uv_checker large.png')
                        });

                        loadedMesh.material = [m,m,m,m,m,m2,m2,m2,m];
</code>```

With the m and m2 positions applied after some trial and error. The texture is applied but it doesn't end up looking the same way as the original. II have some small empty spaces and even texture on places I shouldn't have texture due to my UV mapping.

How can I approach this?

答:
Ok I found a way. I don't know if this will work with all the models but I replaced all the materials that had a map texture with my custom material with another texture and replaced all the other materials with another different material. It worked perfectly and the UV Map was still there.

```<code>var m1 = new THREE.MeshPhongMaterial({map: texture, ...});
var m2 = new THREE.MeshPhongMaterial({...});
for(var n = 0; n < model.material.length; ++n) {
   if(model.material[n].map) model.material[n] = m1;
   else model.material[n] = m2;
}
</code>```

Title: Change obj model material in three.js

Body:
I have a 3D model with UV mapping created in blender. I applied the UV mapping in a way that the texture is only applied on one side of the model. I exported the model as obj and mtl. When I import this model on three.js it works as intended and the loader automatically applies the image defined in the mtl file as the texture.

Now I want to change this texture programatically in three.js. The model has multiple materials (I think it's because of multiple faces). How do I reapply the material maintaining the UV mapping and just changing the texture applied? I want to apply a map and a envMap to the model.

                       var m = new THREE.MeshPhongMaterial({
                            envMap: cubemap,
                            reflectivity: 0.9
                        });
                        var m2 = new THREE.MeshPhongMaterial({
                            envMap: cubemap,
                            color: parseInt(material.color, 16),
                            reflectivity: 0.9,
                            map: THREE.ImageUtils.loadTexture('/textures/uv_checker large.png')
                        });

                        loadedMesh.material = [m,m,m,m,m,m2,m2,m2,m];

With the m and m2 positions applied after some trial and error. The texture is applied but it doesn't end up looking the same way as the original. II have some small empty spaces and even texture on places I shouldn't have texture due to my UV mapping.

How can I approach this?

Body:
Ok I found a way. I don't know if this will work with all the models but I replaced all the materials that had a map texture with my custom material with another texture and replaced all the other materials with another different material. It worked perfectly and the UV Map was still there.

var m1 = new THREE.MeshPhongMaterial({map: texture, ...});
var m2 = new THREE.MeshPhongMaterial({...});
for(var n = 0; n < model.material.length; ++n) {
   if(model.material[n].map) model.material[n] = m1;
   else model.material[n] = m2;
}


问:
UIB tabset is not working
```<code><div class="ui-tab-container">
    <uib-tabset>
        <uib-tab heading="Region Wise" index="region" active="region_wise">Tab 1</uib-tab >
        <uib-tab heading="Branch Wise" index="branch" active="state_tab">Tab 2</uib-tab>
        <uib-tab heading="City Wise" index="city" active="city_tab">Tab 3</uib-tab>
        <uib-tab heading="Counter Wise" index="counter" active="counter_tab">Tab 4</uib-tab>
    </uib-tabset>
</div>
</code>```

No tabs are getting displayed and when I switched to bootstrap tabsets they worked fine but I was not able to switch from 1 tab to another on clicking a button on first tab even though I set the active property of that tab to true from inside the function of the button(when clicked)
"bootstrap": "~3.3.0"
"angular-bootstrap": "~2.3.1"
Thanks in advance.

答:
As far as I understand the directive active inside ui-tab must be bound with some boolean variable in your model.

```<code><uib-tab ... active="boolean_variable_to_bind">...</uib-tab >
</code>```

Title: UIB tabset is not working

Body:
    <uib-tabset>
        <uib-tab heading="Region Wise" index="region" active="region_wise">Tab 1</uib-tab >
        <uib-tab heading="Branch Wise" index="branch" active="state_tab">Tab 2</uib-tab>
        <uib-tab heading="City Wise" index="city" active="city_tab">Tab 3</uib-tab>
        <uib-tab heading="Counter Wise" index="counter" active="counter_tab">Tab 4</uib-tab>
    </uib-tabset>

No tabs are getting displayed and when I switched to bootstrap tabsets they worked fine but I was not able to switch from 1 tab to another on clicking a button on first tab even though I set the active property of that tab to true from inside the function of the button(when clicked)
"bootstrap": "~3.3.0"
"angular-bootstrap": "~2.3.1"
Thanks in advance.

Body:
As far as I understand the directive active inside ui-tab must be bound with some boolean variable in your model.

<uib-tab ... active="boolean_variable_to_bind">...</uib-tab >


问:
Cordova: load epub file in www folder
Time to ask for help; spent too many days of attempting to solve this issue on my own. Any assistance is greatly appreciated.

I’m running react-reader in a web app and it loads epub files across browsers (including Safari) without any issues. But when the app runs on iOS via Cordova, it no longer loads the epub files. I’m assuming it might have to do with the way iOS/Cordova handles files, but I’m not an expert in these matters. I did try out different StackOverflow suggestions (this, this, this, and this), to no avail.

All epub files are located in a subfolder: www/epubs/

Here’s the react code that works on the web app, but not the Cordova app (simplified to the essentials):

```<code>import React from 'react'
import { EpubView } from 'react-reader'

export default ({ lang, name }) => (
  <EpubView
    url={'epubs/' + lang + '-' + name + '.epub'}
  />
)
</code>```

答:
Solved it! One trick that works is to fs.download each file from the www folder into Cordova’s persistent file system. See my original post.

First, in Terminal:

npm install cordova-promise-fs

cordova plugin add cordova-plugin-file --save

cordova plugin add cordova-plugin-file-transfer --save

Then, in your front-end:

```<code>import CordovaPromiseFS from 'cordova-promise-fs'

const fs = CordovaPromiseFS({
  persistent: true,
  storageSize: 200 * 1024 * 1024,
  concurrency: 3
})
</code>```

If you use React, the above has to be declared before the component Class is created, while the below code should be in its own function inside the component Class. See my GitHub comment for more details.

```<code>window.resolveLocalFileSystemURL(
  cordova.file.applicationDirectory + 'www/epubs/alice.epub',
    // If successful...
    (fileSystem) => {
      const downloadUrl = fileSystem.toURL()
      const localUrl = 'alice.epub' // the filename it is stored as in the device
      fs.download(
        downloadUrl,
        localUrl,
        (progressEvent) => {
          if (progressEvent.loaded && progressEvent.total) {
          console.log('progress', Math.round((progressEvent.loaded / progressEvent.total) * 100))
        }
      }
    ).then((filedata) => {
      return fs.toInternalURL(localUrl)
    })
    .then((localPath) => {
      this.setState({ epubPath: localPath })
    }).catch((error) => {
      console.log('some error happend', error)
    })
  },
  // If unsuccessful
  (err) => {
    console.log(err)
  }
)
</code>```

Title: Cordova: load epub file in www folder

Body:
Time to ask for help; spent too many days of attempting to solve this issue on my own. Any assistance is greatly appreciated.

I’m running react-reader in a web app and it loads epub files across browsers (including Safari) without any issues. But when the app runs on iOS via Cordova, it no longer loads the epub files. I’m assuming it might have to do with the way iOS/Cordova handles files, but I’m not an expert in these matters. I did try out different StackOverflow suggestions (this, this, this, and this), to no avail.

All epub files are located in a subfolder: www/epubs/

Here’s the react code that works on the web app, but not the Cordova app (simplified to the essentials):

import React from 'react'
import { EpubView } from 'react-reader'

export default ({ lang, name }) => (
  <EpubView
    url={'epubs/' + lang + '-' + name + '.epub'}
  />
)

Body:
Solved it! One trick that works is to fs.download each file from the www folder into Cordova’s persistent file system. See my original post.

First, in Terminal:

npm install cordova-promise-fs

cordova plugin add cordova-plugin-file --save

cordova plugin add cordova-plugin-file-transfer --save

Then, in your front-end:

import CordovaPromiseFS from 'cordova-promise-fs'

const fs = CordovaPromiseFS({
  persistent: true,
  storageSize: 200 * 1024 * 1024,
  concurrency: 3
})

If you use React, the above has to be declared before the component Class is created, while the below code should be in its own function inside the component Class. See my GitHub comment for more details.

window.resolveLocalFileSystemURL(
  cordova.file.applicationDirectory + 'www/epubs/alice.epub',
    // If successful...
    (fileSystem) => {
      const downloadUrl = fileSystem.toURL()
      const localUrl = 'alice.epub' // the filename it is stored as in the device
      fs.download(
        downloadUrl,
        localUrl,
        (progressEvent) => {
          if (progressEvent.loaded && progressEvent.total) {
          console.log('progress', Math.round((progressEvent.loaded / progressEvent.total) * 100))
        }
      }
    ).then((filedata) => {
      return fs.toInternalURL(localUrl)
    })
    .then((localPath) => {
      this.setState({ epubPath: localPath })
    }).catch((error) => {
      console.log('some error happend', error)
    })
  },
  // If unsuccessful
  (err) => {
    console.log(err)
  }
)


问:
Remove trailing data from Django timesince
Is there a way to remove the trailing data from the django timesince filter?

I would like to only display days, weeks months or years without any trailing information. e.g weeks + days -> weeks, months + weeks -> months, years + months -> years, etc.

Additionally, if the date is less than one day, it should display the hours. e.g. 1 hour ago, 4 hours ago, etc.

Currently I have a datetime object and am using the filter like this:

```<code>{{ my_date_time|timesince}}
</code>```

答:
You can make your own template tag and use it to modify the output of timesince to be anything you like. Here's an example just to get you started:

```<code>def custom_timesince(value):
    now = datetime.datetime.now()
    # can add some error checking if you want
    diff = now - value
    if diff < timedelta(days=1):
        return "recently" # or w/e you wanted with the hours

    # remove trailing information from timesince
    return timesince(value).split(", ")[0]
</code>```

possibly helpful: docs on using such custom tags

Body:
Is there a way to remove the trailing data from the django timesince filter?

I would like to only display days, weeks months or years without any trailing information. e.g weeks + days -> weeks, months + weeks -> months, years + months -> years, etc.

Additionally, if the date is less than one day, it should display the hours. e.g. 1 hour ago, 4 hours ago, etc.

Currently I have a datetime object and am using the filter like this:

{{ my_date_time|timesince}}

Body:
You can make your own template tag and use it to modify the output of timesince to be anything you like. Here's an example just to get you started:

def custom_timesince(value):
    now = datetime.datetime.now()
    # can add some error checking if you want
    diff = now - value
    if diff < timedelta(days=1):
        return "recently" # or w/e you wanted with the hours

    # remove trailing information from timesince
    return timesince(value).split(", ")[0]

possibly helpful: docs on using such custom tags


问:
Keyboard Input handler doesn't work
I'm working on a java project and i'm having a hard time to make the Keyboard input handler work. I have two separate classes, one called KeyInput and one called Player. When i'm starting the Player class and I press a key nothing will be printed, but if i use println in the KeyInput class it will work. So it does register when you press a button only it won't work when I want to make use of it within the Player class.

Player class:

```<code>public class Player extends JFrame {

private static final int IMAGE_TYPE = BufferedImage.TYPE_INT_ARGB;

private BufferedImage img;
KeyInput input

public Player() {
    super();
    this.add(new JPanel() {
        @Override
        protected void paintComponent(Graphics g) {
           g.drawImage(img, 0, 0, null);
        }

    });
    img = new BufferedImage(660, 500, IMAGE_TYPE );
    this.setSize(img.getWidth(), img.getHeight());
    this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    input = new KeyInput(this);

    if(input.up.isPressed()){
        System.out.println("Up");
    }

    this.setVisible( true );
   }
 }
</code>```

KeyInput class:

```<code>public class KeyInput implements KeyListener {
    BufferedImage img = null;
    public KeyInput(Player player) {
            player.requestFocus(); // click window to move bug fix he didn't add this
            player.addKeyListener(this);
    }

    public class Key {
            private int numTimesPressed = 0;
            private boolean pressed = false;

            public int getNumTimesPressed() {
                    return numTimesPressed;
            }

            public boolean isPressed() {
                    return pressed;

            }

            public void toggle(boolean isPressed) {
                    pressed = isPressed;

                    if (isPressed) {
                            numTimesPressed++;
                    }
            }
    }

    public List<Key> keys = new ArrayList<Key>();

    public Key up = new Key();
    public Key down = new Key();
    public Key left = new Key();
    public Key right = new Key();
    public Key esc = new Key();

    public void keyPressed(KeyEvent e) {
            toggleKey(e.getKeyCode(), true);
    }

    public void keyReleased(KeyEvent e) {
            toggleKey(e.getKeyCode(), false);
    }

    public void keyTyped(KeyEvent e) {

    }

    public void toggleKey(int KeyCode, boolean isPressed) {
            if (KeyCode == KeyEvent.VK_W || KeyCode == KeyEvent.VK_UP
                            || KeyCode == KeyEvent.VK_NUMPAD8) {

                    up.toggle(isPressed);
            }
            if (KeyCode == KeyEvent.VK_S || KeyCode == KeyEvent.VK_DOWN
                            || KeyCode == KeyEvent.VK_NUMPAD2) {
                    down.toggle(isPressed);
            }
            if (KeyCode == KeyEvent.VK_A || KeyCode == KeyEvent.VK_LEFT
                            || KeyCode == KeyEvent.VK_NUMPAD4) {
                    left.toggle(isPressed);
            }
            if (KeyCode == KeyEvent.VK_D || KeyCode == KeyEvent.VK_RIGHT
                            || KeyCode == KeyEvent.VK_NUMPAD6) {
                    right.toggle(isPressed);
            }
            if(KeyCode == KeyEvent.VK_ESCAPE){
                System.exit(0);
            }
    }
 }
</code>```

答:
You should use Key Bindings to assign key stroke to action on specific component.

A qoute from docs

```<code>component.getInputMap().put(KeyStroke.getKeyStroke("F2"),
                            "doSomething");
component.getActionMap().put("doSomething",
                             anAction);
//where anAction is a javax.swing.Action
</code>```

https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html#howto

Title: Keyboard Input handler doesn't work

Body:
I'm working on a java project and i'm having a hard time to make the Keyboard input handler work. I have two separate classes, one called KeyInput and one called Player. When i'm starting the Player class and I press a key nothing will be printed, but if i use println in the KeyInput class it will work. So it does register when you press a button only it won't work when I want to make use of it within the Player class.

Player class:

public class Player extends JFrame {

private static final int IMAGE_TYPE = BufferedImage.TYPE_INT_ARGB;

private BufferedImage img;
KeyInput input

public Player() {
    super();
    this.add(new JPanel() {
        @Override
        protected void paintComponent(Graphics g) {
           g.drawImage(img, 0, 0, null);
        }

    });
    img = new BufferedImage(660, 500, IMAGE_TYPE );
    this.setSize(img.getWidth(), img.getHeight());
    this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    input = new KeyInput(this);

    if(input.up.isPressed()){
        System.out.println("Up");
    }

    this.setVisible( true );
   }
 }

KeyInput class:

public class KeyInput implements KeyListener {
    BufferedImage img = null;
    public KeyInput(Player player) {
            player.requestFocus(); // click window to move bug fix he didn't add this
            player.addKeyListener(this);
    }

    public class Key {
            private int numTimesPressed = 0;
            private boolean pressed = false;

            public int getNumTimesPressed() {
                    return numTimesPressed;
            }

            public boolean isPressed() {
                    return pressed;

            }

            public void toggle(boolean isPressed) {
                    pressed = isPressed;

                    if (isPressed) {
                            numTimesPressed++;
                    }
            }
    }

    public List<Key> keys = new ArrayList<Key>();

    public Key up = new Key();
    public Key down = new Key();
    public Key left = new Key();
    public Key right = new Key();
    public Key esc = new Key();

    public void keyPressed(KeyEvent e) {
            toggleKey(e.getKeyCode(), true);
    }

    public void keyReleased(KeyEvent e) {
            toggleKey(e.getKeyCode(), false);
    }

    public void keyTyped(KeyEvent e) {

    }

    public void toggleKey(int KeyCode, boolean isPressed) {
            if (KeyCode == KeyEvent.VK_W || KeyCode == KeyEvent.VK_UP
                            || KeyCode == KeyEvent.VK_NUMPAD8) {

                    up.toggle(isPressed);
            }
            if (KeyCode == KeyEvent.VK_S || KeyCode == KeyEvent.VK_DOWN
                            || KeyCode == KeyEvent.VK_NUMPAD2) {
                    down.toggle(isPressed);
            }
            if (KeyCode == KeyEvent.VK_A || KeyCode == KeyEvent.VK_LEFT
                            || KeyCode == KeyEvent.VK_NUMPAD4) {
                    left.toggle(isPressed);
            }
            if (KeyCode == KeyEvent.VK_D || KeyCode == KeyEvent.VK_RIGHT
                            || KeyCode == KeyEvent.VK_NUMPAD6) {
                    right.toggle(isPressed);
            }
            if(KeyCode == KeyEvent.VK_ESCAPE){
                System.exit(0);
            }
    }
 }

Body:
You should use Key Bindings to assign key stroke to action on specific component.

A qoute from docs

component.getInputMap().put(KeyStroke.getKeyStroke("F2"),
                            "doSomething");
component.getActionMap().put("doSomething",
                             anAction);
//where anAction is a javax.swing.Action

https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html#howto


问:
NumberFormatException For Input String in JAVA
I've written some code which calculate employee's Total overtime,Rate per hour,Total amount based on their overtime,medical,bonus,others etc etc.Here is the code,

```<code>    int salary = Integer.parseInt(txt_salary.getText().trim());
    int overtime = Integer.parseInt(txt_overtime.getText().trim());

    double eight = 8;
    double days = 25;
    double dbop = 0;
    double overtimeRate = 1.5;

    //calculate the total hours of overtime
    double Total_Overtime = overtime * overtimeRate;
    String x = (String.valueOf(Total_Overtime)).trim();
    txt_hw.setText(x);

    //calculate overall overtime
    dbop = salary /days/eight;
    String s = (String.valueOf(dbop)).trim();
    txt_rate.setText(s);

    int med = Integer.parseInt(txt_med.getText().trim());
    int bonus = Integer.parseInt(txt_bonus.getText().trim());
    int other = Integer.parseInt(txt_other.getText().trim());
    int f = med+bonus+other;
    double calc = Total_Overtime * dbop+f;
    String c = (String.valueOf(calc)).trim();
    lbl_total.setText(c);
</code>```

Why this is giving me the following error when I try to calculate,

```<code>Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "20000.0"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Allowance.btn_calcAllwActionPerformed(Allowance.java:764)
at Allowance.access$500(Allowance.java:18)
at Allowance$5.actionPerformed(Allowance.java:248)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6535)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6300)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4891)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
</code>```

Someone please help me. Can't figure out what I did wrong.

答:
A quick fix (not efficient without error handling) could be the following.

```<code>double doubleValue = Double.parseDouble(someValue.getText().trim());
int intValue = (int)doubleValue;
</code>```

Here you first try to convert whatever string you have to Double and then cast it to integer.

Note: Double.parseDouble will still throw an error if the string is not a number.

Body:
I've written some code which calculate employee's Total overtime,Rate per hour,Total amount based on their overtime,medical,bonus,others etc etc.Here is the code,

    int salary = Integer.parseInt(txt_salary.getText().trim());
    int overtime = Integer.parseInt(txt_overtime.getText().trim());

    double eight = 8;
    double days = 25;
    double dbop = 0;
    double overtimeRate = 1.5;

    //calculate the total hours of overtime
    double Total_Overtime = overtime * overtimeRate;
    String x = (String.valueOf(Total_Overtime)).trim();
    txt_hw.setText(x);

    //calculate overall overtime
    dbop = salary /days/eight;
    String s = (String.valueOf(dbop)).trim();
    txt_rate.setText(s);

    int med = Integer.parseInt(txt_med.getText().trim());
    int bonus = Integer.parseInt(txt_bonus.getText().trim());
    int other = Integer.parseInt(txt_other.getText().trim());
    int f = med+bonus+other;
    double calc = Total_Overtime * dbop+f;
    String c = (String.valueOf(calc)).trim();
    lbl_total.setText(c);

Why this is giving me the following error when I try to calculate,

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "20000.0"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Allowance.btn_calcAllwActionPerformed(Allowance.java:764)
at Allowance.access$500(Allowance.java:18)
at Allowance$5.actionPerformed(Allowance.java:248)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6535)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6300)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4891)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Someone please help me. Can't figure out what I did wrong.

Body:
A quick fix (not efficient without error handling) could be the following.

double doubleValue = Double.parseDouble(someValue.getText().trim());
int intValue = (int)doubleValue;

Here you first try to convert whatever string you have to Double and then cast it to integer.

Note: Double.parseDouble will still throw an error if the string is not a number.


问:
JTree: how to check if current node is a file
I am using the following code to populate a JTree which is working perfectly

```<code>File [] children = new File(directory).listFiles(); // list all the files in the directory
for (int i = 0; i < children.length; i++) { // loop through each
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(children[i].getName());
    // only display the node if it isn't a folder, and if this is a recursive call
    if (children[i].isDirectory() && recursive) {
        parent.add(node); // add as a child node
        listAllFiles(children[i].getPath(), node, recursive); // call again for the subdirectory
    } else if (!children[i].isDirectory()){ // otherwise, if it isn't a directory
        parent.add(node); // add it as a node and do nothing else
    }
}
</code>```

Give a directory string, it adds all the files in that directory to the JTree, my problem is that i am unable to get the file from each of the nodes... i know you can use

```<code>jtree.getLastSelectedPathComponent()
</code>```

to get the last selected component but what i really what is to check if the selected component is of type File and if it is, return the path of that file... does anyone know how to do this?

答:
I'm using something like this:

```<code>private boolean isFileSelected()
{
    TreePath treePath = tree.getSelectionPath();
    Object lastPathComponent = treePath.getLastPathComponent();
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) lastPathComponent;

    return node.getUserObject() instanceof MyNodeObject;
}
</code>```

MyNodeObject should be different from the folder data types so you can identify if the node is a file or not.

Body:
I am using the following code to populate a JTree which is working perfectly

File [] children = new File(directory).listFiles(); // list all the files in the directory
for (int i = 0; i < children.length; i++) { // loop through each
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(children[i].getName());
    // only display the node if it isn't a folder, and if this is a recursive call
    if (children[i].isDirectory() && recursive) {
        parent.add(node); // add as a child node
        listAllFiles(children[i].getPath(), node, recursive); // call again for the subdirectory
    } else if (!children[i].isDirectory()){ // otherwise, if it isn't a directory
        parent.add(node); // add it as a node and do nothing else
    }
}

Give a directory string, it adds all the files in that directory to the JTree, my problem is that i am unable to get the file from each of the nodes... i know you can use

jtree.getLastSelectedPathComponent()

to get the last selected component but what i really what is to check if the selected component is of type File and if it is, return the path of that file... does anyone know how to do this?

Body:
I'm using something like this:

private boolean isFileSelected()
{
    TreePath treePath = tree.getSelectionPath();
    Object lastPathComponent = treePath.getLastPathComponent();
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) lastPathComponent;

    return node.getUserObject() instanceof MyNodeObject;
}

MyNodeObject should be different from the folder data types so you can identify if the node is a file or not.


问:
TYPO3 hook for saving page settings
I'm searching for a hook which is called after page settings saving or change. I tried this answer TYPO3: Hook after creating or editing page, but it does something else.

Does someone know of one?

答:
I was solving this problem a week ago. You have to have a class ProcessCmdmap in folder Extension/Classes/Hooks/ProcessCmdmap.php which is called by hook, and this class should have a method which is called by the save. I recommend this method processDatamap_postProcessFieldArray

```<code>    <?php
namespace Vendor\Extension\Hooks;

class ProcessCmdmap {

    public function processDatamap_postProcessFieldArray($status, $table, $id, array &$fieldArray, \TYPO3\CMS\Core\DataHandling\DataHandler &$pObj) {
        var_dump($id);
        var_dump($table);
        var_dump($status);
        var_dump($fieldArray);
        var_dump($pObj);
    }
}

?>
</code>```

And dont forget to register your hook:

```<code>$GLOBALS ['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][''] = 'Vendor\Extension\Hooks\ProcessCmdmap';
$GLOBALS ['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'][''] = 'Vendor\ Extension\Hooks\ProcessCmdmap';
</code>```

Title: TYPO3 hook for saving page settings

Body:
I was solving this problem a week ago. You have to have a class ProcessCmdmap in folder Extension/Classes/Hooks/ProcessCmdmap.php which is called by hook, and this class should have a method which is called by the save. I recommend this method processDatamap_postProcessFieldArray

    <?php
namespace Vendor\Extension\Hooks;

class ProcessCmdmap {

    public function processDatamap_postProcessFieldArray($status, $table, $id, array &$fieldArray, \TYPO3\CMS\Core\DataHandling\DataHandler &$pObj) {
        var_dump($id);
        var_dump($table);
        var_dump($status);
        var_dump($fieldArray);
        var_dump($pObj);
    }
}

?>

And dont forget to register your hook:

$GLOBALS ['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'][''] = 'Vendor\Extension\Hooks\ProcessCmdmap';
$GLOBALS ['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'][''] = 'Vendor\ Extension\Hooks\ProcessCmdmap';


问:
Is this a method or a function?
Am I correct in assuming that getDataPoint() is a method as opposed to a function when used in this context?

```<code>class Globals: NSObject{
   static let sharedInstance = Globals()

   func getDataPoint() -> Int {
      var theValue: Int
      //Some JSON code here
      return theValue
   }
}

class GameScene: SKScene{
   override func didMove(to: view: SKView){
      let globals = Globals.sharedInstance()

      var x = globals.getDataPoint() //Is a method?
   }
}
</code>```

But if I used within the Globals class, I would call it a function.

```<code> class Globals: NSObject{
   static let sharedInstance = Globals()

   func foo() {
      print(\(getDataPoint())) //Is a function?
   }

   func getDataPoint() -> Int {
      var theValue: Int
      //Some JSON code here
      return theValue
   }
}
</code>```

答:
A method is not "opposed to a function" so the question is meaningless. A method is a function — a function declared at the top level of a type declaration.

```<code>func function() {}
class Class {
    func method() {}
    func anotherMethod() {
        func function() { }
    }
}
</code>```

Title: Is this a method or a function?

Body:
Am I correct in assuming that getDataPoint() is a method as opposed to a function when used in this context?

class Globals: NSObject{
   static let sharedInstance = Globals()

   func getDataPoint() -> Int {
      var theValue: Int
      //Some JSON code here
      return theValue
   }
}

class GameScene: SKScene{
   override func didMove(to: view: SKView){
      let globals = Globals.sharedInstance()

      var x = globals.getDataPoint() //Is a method?
   }
}

But if I used within the Globals class, I would call it a function.

 class Globals: NSObject{
   static let sharedInstance = Globals()

   func foo() {
      print(\(getDataPoint())) //Is a function?
   }

   func getDataPoint() -> Int {
      var theValue: Int
      //Some JSON code here
      return theValue
   }
}

Body:
A method is not "opposed to a function" so the question is meaningless. A method is a function — a function declared at the top level of a type declaration.

func function() {}
class Class {
    func method() {}
    func anotherMethod() {
        func function() { }
    }
}


问:
invalid argument supplied for foreach
I am parsing XML in PHP code and getting a warning "invalid argument supplied for foreach".
Below is the XML:

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<BookStore>
    <book>
        <title>Computer Concepts</title>
        <auther>Goerge Arthar</auther>
        <category>Computer Science</category>
        <price>24.00</price>
    </book>
    <book>
        <title>Algebra</title>
        <auther>Mike</auther>
        <category>Mathematics</category>
        <price>34.00</price>
    </book>
</BookStore>
</code>```

and using the following code:

```<code><?php
$xmlDOM = new DOMDocument();
$xmlDOM->load("Books.xml");
$document = $xmlDOM->documentElement;
foreach ($document->childNodes as $node) {
    foreach($node->childNodes as $temp) {
        echo $temp->nodeName."=".$temp->nodeValue."<br />";
    }
}
?>
</code>```

NOTE: I get the output that I require but with a warning. It shows that array is not empty.
Please see output also:

```<code>Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8
#text=
title=Computer Concepts
#text=
auther=Goerge Arthar
#text=
category=Computer Science
#text=
price=24.00
#text=

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8
#text=
title=Algebra
#text=
auther=Mike
#text=
category=Mathematics
#text=
price=34.00
#text=

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8
</code>```

答: You're trying to iterate over the text node before and after the book sections.

ContentLicense: CC BY-SA 2.5

Title: invalid argument supplied for foreach

Body:
I am parsing XML in PHP code and getting a warning "invalid argument supplied for foreach".
Below is the XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
<BookStore>
    <book>
        <title>Computer Concepts</title>
        <auther>Goerge Arthar</auther>
        <category>Computer Science</category>
        <price>24.00</price>
    </book>
    <book>
        <title>Algebra</title>
        <auther>Mike</auther>
        <category>Mathematics</category>
        <price>34.00</price>
    </book>
</BookStore>

and using the following code:

<?php
$xmlDOM = new DOMDocument();
$xmlDOM->load("Books.xml");
$document = $xmlDOM->documentElement;
foreach ($document->childNodes as $node) {
    foreach($node->childNodes as $temp) {
        echo $temp->nodeName."=".$temp->nodeValue."
";
    }
}
?>

NOTE: I get the output that I require but with a warning. It shows that array is not empty.
Please see output also:

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8
#text=
title=Computer Concepts
#text=
auther=Goerge Arthar
#text=
category=Computer Science
#text=
price=24.00
#text=

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8
#text=
title=Algebra
#text=
auther=Mike
#text=
category=Mathematics
#text=
price=34.00
#text=

Warning: Invalid argument supplied for foreach() in D:\program Files\wamp\www\Test web\Day2\xmlparsing.php on line 8


问:
Difference between two datetime in c++
I have a two datetime in string format. for example

```<code>string str1 = "20160302101710"; //YYYYMMDDHHMMSS
string str2 = "20160302101715"; //same as above
</code>```

Now, i need difference between two datetime is greater that 24Hours.

I have tried my problem as follows

I parsed the both string and put as follows:

```<code>#include <iostream>
using namespace std;

int main() {

time_t rawtime, rawtime1;
struct tm * timeinfo, *timeinfo1;

timeinfo->tm_year = 2016 ;
timeinfo->tm_mon = 03;
timeinfo->tm_mday = 02;
timeinfo->tm_hour = 10;
timeinfo->tm_min = 17;
timeinfo->tm_sec = 10;
rawtime = mktime(timeinfo);

timeinfo1->tm_year = 2016 ;
timeinfo1->tm_mon = 03;
timeinfo1->tm_mday = 02;
timeinfo1->tm_hour = 10;
timeinfo1->tm_min = 17;
timeinfo1->tm_sec = 15;
rawtime1 =  mktime(timeinfo1);

cout<<"Diff: "<<     difftime(rawtime1,rawtime);

return 0;
}
</code>```

But After execution output is nothing.
Can anyone help me how to get the correct answer.
Once I will get the diff in second. then i will convert into hours.

Thanks,

答:
This can be done more easily with Howard Hinnant's free, open-source header-only datetime library:

```<code>#include "date/date.h"
#include <string>
#include <iostream>
#include <sstream>

int
main()
{
    using namespace std;
    using namespace std::chrono;
    using namespace date;
    string str1 = "20160302101710"; //YYYYMMDDHHMMSS
    string str2 = "20160302101715"; //same as above
    istringstream in{str1 + ' ' + str2};
    sys_seconds t1, t2;
    string fmt = " %Y%m%d%H%M%S";
    in >> parse(fmt, t1) >> parse(fmt, t2);
    cout << "Diff: " << t2 - t1 << '\n';
}
</code>```

Output:

```<code>Diff: 5s
</code>```

Title: Difference between two datetime in c++

Body:
I have a two datetime in string format. for example

string str1 = "20160302101710"; //YYYYMMDDHHMMSS
string str2 = "20160302101715"; //same as above

Now, i need difference between two datetime is greater that 24Hours.

I have tried my problem as follows

I parsed the both string and put as follows:

#include <iostream>
using namespace std;

int main() {

time_t rawtime, rawtime1;
struct tm * timeinfo, *timeinfo1;

timeinfo->tm_year = 2016 ;
timeinfo->tm_mon = 03;
timeinfo->tm_mday = 02;
timeinfo->tm_hour = 10;
timeinfo->tm_min = 17;
timeinfo->tm_sec = 10;
rawtime = mktime(timeinfo);

timeinfo1->tm_year = 2016 ;
timeinfo1->tm_mon = 03;
timeinfo1->tm_mday = 02;
timeinfo1->tm_hour = 10;
timeinfo1->tm_min = 17;
timeinfo1->tm_sec = 15;
rawtime1 =  mktime(timeinfo1);

cout<<"Diff: "<<     difftime(rawtime1,rawtime);

return 0;
}

But After execution output is nothing.
Can anyone help me how to get the correct answer.
Once I will get the diff in second. then i will convert into hours.

Thanks,

Body:
This can be done more easily with Howard Hinnant's free, open-source header-only datetime library:

#include "date/date.h"
#include <string>
#include <iostream>
#include <sstream>

int
main()
{
    using namespace std;
    using namespace std::chrono;
    using namespace date;
    string str1 = "20160302101710"; //YYYYMMDDHHMMSS
    string str2 = "20160302101715"; //same as above
    istringstream in{str1 + ' ' + str2};
    sys_seconds t1, t2;
    string fmt = " %Y%m%d%H%M%S";
    in >> parse(fmt, t1) >> parse(fmt, t2);
    cout << "Diff: " << t2 - t1 << '\n';
}

Output:

Diff: 5s