问:
Angular 5 recurrent issue - Webpack failed to compile a simple project
I want to create and serve a ng app. The problem is that after following the installation of angular 5 (+ionic) I found myself have the same problem over and over again and I have no idea what is causing it. I don't really understand what is the issue but I cannot serve any angular app.

The way I can resolve this is by a complete format of C:\ drive and reinstall anything from scratch. Last time I did it was 2 days ago. And before that 7 days ago.

This is all the stuff I get in the cmd.exe:

```<code>D:\!MY PROJECTS\APP-test>ng new engi
create engi/e2e/app.e2e-spec.ts (286 bytes)
create engi/e2e/app.po.ts (208 bytes)
create engi/e2e/tsconfig.e2e.json (235 bytes)
create engi/karma.conf.js (923 bytes)
create engi/package.json (1309 bytes)
create engi/protractor.conf.js (722 bytes)
create engi/README.md (1020 bytes)
create engi/tsconfig.json (363 bytes)
create engi/tslint.json (3097 bytes)
create engi/.angular-cli.json (1239 bytes)
create engi/.editorconfig (245 bytes)
create engi/.gitignore (516 bytes)
create engi/src/assets/.gitkeep (0 bytes)
create engi/src/environments/environment.prod.ts (51 bytes)
create engi/src/environments/environment.ts (387 bytes)
create engi/src/favicon.ico (5430 bytes)
create engi/src/index.html (291 bytes)
create engi/src/main.ts (370 bytes)
create engi/src/polyfills.ts (2405 bytes)
create engi/src/styles.css (80 bytes)
create engi/src/test.ts (1085 bytes)
create engi/src/tsconfig.app.json (211 bytes)
create engi/src/tsconfig.spec.json (304 bytes)
create engi/src/typings.d.ts (104 bytes)
create engi/src/app/app.module.ts (316 bytes)
create engi/src/app/app.component.html (1141 bytes)
create engi/src/app/app.component.spec.ts (986 bytes)
create engi/src/app/app.component.ts (207 bytes)
create engi/src/app/app.component.css (0 bytes)
Installing packages for tooling via npm.
Installed packages for tooling via npm.
Project 'engi' successfully created.

D:\!MY PROJECTS\APP-test>cd engi

D:\!MY PROJECTS\APP-test\engi>ng serve
** NG Live Development Server is listening on localhost:4200, open your
browser on http://localhost:4200/ **
Date: 2017-12-04T19:00:14.752Z
Hash: 96b1bdc547c1ab33ed03
Time: 4145ms
chunk {inline} inline.bundle.js (inline) 5.79 kB [entry] [rendered]
chunk {main} main.bundle.js (main) 3.25 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js (polyfills) 257 bytes [initial]
[rendered]
chunk {styles} styles.bundle.js (styles) 246 bytes [initial] [rendered]
chunk {vendor} vendor.bundle.js (vendor) 861 kB [initial] [rendered]

ERROR in multi webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts
Module not found: Error: Can't resolve 'D:\' in 'D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\models\webpack-configs'
resolve 'D:\' in 'D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\models\webpack-configs'
Parsed request is a directory
using description file: D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\package.json (relative path:
./models/webpack-configs)
after using description file: D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\package.json (relative path:
./models/webpack-configs)
No description file found
as directory
    existing directory
        using path: D:\index
          No description file found
        after using path: D:\index
          no extension
            D:\index doesn't exist
          .js
            D:\index.js doesn't exist
          .json
            D:\index.json doesn't exist
[D:\package.json]
[D:\index\package.json]
[D:\index]
[D:\index.js]
[D:\index.json]
 @ multi webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts
ERROR in multi ./src/polyfills.ts
Module not found: Error: Can't resolve 'D:\' in 'D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\models\webpack-configs'
resolve 'D:\' in 'D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\models\webpack-configs'
Parsed request is a directory
using description file: D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\package.json (relative path:
./models/webpack-configs)
after using description file: D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\package.json (relative path:
./models/webpack-configs)
    No description file found
    as directory
      existing directory
        using path: D:\index
          No description file found
        after using path: D:\index
          no extension
            D:\index doesn't exist
          .js
            D:\index.js doesn't exist
          .json
            D:\index.json doesn't exist
[D:\package.json]
[D:\index\package.json]
[D:\index]
[D:\index.js]
[D:\index.json]
 @ multi ./src/polyfills.ts
ERROR in multi ./src/styles.css
Module not found: Error: Can't resolve 'D:\' in 'D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\models\webpack-configs'
resolve 'D:\' in 'D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\models\webpack-configs'
  Parsed request is a directory
  using description file: D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\package.json (relative path:
./models/webpack-configs)
  after using description file: D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\package.json (relative path:
./models/webpack-configs)
    No description file found
    as directory
      existing directory
        using path: D:\index
          No description file found
        after using path: D:\index
          no extension
            D:\index doesn't exist
          .js
            D:\index.js doesn't exist
          .json
            D:\index.json doesn't exist
[D:\package.json]
[D:\index\package.json]
[D:\index]
[D:\index.js]
[D:\index.json]
 @ multi ./src/styles.css
ERROR in   Error: Child compilation failed:
  Entry module not found: Error: Can't resolve 'D:\' in 'D:\!MY
PROJECTS\APP-test\engi\node_modules\@angular\cli\models\webpack-configs':
  Error: Can't resolve 'D:\' in 'D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\models\webpack-configs'

  - compiler.js:76
    [engi]/[html-webpack-plugin]/lib/compiler.js:76:16

  - Compiler.js:304 compile
    [engi]/[webpack]/lib/Compiler.js:304:11

  - Compiler.js:514 applyPluginsAsync.err
    [engi]/[webpack]/lib/Compiler.js:514:14

  - Tapable.js:202 next
    [engi]/[tapable]/lib/Tapable.js:202:11

  - CachePlugin.js:78 Compiler.<anonymous>
    [engi]/[webpack]/lib/CachePlugin.js:78:5

  - Tapable.js:206 Compiler.applyPluginsAsyncSeries
    [engi]/[tapable]/lib/Tapable.js:206:13

  - Compiler.js:511 compilation.seal.err
    [engi]/[webpack]/lib/Compiler.js:511:11

  - Tapable.js:195 Compilation.applyPluginsAsyncSeries
    [engi]/[tapable]/lib/Tapable.js:195:46

  - Compilation.js:680 self.applyPluginsAsync.err
    [engi]/[webpack]/lib/Compilation.js:680:19

  - Tapable.js:195 Compilation.applyPluginsAsyncSeries
    [engi]/[tapable]/lib/Tapable.js:195:46

  - Compilation.js:671 self.applyPluginsAsync.err
    [engi]/[webpack]/lib/Compilation.js:671:11

  - Tapable.js:195 Compilation.applyPluginsAsyncSeries
    [engi]/[tapable]/lib/Tapable.js:195:46

  - Compilation.js:666 self.applyPluginsAsync.err
    [engi]/[webpack]/lib/Compilation.js:666:10

  - Tapable.js:195 Compilation.applyPluginsAsyncSeries
    [engi]/[tapable]/lib/Tapable.js:195:46

  - Compilation.js:662 sealPart2
    [engi]/[webpack]/lib/Compilation.js:662:9

  - Tapable.js:195 Compilation.applyPluginsAsyncSeries
    [engi]/[tapable]/lib/Tapable.js:195:46

  webpack: Failed to compile.
</code>```

答:
Remove the ! from your directory name.

(Adding here from the comment for resolution)

Body:
I want to create and serve a ng app. The problem is that after following the installation of angular 5 (+ionic) I found myself have the same problem over and over again and I have no idea what is causing it. I don't really understand what is the issue but I cannot serve any angular app.

The way I can resolve this is by a complete format of C:\ drive and reinstall anything from scratch. Last time I did it was 2 days ago. And before that 7 days ago.

This is all the stuff I get in the cmd.exe:

D:\!MY PROJECTS\APP-test>ng new engi
create engi/e2e/app.e2e-spec.ts (286 bytes)
create engi/e2e/app.po.ts (208 bytes)
create engi/e2e/tsconfig.e2e.json (235 bytes)
create engi/karma.conf.js (923 bytes)
create engi/package.json (1309 bytes)
create engi/protractor.conf.js (722 bytes)
create engi/README.md (1020 bytes)
create engi/tsconfig.json (363 bytes)
create engi/tslint.json (3097 bytes)
create engi/.angular-cli.json (1239 bytes)
create engi/.editorconfig (245 bytes)
create engi/.gitignore (516 bytes)
create engi/src/assets/.gitkeep (0 bytes)
create engi/src/environments/environment.prod.ts (51 bytes)
create engi/src/environments/environment.ts (387 bytes)
create engi/src/favicon.ico (5430 bytes)
create engi/src/index.html (291 bytes)
create engi/src/main.ts (370 bytes)
create engi/src/polyfills.ts (2405 bytes)
create engi/src/styles.css (80 bytes)
create engi/src/test.ts (1085 bytes)
create engi/src/tsconfig.app.json (211 bytes)
create engi/src/tsconfig.spec.json (304 bytes)
create engi/src/typings.d.ts (104 bytes)
create engi/src/app/app.module.ts (316 bytes)
create engi/src/app/app.component.html (1141 bytes)
create engi/src/app/app.component.spec.ts (986 bytes)
create engi/src/app/app.component.ts (207 bytes)
create engi/src/app/app.component.css (0 bytes)
Installing packages for tooling via npm.
Installed packages for tooling via npm.
Project 'engi' successfully created.

D:\!MY PROJECTS\APP-test>cd engi

D:\!MY PROJECTS\APP-test\engi>ng serve
** NG Live Development Server is listening on localhost:4200, open your
browser on http://localhost:4200/ **
Date: 2017-12-04T19:00:14.752Z
Hash: 96b1bdc547c1ab33ed03
Time: 4145ms
chunk {inline} inline.bundle.js (inline) 5.79 kB [entry] [rendered]
chunk {main} main.bundle.js (main) 3.25 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js (polyfills) 257 bytes [initial]
[rendered]
chunk {styles} styles.bundle.js (styles) 246 bytes [initial] [rendered]
chunk {vendor} vendor.bundle.js (vendor) 861 kB [initial] [rendered]

ERROR in multi webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts
Module not found: Error: Can't resolve 'D:\' in 'D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\models\webpack-configs'
resolve 'D:\' in 'D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\models\webpack-configs'
Parsed request is a directory
using description file: D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\package.json (relative path:
./models/webpack-configs)
after using description file: D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\package.json (relative path:
./models/webpack-configs)
No description file found
as directory
    existing directory
        using path: D:\index
          No description file found
        after using path: D:\index
          no extension
            D:\index doesn't exist
          .js
            D:\index.js doesn't exist
          .json
            D:\index.json doesn't exist
[D:\package.json]
[D:\index\package.json]
[D:\index]
[D:\index.js]
[D:\index.json]
 @ multi webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts
ERROR in multi ./src/polyfills.ts
Module not found: Error: Can't resolve 'D:\' in 'D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\models\webpack-configs'
resolve 'D:\' in 'D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\models\webpack-configs'
Parsed request is a directory
using description file: D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\package.json (relative path:
./models/webpack-configs)
after using description file: D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\package.json (relative path:
./models/webpack-configs)
    No description file found
    as directory
      existing directory
        using path: D:\index
          No description file found
        after using path: D:\index
          no extension
            D:\index doesn't exist
          .js
            D:\index.js doesn't exist
          .json
            D:\index.json doesn't exist
[D:\package.json]
[D:\index\package.json]
[D:\index]
[D:\index.js]
[D:\index.json]
 @ multi ./src/polyfills.ts
ERROR in multi ./src/styles.css
Module not found: Error: Can't resolve 'D:\' in 'D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\models\webpack-configs'
resolve 'D:\' in 'D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\models\webpack-configs'
  Parsed request is a directory
  using description file: D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\package.json (relative path:
./models/webpack-configs)
  after using description file: D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\package.json (relative path:
./models/webpack-configs)
    No description file found
    as directory
      existing directory
        using path: D:\index
          No description file found
        after using path: D:\index
          no extension
            D:\index doesn't exist
          .js
            D:\index.js doesn't exist
          .json
            D:\index.json doesn't exist
[D:\package.json]
[D:\index\package.json]
[D:\index]
[D:\index.js]
[D:\index.json]
 @ multi ./src/styles.css
ERROR in   Error: Child compilation failed:
  Entry module not found: Error: Can't resolve 'D:\' in 'D:\!MY
PROJECTS\APP-test\engi\node_modules\@angular\cli\models\webpack-configs':
  Error: Can't resolve 'D:\' in 'D:\!MY PROJECTS\APP-
test\engi\node_modules\@angular\cli\models\webpack-configs'

  - compiler.js:76
    [engi]/[html-webpack-plugin]/lib/compiler.js:76:16

  - Compiler.js:304 compile
    [engi]/[webpack]/lib/Compiler.js:304:11

  - Compiler.js:514 applyPluginsAsync.err
    [engi]/[webpack]/lib/Compiler.js:514:14

  - Tapable.js:202 next
    [engi]/[tapable]/lib/Tapable.js:202:11

  - CachePlugin.js:78 Compiler.<anonymous>
    [engi]/[webpack]/lib/CachePlugin.js:78:5

  - Tapable.js:206 Compiler.applyPluginsAsyncSeries
    [engi]/[tapable]/lib/Tapable.js:206:13

  - Compiler.js:511 compilation.seal.err
    [engi]/[webpack]/lib/Compiler.js:511:11

  - Tapable.js:195 Compilation.applyPluginsAsyncSeries
    [engi]/[tapable]/lib/Tapable.js:195:46

  - Compilation.js:680 self.applyPluginsAsync.err
    [engi]/[webpack]/lib/Compilation.js:680:19

  - Tapable.js:195 Compilation.applyPluginsAsyncSeries
    [engi]/[tapable]/lib/Tapable.js:195:46

  - Compilation.js:671 self.applyPluginsAsync.err
    [engi]/[webpack]/lib/Compilation.js:671:11

  - Tapable.js:195 Compilation.applyPluginsAsyncSeries
    [engi]/[tapable]/lib/Tapable.js:195:46

  - Compilation.js:666 self.applyPluginsAsync.err
    [engi]/[webpack]/lib/Compilation.js:666:10

  - Tapable.js:195 Compilation.applyPluginsAsyncSeries
    [engi]/[tapable]/lib/Tapable.js:195:46

  - Compilation.js:662 sealPart2
    [engi]/[webpack]/lib/Compilation.js:662:9

  - Tapable.js:195 Compilation.applyPluginsAsyncSeries
    [engi]/[tapable]/lib/Tapable.js:195:46

  webpack: Failed to compile.


来源: stackexchange

问:
Drag/Drop events return undefined
I'm trying to do an inventory system for a RPG. I want an user to be able to drag an item from their inventory and drop it into a character slot and equip it.

```<code>this.dragItem = function(event) {
    event.dataTransfer.setData("text", event.target.id);
}
</code>```

The element I intended to drag is

```<code>$('<div>', {
    class: 'HUDInventoryItem',
    id: `${i}`,
    draggable: 'true',
    ondragstart: 'inventoryWindow.dragItem()'
}).appendTo('#inventoryWindowItems');
</code>```

I used dragItem() to get the data andthe first error that I got when I dragged an item was

Uncaught TypeError: Cannot read property 'dataTransfer' of undefined

I added console.log(event) to see the event object, and it returns an undefined object. What am I doing wrong?

答:
You're not passing in the event to the function. Try this:</p>

```<code>$('<div>', {
    class: 'HUDInventoryItem',
    id: `${i}`,
    draggable: 'true',
    ondragstart: 'inventoryWindow.dragItem(event)'
}).appendTo('#inventoryWindowItems');
</code>```

ContentLicense: CC BY-SA 3.0

Title: Drag/Drop events return undefined

Body:
I'm trying to do an inventory system for a RPG. I want an user to be able to drag an item from their inventory and drop it into a character slot and equip it.

this.dragItem = function(event) {
    event.dataTransfer.setData("text", event.target.id);
}

The element I intended to drag is

$('
', {
    class: 'HUDInventoryItem',
    id: `${i}`,
    draggable: 'true',
    ondragstart: 'inventoryWindow.dragItem()'
}).appendTo('#inventoryWindowItems');

I used dragItem() to get the data andthe first error that I got when I dragged an item was

Uncaught TypeError: Cannot read property 'dataTransfer' of undefined

I added console.log(event) to see the event object, and it returns an undefined object. What am I doing wrong?

Body:
You're not passing in the event to the function. Try this:

$('<div>', {
    class: 'HUDInventoryItem',
    id: `${i}`,
    draggable: 'true',
    ondragstart: 'inventoryWindow.dragItem(event)'
}).appendTo('#inventoryWindowItems');


问:
Remove an item from a list view
If I want to remove an item from my list view by tapping it, do I remove the object from the ArrayList I'm using with my ArrayAdapter, or do I remove the object directly from the adapter and call the notifyDatasetChange?

Also I want to store the data from the list on the disk, do I save the adapter or the arraylist I use?

Here is the code: The idea I'm going for is to save the data from the list and load it back when the activity launches again, however once this happens I cannot delete items from the list anymore.

```<code>public class EditKeywords extends ListActivity implements Serializable{

    private ArrayList<String> keyWordList;
    private EditText keywordEditText;
    private IconicAdapter adapter;
    private Button enterButton;
    private int position;
    private Button finishedButton;
    public static final String KEYWORDS = "keywords";
    public static final String ADAPTER = "adapter";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.editkeyowords);
        getKeywordsAndAdapter();
        keywordEditText = (EditText) findViewById(R.id.keywordedittext);
        setListAdapter(adapter);

        enterButton = (Button) findViewById(R.id.enterkeywords);
        enterButton.setOnClickListener(enterButtonListener);

        finishedButton = (Button) findViewById(R.id.finishedbutton);
        finishedButton.setOnClickListener(finishedButtonListener);
    }

    public void onResume(){
    super.onResume();
    getKeywordsAndAdapter();
    }

    public void onPause(Bundle savedInstanceState){
    super.onPause();
    writeKeywordsAndAdapter();
    }

    public void getKeywordsAndAdapter(){
    try {
        InputStream fi = openFileInput(KEYWORDS);

        if (fi!=null) {
            ObjectInputStream in = new ObjectInputStream(fi);
                    keyWordList = (ArrayList<String>) in.readObject();
                    in.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
            .show();
    }
    if(keyWordList == null){
        keyWordList = new ArrayList<String>();
    }

    try {
        InputStream fi = openFileInput(ADAPTER);

        if (fi!=null) {
            ObjectInputStream in = new ObjectInputStream(fi);
                adapter = (IconicAdapter) in.readObject();
                in.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
            .show();
    }
    if(adapter == null){
        adapter = new IconicAdapter();
    }
    }

    public void writeKeywordsAndAdapter(){

    try {
        OutputStream fi = openFileOutput(KEYWORDS, 0);

        if (fi!=null) {
            ObjectOutputStream out = new ObjectOutputStream(fi);
                out.writeObject(keyWordList);
                out.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
            .show();
    }

    try {
        OutputStream fi = openFileOutput(ADAPTER, 0);

        if (fi!=null) {
            ObjectOutputStream out = new ObjectOutputStream(fi);
            out.writeObject(adapter);
            out.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
            .show();
    }

    }

    public void onListItemClick(ListView parent, View v,
        int aPosition, long id) {

        ImageView image = (ImageView) findViewById(R.id.icon1);
        image.setImageResource(R.drawable.delete);
        image.setOnClickListener(deleteImageListener);
        getListView().getChildAt(aPosition).invalidate();
        //adapter.notifyDataSetInvalidated();
        position = aPosition;
    }

    public void startHome() {
    Intent intent = new Intent(this, ECS.class);
    this.startActivity(intent);
    finish();
    }

    public class IconicAdapter extends ArrayAdapter<String> implements Serializable {
    private static final long serialVersionUID = 6175078429973952022L;

    IconicAdapter() {
        super(EditKeywords.this, R.layout.rowkeywords, keyWordList);
    }

    public View getView(int position, View convertView,ViewGroup parent) {
        LayoutInflater inflater=getLayoutInflater();

        View row=inflater.inflate(R.layout.rowkeywords, parent, false);
        TextView label=(TextView)row.findViewById(R.id.label1);

        label.setText(keyWordList.get(position));
        return(row);
    }
    }

    private OnClickListener enterButtonListener = new OnClickListener() {

    @Override
    public void onClick(View arg0){

        if(keywordEditText.getText().toString() != ""){
        boolean unique = true;
        for(String s : keyWordList){
            if(s.equals(keywordEditText.getText().toString())){
            unique = false;
            }
        }
        if(unique == true){
            adapter.add(keywordEditText.getText().toString());
            keywordEditText.setText("");
            adapter.notifyDataSetChanged();
        }
        }
    }
    };

    private OnClickListener deleteImageListener = new OnClickListener() {

    @Override
    public void onClick(View arg0){
        //keyWordList.remove(position);
        adapter.remove(keyWordList.get(0));
        adapter.notifyDataSetChanged();
        writeKeywordsAndAdapter();

    }
    };

    private OnClickListener finishedButtonListener = new OnClickListener() {

    @Override
    public void onClick(View arg0){
       writeKeywordsAndAdapter();
       startHome();
    }
    };

}
</code>```

答:
Changing the ArrayList or adapter should have the same effect, since the adapter is just looking at the ArrayList.  In either case you need to announce the change via notifyDatasetChanged.

As f20k mentioned, lots of options for storing data are explained in the data storage guide.  It doesn't make sense to talk about storing an adapter or array list, you would be storing the data within that list.

ContentLicense: CC BY-SA 2.5

Title: Remove an item from a list view

Body:
If I want to remove an item from my list view by tapping it, do I remove the object from the ArrayList I'm using with my ArrayAdapter, or do I remove the object directly from the adapter and call the notifyDatasetChange?

Also I want to store the data from the list on the disk, do I save the adapter or the arraylist I use?

Here is the code: The idea I'm going for is to save the data from the list and load it back when the activity launches again, however once this happens I cannot delete items from the list anymore.

public class EditKeywords extends ListActivity implements Serializable{

    private ArrayList<String> keyWordList;
    private EditText keywordEditText;
    private IconicAdapter adapter;
    private Button enterButton;
    private int position;
    private Button finishedButton;
    public static final String KEYWORDS = "keywords";
    public static final String ADAPTER = "adapter";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.editkeyowords);
        getKeywordsAndAdapter();
        keywordEditText = (EditText) findViewById(R.id.keywordedittext);
        setListAdapter(adapter);

        enterButton = (Button) findViewById(R.id.enterkeywords);
        enterButton.setOnClickListener(enterButtonListener);

        finishedButton = (Button) findViewById(R.id.finishedbutton);
        finishedButton.setOnClickListener(finishedButtonListener);
    }

    public void onResume(){
    super.onResume();
    getKeywordsAndAdapter();
    }

    public void onPause(Bundle savedInstanceState){
    super.onPause();
    writeKeywordsAndAdapter();
    }

    public void getKeywordsAndAdapter(){
    try {
        InputStream fi = openFileInput(KEYWORDS);

        if (fi!=null) {
            ObjectInputStream in = new ObjectInputStream(fi);
                    keyWordList = (ArrayList<String>) in.readObject();
                    in.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
            .show();
    }
    if(keyWordList == null){
        keyWordList = new ArrayList<String>();
    }

    try {
        InputStream fi = openFileInput(ADAPTER);

        if (fi!=null) {
            ObjectInputStream in = new ObjectInputStream(fi);
                adapter = (IconicAdapter) in.readObject();
                in.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
            .show();
    }
    if(adapter == null){
        adapter = new IconicAdapter();
    }
    }

    public void writeKeywordsAndAdapter(){

    try {
        OutputStream fi = openFileOutput(KEYWORDS, 0);

        if (fi!=null) {
            ObjectOutputStream out = new ObjectOutputStream(fi);
                out.writeObject(keyWordList);
                out.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
            .show();
    }

    try {
        OutputStream fi = openFileOutput(ADAPTER, 0);

        if (fi!=null) {
            ObjectOutputStream out = new ObjectOutputStream(fi);
            out.writeObject(adapter);
            out.close();
        }
    }
    catch (java.io.FileNotFoundException e) {
        // that's OK, we probably haven't created it yet
    }
    catch (Throwable t) {
        Toast
            .makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
            .show();
    }

    }

    public void onListItemClick(ListView parent, View v,
        int aPosition, long id) {

        ImageView image = (ImageView) findViewById(R.id.icon1);
        image.setImageResource(R.drawable.delete);
        image.setOnClickListener(deleteImageListener);
        getListView().getChildAt(aPosition).invalidate();
        //adapter.notifyDataSetInvalidated();
        position = aPosition;
    }

    public void startHome() {
    Intent intent = new Intent(this, ECS.class);
    this.startActivity(intent);
    finish();
    }

    public class IconicAdapter extends ArrayAdapter<String> implements Serializable {
    private static final long serialVersionUID = 6175078429973952022L;

    IconicAdapter() {
        super(EditKeywords.this, R.layout.rowkeywords, keyWordList);
    }

    public View getView(int position, View convertView,ViewGroup parent) {
        LayoutInflater inflater=getLayoutInflater();

        View row=inflater.inflate(R.layout.rowkeywords, parent, false);
        TextView label=(TextView)row.findViewById(R.id.label1);

        label.setText(keyWordList.get(position));
        return(row);
    }
    }

    private OnClickListener enterButtonListener = new OnClickListener() {

    @Override
    public void onClick(View arg0){

        if(keywordEditText.getText().toString() != ""){
        boolean unique = true;
        for(String s : keyWordList){
            if(s.equals(keywordEditText.getText().toString())){
            unique = false;
            }
        }
        if(unique == true){
            adapter.add(keywordEditText.getText().toString());
            keywordEditText.setText("");
            adapter.notifyDataSetChanged();
        }
        }
    }
    };

    private OnClickListener deleteImageListener = new OnClickListener() {

    @Override
    public void onClick(View arg0){
        //keyWordList.remove(position);
        adapter.remove(keyWordList.get(0));
        adapter.notifyDataSetChanged();
        writeKeywordsAndAdapter();

    }
    };

    private OnClickListener finishedButtonListener = new OnClickListener() {

    @Override
    public void onClick(View arg0){
       writeKeywordsAndAdapter();
       startHome();
    }
    };

}


问:
How to create a GUID in Excel?
I need a function to add a GUID to cells in excel. I found this previous question on stackoverflow, but it is not working. It suggests the following function:

```<code>=CONCATENATE(DEC2HEX(RANDBETWEEN(0,4294967295),8),"-",DEC2HEX(RANDBETWEEN(0,65535),4),"-"
    ,DEC2HEX(RANDBETWEEN(16384,20479),4),"-",DEC2HEX(RANDBETWEEN(32768,49151),4),"-"
    ,DEC2HEX(RANDBETWEEN(0,65535),4),DEC2HEX(RANDBETWEEN(0,4294967295),8))
</code>```

I have been unable to get the concatenate method to work, and so tried it using the "&" figure to concatenate anyway. That seemed to work, but then I get an inexplicable error on the second DEX2HEX block: DEC2HEX(RANDBETWEEN(0,65535),4). The Excel formula evaluator says it's invalid, but I can't seem to figure out why at all. Any ideas?

答:
The formula for Dutch Excel:</p>

```<code>=KLEINE.LETTERS(
    TEKST.SAMENVOEGEN(
        DEC.N.HEX(ASELECTTUSSEN(0;MACHT(16;8));8);"-";
        DEC.N.HEX(ASELECTTUSSEN(0;MACHT(16;4));4);"-";"4";
        DEC.N.HEX(ASELECTTUSSEN(0;MACHT(16;3));3);"-";
        DEC.N.HEX(ASELECTTUSSEN(8;11));
        DEC.N.HEX(ASELECTTUSSEN(0;MACHT(16;3));3);"-";
        DEC.N.HEX(ASELECTTUSSEN(0;MACHT(16;8));8);
        DEC.N.HEX(ASELECTTUSSEN(0;MACHT(16;4));4)
    )
)
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to create a GUID in Excel?

Body:
I need a function to add a GUID to cells in excel. I found this previous question on stackoverflow, but it is not working. It suggests the following function:

=CONCATENATE(DEC2HEX(RANDBETWEEN(0,4294967295),8),"-",DEC2HEX(RANDBETWEEN(0,65535),4),"-"
    ,DEC2HEX(RANDBETWEEN(16384,20479),4),"-",DEC2HEX(RANDBETWEEN(32768,49151),4),"-"
    ,DEC2HEX(RANDBETWEEN(0,65535),4),DEC2HEX(RANDBETWEEN(0,4294967295),8))

I have been unable to get the concatenate method to work, and so tried it using the "&" figure to concatenate anyway. That seemed to work, but then I get an inexplicable error on the second DEX2HEX block: DEC2HEX(RANDBETWEEN(0,65535),4). The Excel formula evaluator says it's invalid, but I can't seem to figure out why at all. Any ideas?

Body:
The formula for Dutch Excel:

=KLEINE.LETTERS(
    TEKST.SAMENVOEGEN(
        DEC.N.HEX(ASELECTTUSSEN(0;MACHT(16;8));8);"-";
        DEC.N.HEX(ASELECTTUSSEN(0;MACHT(16;4));4);"-";"4";
        DEC.N.HEX(ASELECTTUSSEN(0;MACHT(16;3));3);"-";
        DEC.N.HEX(ASELECTTUSSEN(8;11));
        DEC.N.HEX(ASELECTTUSSEN(0;MACHT(16;3));3);"-";
        DEC.N.HEX(ASELECTTUSSEN(0;MACHT(16;8));8);
        DEC.N.HEX(ASELECTTUSSEN(0;MACHT(16;4));4)
    )
)


问:
Acces Outlook via Visual Basic error
I'm trying to create a program which retrieves all emails from Outlook's(2007 desktop version) Inbox and puts them into a DataGridView.

Code:

```<code>Imports Outlook = Microsoft.Office.Interop.Outlook

Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim dt As DataTable
    Try
        Dim app As Outlook.Application = New Outlook.Application()
        Dim ns As Outlook.[NameSpace] = app.GetNamespace("MAPI")
        Dim inbox As Outlook.MAPIFolder = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
        ns.SendAndReceive(True)
        dt = New DataTable("Inbox")
        dt.Columns.Add("Subject", GetType(String))
        dt.Columns.Add("Sender", GetType(String))
        dt.Columns.Add("Body", GetType(String))
        dt.Columns.Add("Date", GetType(String))
        DataGridView1.DataSource = dt
        For Each item As Object In inbox.Items
            If TypeOf item Is Outlook.MailItem Then
                Dim item1 As Outlook.MailItem = CType(item, Outlook.MailItem)
                dt.Rows.Add(New Object() {item1.Subject, item1.Sender, item1.HTMLBody, item1.SentOn.ToLongDateString() & "" + item1.SentOn.ToLongTimeString()})
            End If
        Next
        MessageBox.Show("done")
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.[Error])
    End Try
End Sub
End Class
</code>```

When I try to Build the project I'm getting the follow error:

System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

UPDATE

I've changed the Compiler CPU to x86 and x64, this does not solve the error.

Target platform

答:
What is the target platform of your application? Is it a x86-based application?

The problem (probably) that the COM class (which is in a 32 bit COM dll) is registered, but since the application is running in 64 bit mode it won't find a correct registration (32 bit and 64 bit COM servers are registered separately).

Also you may find the How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))? page helpful.

Title: Acces Outlook via Visual Basic error

Body:
I'm trying to create a program which retrieves all emails from Outlook's(2007 desktop version) Inbox and puts them into a DataGridView.

Code:

Imports Outlook = Microsoft.Office.Interop.Outlook

Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim dt As DataTable
    Try
        Dim app As Outlook.Application = New Outlook.Application()
        Dim ns As Outlook.[NameSpace] = app.GetNamespace("MAPI")
        Dim inbox As Outlook.MAPIFolder = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
        ns.SendAndReceive(True)
        dt = New DataTable("Inbox")
        dt.Columns.Add("Subject", GetType(String))
        dt.Columns.Add("Sender", GetType(String))
        dt.Columns.Add("Body", GetType(String))
        dt.Columns.Add("Date", GetType(String))
        DataGridView1.DataSource = dt
        For Each item As Object In inbox.Items
            If TypeOf item Is Outlook.MailItem Then
                Dim item1 As Outlook.MailItem = CType(item, Outlook.MailItem)
                dt.Rows.Add(New Object() {item1.Subject, item1.Sender, item1.HTMLBody, item1.SentOn.ToLongDateString() & "" + item1.SentOn.ToLongTimeString()})
            End If
        Next
        MessageBox.Show("done")
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.[Error])
    End Try
End Sub
End Class

When I try to Build the project I'm getting the follow error:

System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

UPDATE

I've changed the Compiler CPU to x86 and x64, this does not solve the error.

Target platform


问:
Is there an Objective C equivalent of the JavaScript method encode()?
```<code>NSString *searchString = @"Lyngbø";
NSLog("%@",[searchString stringByAddingPercentEscapeUsingEncoding:NSUTF8StringEncoding]);
</code>```

This gives me : Lyng%C3%B8

```<code><script type="text/javascript">
document.write(escape("Lyngbø"));
</script>
</code>```

This gives me : Lyngb%F8

The web search engine i am developing against doesnt understand the Objectiv C's way of encoding the string, and returns nothing when searching for words that contains either æ. ø or å

答: Charset difference. Instead of NSUTF8StringEncoding, use NSISOLatin1StringEncoding.

Body:
NSString *searchString = @"Lyngbø";
NSLog("%@",[searchString stringByAddingPercentEscapeUsingEncoding:NSUTF8StringEncoding]);

This gives me : Lyng%C3%B8

This gives me : Lyngb%F8

The web search engine i am developing against doesnt understand the Objectiv C's way of encoding the string, and returns nothing when searching for words that contains either æ. ø or å


问:
Angular Material programmatically change Tab labels
I am using Angular 5.0.0 with Material 5.0.0-rc.1.  I have a tab group where I want the last tab to always have an extra icon button as part of the label.

Here is the existing code for the tab group:

```<code><mat-tab-group #revTabGroup class="tab-group" [(selectedIndex)]="selectedTab">
    <mat-tab *ngFor="let rev of proposal.revisions" label="{{rev.revisionID}}">
        <proposal-revision [proposalRevision]="rev"></proposal-revision>
    </mat-tab>
</mat-tab-group>
</code>```

I want <button mat-icon-button matTooltip="Delete This Item"><mat-icon>delete_forever</mat-icon></button> to show up next to the revisionID on the last tab only.  The number of tabs will change, so there needs to be a function or something to call to update which tab has the button after changes are made.

First, is it even possible to display a button on the tab label, or can you only add text?

Second, is there a way to programmatically set the label, maybe something like this.revTabGroup.???.textLabel = "<button> ... </button>"?

I even thought that maybe this could be done using css, something like:

```<code>.mat-tab-labels:last-child {
    ...
}
</code>```

However, I couldn't get anything to work.  Anyone have any ideas or know if this is possible?

答:
You can use Angular's last key in ngFor loops:

```<code><mat-tab-group #revTabGroup class="tab-group" [(selectedIndex)]="selectedTab">
    <mat-tab *ngFor="let rev of proposal.revisions; let last = last;" [label]="rev.revisionID">
          <ng-template md-tab-label>
            {{rev.revisionID}}
            <button *ngIf="last" mat-icon-button matTooltip="Delete This Item"><mat-icon>delete_forever</mat-icon></button>
          </ng-template>
        <proposal-revision [proposalRevision]="rev"></proposal-revision>

    </mat-tab>
</mat-tab-group>
</code>```

Body:
I am using Angular 5.0.0 with Material 5.0.0-rc.1.  I have a tab group where I want the last tab to always have an extra icon button as part of the label.

Here is the existing code for the tab group:

<mat-tab-group #revTabGroup class="tab-group" [(selectedIndex)]="selectedTab">
    <mat-tab *ngFor="let rev of proposal.revisions" label="{{rev.revisionID}}">
        <proposal-revision [proposalRevision]="rev"></proposal-revision>
    </mat-tab>
</mat-tab-group>

I want <button mat-icon-button matTooltip="Delete This Item"><mat-icon>delete_forever</mat-icon></button> to show up next to the revisionID on the last tab only.  The number of tabs will change, so there needs to be a function or something to call to update which tab has the button after changes are made.

First, is it even possible to display a button on the tab label, or can you only add text?

Second, is there a way to programmatically set the label, maybe something like this.revTabGroup.???.textLabel = "<button> ... </button>"?

I even thought that maybe this could be done using css, something like:

.mat-tab-labels:last-child {
    ...
}

However, I couldn't get anything to work.  Anyone have any ideas or know if this is possible?

Body:
You can use Angular's last key in ngFor loops:

<mat-tab-group #revTabGroup class="tab-group" [(selectedIndex)]="selectedTab">
    <mat-tab *ngFor="let rev of proposal.revisions; let last = last;" [label]="rev.revisionID">
          <ng-template md-tab-label>
            {{rev.revisionID}}
            <button *ngIf="last" mat-icon-button matTooltip="Delete This Item"><mat-icon>delete_forever</mat-icon></button>
          </ng-template>
        <proposal-revision [proposalRevision]="rev"></proposal-revision>

    </mat-tab>
</mat-tab-group>


问:
Espresso toast test fails if second test is added
I have an activity that can display different toasts depending on the status returned from a web service call.

I am writing a test class, and my first test tests that one of these toasts is displayed when there's a network error. Below is the test class:

```<code>@RunWith(AndroidJUnit4.class)
public class LoginActivityTest extends BaseTest {

    @Rule
    public final ActivityTestRule<LoginActivity> login = new ActivityTestRule(LoginActivity.class, true);

    @Test
    public void noNetwork() {
        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
            @Override
            public void run() {
                login.getActivity().onEventMainThread(new LoginResp(CopiaWebServiceClient.ResponseStatus.NETWORK_ERROR));
            }
        });

        onView(withText(R.string.toast_no_network_connection))
            .inRoot(withDecorView(not(is(login.getActivity().getWindow().getDecorView()))))
            .check(matches(isDisplayed()));
    }
}
</code>```

So the noNetwork test calls LoginActivity's onEventMainThread(LoginResp loginResp) method (this needs to run on the UI thread, hence my use of runOnMainSync) with a network error status to prompt it to show the expected toast_no_network_connection toast.

This test works and runs and passes successfully.

This is my issue:

If I add a second test to the test class, the second test fails. This is the second test, identical to the first except that it passes a different error status to onEventMainThread(LoginResp loginResp) so that a different toast will be shown:

```<code>    @Test
    public void serverErr() {
       InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
            @Override
            public void run() {
                login.getActivity().onEventMainThread(new LoginResp(CopiaWebServiceClient.ResponseStatus.HTTP_SERVER_ERROR));
            }
        });

        onView(withText(R.string.toast_operation_failure_app_error))
            .inRoot(withDecorView(not(is(login.getActivity().getWindow().getDecorView()))))
            .check(matches(isDisplayed()));
    }
</code>```

The second test fails with output: android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with string from resource id: <2131689669>[toast_operation_failure_app_error] value: Sorry, failure to complete operation due to application error.

However, watching the emulator while running the tests I see both the initial toast_no_network_connection toast (expected by the first test), and then the toast_operation_failure_app_error toast (expected by the second test). Why does the second test fail?

It has something to do with the tests running one after the other, because when I comment out the first test, the second test passes.

My onEventMainThread(LoginResp loginResp) method in LoginActivity has the following code that shows an appropriate toast based on status:

```<code>switch (status) {

        case HTTP_UNAUTHORIZED:
            DialogCreator.createAlertDialog(this, getString(R.string.dialog_msg_login_fail)).show();

            break;

        case NETWORK_ERROR:
            Toast.makeText(this, getString(R.string.toast_no_network_connection), Toast.LENGTH_SHORT).show();

            break;

        default:
            Toast.makeText(this, getString(R.string.toast_operation_failure_app_error), Toast.LENGTH_SHORT).show();

    }
</code>```

Debugging the test I see that the first test enters the NETWORK_ERROR case, as expected, and the second test enters the switch statement's default section, also as expected.

答:
After some further playing with the tests I opted for an approach suggested by Eirik W's answer from Espresso checking if toasts are displayed (one on top of another)

I changed my production code slightly to add a @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) annotated Toast member to LoginActivity to enable an @After annotated method in LoginActivityTest cancel any showing toast after each test.

Body:
I have an activity that can display different toasts depending on the status returned from a web service call.

I am writing a test class, and my first test tests that one of these toasts is displayed when there's a network error. Below is the test class:

@RunWith(AndroidJUnit4.class)
public class LoginActivityTest extends BaseTest {

    @Rule
    public final ActivityTestRule<LoginActivity> login = new ActivityTestRule(LoginActivity.class, true);

    @Test
    public void noNetwork() {
        InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
            @Override
            public void run() {
                login.getActivity().onEventMainThread(new LoginResp(CopiaWebServiceClient.ResponseStatus.NETWORK_ERROR));
            }
        });

        onView(withText(R.string.toast_no_network_connection))
            .inRoot(withDecorView(not(is(login.getActivity().getWindow().getDecorView()))))
            .check(matches(isDisplayed()));
    }
}

So the noNetwork test calls LoginActivity's onEventMainThread(LoginResp loginResp) method (this needs to run on the UI thread, hence my use of runOnMainSync) with a network error status to prompt it to show the expected toast_no_network_connection toast.

This test works and runs and passes successfully.

This is my issue:

If I add a second test to the test class, the second test fails. This is the second test, identical to the first except that it passes a different error status to onEventMainThread(LoginResp loginResp) so that a different toast will be shown:

    @Test
    public void serverErr() {
       InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() {
            @Override
            public void run() {
                login.getActivity().onEventMainThread(new LoginResp(CopiaWebServiceClient.ResponseStatus.HTTP_SERVER_ERROR));
            }
        });

        onView(withText(R.string.toast_operation_failure_app_error))
            .inRoot(withDecorView(not(is(login.getActivity().getWindow().getDecorView()))))
            .check(matches(isDisplayed()));
    }

The second test fails with output: android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with string from resource id: <2131689669>[toast_operation_failure_app_error] value: Sorry, failure to complete operation due to application error.

However, watching the emulator while running the tests I see both the initial toast_no_network_connection toast (expected by the first test), and then the toast_operation_failure_app_error toast (expected by the second test). Why does the second test fail?

It has something to do with the tests running one after the other, because when I comment out the first test, the second test passes.

My onEventMainThread(LoginResp loginResp) method in LoginActivity has the following code that shows an appropriate toast based on status:

switch (status) {

        case HTTP_UNAUTHORIZED:
            DialogCreator.createAlertDialog(this, getString(R.string.dialog_msg_login_fail)).show();

            break;

        case NETWORK_ERROR:
            Toast.makeText(this, getString(R.string.toast_no_network_connection), Toast.LENGTH_SHORT).show();

            break;

        default:
            Toast.makeText(this, getString(R.string.toast_operation_failure_app_error), Toast.LENGTH_SHORT).show();

    }

Debugging the test I see that the first test enters the NETWORK_ERROR case, as expected, and the second test enters the switch statement's default section, also as expected.


问:
Moving an an entire row from one position to another
I have 5 rows from my query results and i want to know if its even possible to move an entire row from one position to another. For example the third row to the first row.

Below is my sql code:

```<code>DECLARE @ClientID int = 1041
DECLARE @ProfileID int =2520
DECLARE @PageType tinyint = 2
BEGIN
WITH SortedList
    AS (
        SELECT PageID, PageName, PageTitle, PageUrl, ParentID,
            CAST((PageName) AS VARCHAR(1000)) AS "Path"
            FROM Pagelist p
            WHERE p.ParentId IS NULL and p.PageType=@PageType
        UNION ALL
        SELECT p.PageID, p.PageName, p.PageTitle, p.PageUrl, p.ParentID,
            CAST((a.path + '/' + p.PageName) AS VARCHAR(1000)) AS "Path"
            FROM Pagelist AS p
                JOIN SortedList AS a
                ON p.ParentID = a.PageID
            WHERE  p.PageType=@PageType
       )
        SELECT a.PageID,a.PageTitle,a.ParentID,ua.Access,a.Path,a.PageName
        FROM SortedList as a,ProfilePageAccess ua,UserProfile up
        WHERE ua.ClientID=@ClientID and ua.PageID=a.PageID
            and up.ProfileID=ua.ProfileID and up.ProfileID=@ProfileID
        ORDER BY a.Path
</code>```

END

I want to be able to move the third row to first row.

This is my current results

```<code>PAGEID  PAGETITLE       PARENTID ACCESS  PATH                     PAGENAME
</code>```

```<code>001R    Administration   801       2     HRAdmin                   HrAdmin
002R    Performance      802       2     HRAdmin/AdminPer          AdminPer
003R    Overall Ratings  803       2     HRAdmin/AdminPerformance  Perform
004R    Score Ratings    804       2     HRAdmin/AdminPerformance  Perform
005R    Template Setup   805       2     HRAdmin/AdminPerformance  Perform
</code>```

答:
In your ORDER BY you have: ORDER BY a.Path

This is ordering by a.Path in ascending (alphabetical) order.

If you want to order by specific values of some other column, you can use an ORDER BY with a CASE Statement.

ex.

```<code>...

SELECT a.PageID,a.PageTitle,a.ParentID,ua.Access,a.Path,a.PageName
        FROM SortedList as a,ProfilePageAccess ua,UserProfile up
        WHERE ua.ClientID=@ClientID and ua.PageID=a.PageID
            and up.ProfileID=ua.ProfileID and up.ProfileID=@ProfileID
        ORDER BY CASE a.PageTitle
                  WHEN 'Overall Ratings' THEN 1
                  WHEN 'Score Ratings' THEN 2
                  ELSE 3
                 END
</code>```

Body:
I have 5 rows from my query results and i want to know if its even possible to move an entire row from one position to another. For example the third row to the first row.

Below is my sql code:

DECLARE @ClientID int = 1041
DECLARE @ProfileID int =2520
DECLARE @PageType tinyint = 2
BEGIN
WITH SortedList
    AS (
        SELECT PageID, PageName, PageTitle, PageUrl, ParentID,
            CAST((PageName) AS VARCHAR(1000)) AS "Path"
            FROM Pagelist p
            WHERE p.ParentId IS NULL and p.PageType=@PageType
        UNION ALL
        SELECT p.PageID, p.PageName, p.PageTitle, p.PageUrl, p.ParentID,
            CAST((a.path + '/' + p.PageName) AS VARCHAR(1000)) AS "Path"
            FROM Pagelist AS p
                JOIN SortedList AS a
                ON p.ParentID = a.PageID
            WHERE  p.PageType=@PageType
       )
        SELECT a.PageID,a.PageTitle,a.ParentID,ua.Access,a.Path,a.PageName
        FROM SortedList as a,ProfilePageAccess ua,UserProfile up
        WHERE ua.ClientID=@ClientID and ua.PageID=a.PageID
            and up.ProfileID=ua.ProfileID and up.ProfileID=@ProfileID
        ORDER BY a.Path

END

I want to be able to move the third row to first row.

This is my current results

PAGEID  PAGETITLE       PARENTID ACCESS  PATH                     PAGENAME

001R    Administration   801       2     HRAdmin                   HrAdmin
002R    Performance      802       2     HRAdmin/AdminPer          AdminPer
003R    Overall Ratings  803       2     HRAdmin/AdminPerformance  Perform
004R    Score Ratings    804       2     HRAdmin/AdminPerformance  Perform
005R    Template Setup   805       2     HRAdmin/AdminPerformance  Perform

Body:
In your ORDER BY you have: ORDER BY a.Path

This is ordering by a.Path in ascending (alphabetical) order.

If you want to order by specific values of some other column, you can use an ORDER BY with a CASE Statement.

ex.

...

SELECT a.PageID,a.PageTitle,a.ParentID,ua.Access,a.Path,a.PageName
        FROM SortedList as a,ProfilePageAccess ua,UserProfile up
        WHERE ua.ClientID=@ClientID and ua.PageID=a.PageID
            and up.ProfileID=ua.ProfileID and up.ProfileID=@ProfileID
        ORDER BY CASE a.PageTitle
                  WHEN 'Overall Ratings' THEN 1
                  WHEN 'Score Ratings' THEN 2
                  ELSE 3
                 END


答:
Your solution is correct, and can't be improved too much. You can get rid of the non-idiomatic use of var by replacing the for-loop with a foldLeft, and use some more syntactic sugar all around, but other than that it would remain the same:

```<code>val withTotal = df.withColumn("total", df.columns.map(col).reduce(_ + _))

val result = df.columns.foldLeft(withTotal) {
  (tmp, c) => tmp.withColumn(s"new_$c", $"$c" / $"total")
}
  .drop(df.columns: _*)
  .drop("total")
</code>```

Title: Spark: normalize each row of a DataFrame

Body:
I have a Spark DataFrame, which looks like the following

df.show()
+------+------+------+
|  col1|  col2|  col3|
+------+------+------+
|   5.0|   5.0|   0.0|
|   2.0|   3.0|   5.0|
|   4.0|   1.0|  10.0|
+------+------+------+

I would like to normalize each individual rows, such that after the operation, the new columns would look like:

+--------+--------+--------+
|new_col1|new_col2|new_col3|
+--------+--------+--------+
|     0.5|     0.5|     0.0|
|     0.2|     0.3|     0.5|
|0.266667|0.066667|0.666667|
+--------+--------+--------+

More formally, the operation I would like to apply is:

for each row,

    new_col_i = col_i / (col_1 + col_2 + col_3)

I will need to do this programmatically instead of listing all the columns, as my DataFrame has many columns.

Current solution:

The current solution I think of is to create a column to represent the sum of all the entries for each row, then divide each column by that sum column.

var newDF = df.withColumn("total", df.columns.map(c => col(c)).reduce((c1, c2) => c1 + c2))

for (c <- Array("col1", "col2", "col3")) {
    newDF = newDF.withColumn("normalized_" + c, col(c).divide(col("total")))
}
newDF.show()

+----+----+----+-----+-------------------+-------------------+------------------+
|col1|col2|col3|total|    normalized_col1|    normalized_col2|   normalized_col3|
+----+----+----+-----+-------------------+-------------------+------------------+
| 5.0| 5.0| 0.0| 10.0|                0.5|                0.5|               0.0|
| 2.0| 3.0| 5.0| 10.0|                0.2|                0.3|               0.5|
| 4.0| 1.0|10.0| 15.0|0.26666666666666666|0.06666666666666667|0.6666666666666666|
+----+----+----+-----+-------------------+-------------------+------------------+

Any alternative to make the code more succinct?

Body:
Your solution is correct, and can't be improved too much. You can get rid of the non-idiomatic use of var by replacing the for-loop with a foldLeft, and use some more syntactic sugar all around, but other than that it would remain the same:

val withTotal = df.withColumn("total", df.columns.map(col).reduce(_ + _))

val result = df.columns.foldLeft(withTotal) {
  (tmp, c) => tmp.withColumn(s"new_$c", $"$c" / $"total")
}
  .drop(df.columns: _*)
  .drop("total")


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
I can totally sympathize.  I have degrees in English and Film; the only programming I'd done before my latter twenties was on an Apply ][e, when I was 12.  Classic ASP was my first foray into Web programming, which I only learned because I had to, as a technical writer working on an intranet project documenting real-estate software.

But eventually programming took, and I decided to start learning how to do things right.  The transition wasn't easy.  But I can say learning C# for Web development, particularly if you don't already sort of "grok" OO, can be daunting -- mainly because OO is so much about creating and managing state and statefulness, and the Web is inherently stateless.

Believe it or not, I learned more about OO writing Ajax apps with JavaScript and Flex apps in ActionScript -- i.e., building stateful clients -- than I ever did trying to force C# into my brain, because Ajax apps and Flex apps force you to think about things in terms of state.  Returning to C# after having spent a couple of years (yes, a couple of years) writing lots of JavaScript code, and lots of Flex code, and reading lots and lots of both, was actually pretty easy, because by then, I realized how C# should work, as an OO language.

The Head First series of books is great, too -- people sort of downplay them around here, because they're rather silly, but they teach great concepts and I've been surprised how well their lessons have remained with me over the years.  Try the OO title.  And spend some time futzing around with JavaScript, too.  Maybe have a look at Douglas Crockford's work.  It'll click.  Just give it some time.

OwnerDisplayName: GregD

LastEditorDisplayName: GregD

OwnerDisplayName: Christian Nunciato


问:
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@b0baaa1 is not valid; is your activity running?
In recently, i always receive an error in android 7.1.1 that shows toast case crash. It's very strange, is anyone have the same problem?</p>

```<code>android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@b0baaa1 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:812)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:351)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.widget.Toast$TN.handleShow(Toast.java:489)
at android.widget.Toast$TN$2.handleMessage(Toast.java:360)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6475)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1134)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
</code>```

答:
Do you use Leak Canary? There's an open issue associated with Toast messages.

It looks like Leak Canary is trying to notify a user about the leak using no longer existing context.

Body:
In recently, i always receive an error in android 7.1.1 that shows toast case crash. It's very strange, is anyone have the same problem?

android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@b0baaa1 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:812)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:351)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.widget.Toast$TN.handleShow(Toast.java:489)
at android.widget.Toast$TN$2.handleMessage(Toast.java:360)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6475)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1134)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)


问:
How to disable skipping in JavaScript console.log()

I'm trying to measure time taken by a function to execute in JS.
When I try to console.log() the elapsed time, some blue numbers appear in the console and some of the logs are gone.

When I counted the appeared number, it matched with the number of lines of skipped log.

I'm sure you can notice the problem at the right part of screenshot.

I would like the console to show all of the logs.

Is there anything I can do? BTW, the browser is Firefox 58.0b8. (Developer Edition)

答: Rather than do console.log, why don't you write the time to an array a print that at the end of the test?</p>


问:
How do I deal with localStorage in jest tests?
I keep getting "localStorage is not defined" in Jest tests which makes sense but what are my options? Hitting brick walls.</p>

答:
Riffed off some other answers here to solve it for a project with Typescript. I created a LocalStorageMock like this:

```<code>export class LocalStorageMock {

    private store = {}

    clear() {
        this.store = {}
    }

    getItem(key: string) {
        return this.store[key] || null
    }

    setItem(key: string, value: string) {
        this.store[key] = value
    }

    removeItem(key: string) {
        delete this.store[key]
    }
}
</code>```

Then I created a LocalStorageWrapper class that I use for all access to local storage in the app instead of directly accessing the global local storage variable. Made it easy to set the mock in the wrapper for tests.

Body:
Riffed off some other answers here to solve it for a project with Typescript. I created a LocalStorageMock like this:

export class LocalStorageMock {

    private store = {}

    clear() {
        this.store = {}
    }

    getItem(key: string) {
        return this.store[key] || null
    }

    setItem(key: string, value: string) {
        this.store[key] = value
    }

    removeItem(key: string) {
        delete this.store[key]
    }
}

Then I created a LocalStorageWrapper class that I use for all access to local storage in the app instead of directly accessing the global local storage variable. Made it easy to set the mock in the wrapper for tests.


问:
how to remove spaces in a list that has a specific character
how do you get a list to fix the spaces in the list m.

```<code>m = ['m, a \n', 'l, n \n', 'c, l\n']
for i in m:
    if (' ') in i:
        i.strip(' ')
</code>```

I got:

```<code>'m, a \n'
'l, n \n'
'c, l\n'
</code>```

and I want it to return:

```<code>['m, a\n', 'l, n\n', 'c, l\n']
</code>```

答:
The strip() method will strip all the characters from the end of the string. In your case, strip starts at the end of your string, encounters a '\n' character, and exits.

It seems a little unclear what you are trying to do, but I will assume that you are looking to clear out any white space between the last non-whitespace character of your string and the newline. Correct me if I'm wrong.

There are many ways to do this, and this may not be the best, but here is what I came up with:

```<code>m = ['This, is a string. \n', 'another string!    \n', 'final example\n    ']

m = map(lambda(x): x.rstrip() + '\n' if x[-1] == '\n' else x.rstrip(' '), m)

print(m)

['This, is a string.\n', 'another string!\n', 'final example\n']
</code>```

Here I use the built in map function iterate over each list element and remove all white space from the end (rstrip() instead of strip() which does both the start and end) of the string, and add in a new line if there was one present in the original string.

Body:
how do you get a list to fix the spaces in the list m.

m = ['m, a \n', 'l, n \n', 'c, l\n']
for i in m:
    if (' ') in i:
        i.strip(' ')

I got:

'm, a \n'
'l, n \n'
'c, l\n'

and I want it to return:

['m, a\n', 'l, n\n', 'c, l\n']

Body:
The strip() method will strip all the characters from the end of the string. In your case, strip starts at the end of your string, encounters a '\n' character, and exits.

It seems a little unclear what you are trying to do, but I will assume that you are looking to clear out any white space between the last non-whitespace character of your string and the newline. Correct me if I'm wrong.

There are many ways to do this, and this may not be the best, but here is what I came up with:

m = ['This, is a string. \n', 'another string!    \n', 'final example\n    ']

m = map(lambda(x): x.rstrip() + '\n' if x[-1] == '\n' else x.rstrip(' '), m)

print(m)

['This, is a string.\n', 'another string!\n', 'final example\n']

Here I use the built in map function iterate over each list element and remove all white space from the end (rstrip() instead of strip() which does both the start and end) of the string, and add in a new line if there was one present in the original string.


问:
Left join, where clause
I'm wondering why this returns no values but if I place the "and r2.ref_nm = 'memberPrograStatusType" in the join clause it returns values. The 'memberPrograStatusType is null. </p>

```<code>`select mp.mbr_id
,r1.ref_desc as program_name
,r2.ref_desc as program_status
,mp.nom_dt
,mp.enrl_dt
,mp.end_dt
from icue.mbr_pgm mp
  left join icue.ref r1 on mp.pgm_typ_id = r1.ref_cd
  left join icue.ref r2 on mp.mbr_pgm_sts_typ_id = r2.ref_cd
where '15-JAN-17' between mp.enrl_dt and nvl(mp.end_dt,sysdate)
    and mp.mbr_id = 46714641
    and r1.ref_nm = 'programType'
    and r2.ref_nm = 'memberPrograStatusType'
'
</code>```

答:
The reason is because when you place a filter from a column in the left join in the where clause, you are turning it into an inner join. </p>

<p>However if you place the filter on the join clause then the filter applies only to the rows that have data in left join table. </p>

Title: Left join, where clause

Body:
I'm wondering why this returns no values but if I place the "and r2.ref_nm = 'memberPrograStatusType" in the join clause it returns values. The 'memberPrograStatusType is null.

`select mp.mbr_id
,r1.ref_desc as program_name
,r2.ref_desc as program_status
,mp.nom_dt
,mp.enrl_dt
,mp.end_dt
from icue.mbr_pgm mp
  left join icue.ref r1 on mp.pgm_typ_id = r1.ref_cd
  left join icue.ref r2 on mp.mbr_pgm_sts_typ_id = r2.ref_cd
where '15-JAN-17' between mp.enrl_dt and nvl(mp.end_dt,sysdate)
    and mp.mbr_id = 46714641
    and r1.ref_nm = 'programType'
    and r2.ref_nm = 'memberPrograStatusType'
'

Body:
The reason is because when you place a filter from a column in the left join in the where clause, you are turning it into an inner join.

However if you place the filter on the join clause then the filter applies only to the rows that have data in left join table.


问:
Why verilog simulators model net delay as inertial delay rather than transport delay?
I'm connecting a DDR model in the test bench using wires with net delay to model the trace delay on the board. The trace can hold 1 or 2 bits in its transmission line, but because the simulators models the net delay as inertial delay, all the bits get filtered out as glitches. I don't even get the clock this way. The SystemVerilog spec is not explicit on this subject. So, I'm guessing that the simulators don't want to incur the cost on performance and storage to model it as transport delay. However, I strongly believe transport delay is the right way to use for net delay, because otherwise the hassle of modeling each bidir signal with its own delay is huge. What do you think?

Here's my test case.

```<code>`timescale 1ps/1ps

module sim_top  ();

parameter realtime NET_DELAY = 80ps;
parameter realtime PULSE_DELAY = 50ps;

logic driver;
initial begin
  driver = 0;
  forever #PULSE_DELAY driver = !driver;
end

wire #NET_DELAY a;
assign a = driver;
always @(posedge a or negedge a) begin
  $display("a=%b @ %t", a, $time);
end

logic b;
always @(*) begin
  b <= #NET_DELAY driver;
end

always @(posedge b or negedge b) begin
  $display("b=%b @ %t", b, $time);
end

initial begin
 #1ns;
 $finish;
end
endmodule
</code>```

答:
So, I'm guessing that the simulators don't want to incur the cost on performance and storage to model it as transport delay.

I can imagine how you got that reasoning. From what I have learned, your assumptions is incorrect.

Real logic gates have inertial delay. This delay is caused by RC (resistance & capacitance) that is inherit to the device, from routing, or intentionally added. Verilog uses inertial delay to emulate delay behavior of real logic.

I cannot find a citation, but from discussions with engineers with pre-Verilog experience, early Verilog only modeled gates (think Verilog primitives and,or,nand,bufif0, etc.). Assign statements and always blocks were added some time later along with the possibility of synthesis. Non-blocking (<=) assignments were added much later (and copied from VHDL from what I've heard), but sill before Verilog by IEEE.

Assign statement handle delay the same way as gates. See IEEE1800-2012 § 10.3.3 Continuous assignment delays

A delay given to a continuous assignment shall specify the time duration between a right-hand operand value change and the assignment made to the left-hand side. If the left-hand references a scalar net, then the delay shall be treated in the same way as for gate delays; that is, different delays can be given for the output rising, falling, and changing to high impedance (see 28.16).

I'm guessing assign statements use the same type of delay as gates to reuse existing code (inside the simulator, not Verilog code) for managing delay and maintains continuity for the definition of delay. It also mapping easier, ex: assign #1 out = in; is the same as buf #1 (out,in);.

With real circuits, when you want a delay of 10 with a filter of 0.5, you need chain of 20 delay cells with small RC. If you want a delay and filter of 10 you use one delay cell with large RC. In theory synthesizers could use this delay information for target delay and filtration control (I cannot think of any synthesizer that actually does this; all synthesizers I know of ignore RTL delays).

Generally non-blocking (<=) assignments are used for synchronous logic (edge-sensitive flops and level-sensitive latches). Transport delay is the main exception but should only be used for behavioral modeling that will not be synthesized. If you know the amount of filtering your real delay path will have, I suggest coding it as follows:

```<code>reg out;
wire #(FILTER) in_filtered = in;
always @* out <= #(TOTAL_DELAY-FILTER) in_filter; // must be >=0.0
</code>```

Which is cleaner and less CPU intensive then the pure inertial delay approach:

```<code>localparam LENGTH = TOTAL_DELAY/FILTER; // must be an integer >=2
wire out;
wire [LENGTH-2 : 0] delay_chain;
assign #(FILTER) {out,delay_chain} = {delay_chain,in};
</code>```

Body:
I'm connecting a DDR model in the test bench using wires with net delay to model the trace delay on the board. The trace can hold 1 or 2 bits in its transmission line, but because the simulators models the net delay as inertial delay, all the bits get filtered out as glitches. I don't even get the clock this way. The SystemVerilog spec is not explicit on this subject. So, I'm guessing that the simulators don't want to incur the cost on performance and storage to model it as transport delay. However, I strongly believe transport delay is the right way to use for net delay, because otherwise the hassle of modeling each bidir signal with its own delay is huge. What do you think?

Here's my test case.

`timescale 1ps/1ps

module sim_top  ();

parameter realtime NET_DELAY = 80ps;
parameter realtime PULSE_DELAY = 50ps;

logic driver;
initial begin
  driver = 0;
  forever #PULSE_DELAY driver = !driver;
end

wire #NET_DELAY a;
assign a = driver;
always @(posedge a or negedge a) begin
  $display("a=%b @ %t", a, $time);
end

logic b;
always @(*) begin
  b <= #NET_DELAY driver;
end

always @(posedge b or negedge b) begin
  $display("b=%b @ %t", b, $time);
end

initial begin
 #1ns;
 $finish;
end
endmodule

Body:
So, I'm guessing that the simulators don't want to incur the cost on performance and storage to model it as transport delay.

I can imagine how you got that reasoning. From what I have learned, your assumptions is incorrect.

Real logic gates have inertial delay. This delay is caused by RC (resistance & capacitance) that is inherit to the device, from routing, or intentionally added. Verilog uses inertial delay to emulate delay behavior of real logic.

I cannot find a citation, but from discussions with engineers with pre-Verilog experience, early Verilog only modeled gates (think Verilog primitives and,or,nand,bufif0, etc.). Assign statements and always blocks were added some time later along with the possibility of synthesis. Non-blocking (<=) assignments were added much later (and copied from VHDL from what I've heard), but sill before Verilog by IEEE.

Assign statement handle delay the same way as gates. See IEEE1800-2012 § 10.3.3 Continuous assignment delays

A delay given to a continuous assignment shall specify the time duration between a right-hand operand value change and the assignment made to the left-hand side. If the left-hand references a scalar net, then the delay shall be treated in the same way as for gate delays; that is, different delays can be given for the output rising, falling, and changing to high impedance (see 28.16).

I'm guessing assign statements use the same type of delay as gates to reuse existing code (inside the simulator, not Verilog code) for managing delay and maintains continuity for the definition of delay. It also mapping easier, ex: assign #1 out = in; is the same as buf #1 (out,in);.

With real circuits, when you want a delay of 10 with a filter of 0.5, you need chain of 20 delay cells with small RC. If you want a delay and filter of 10 you use one delay cell with large RC. In theory synthesizers could use this delay information for target delay and filtration control (I cannot think of any synthesizer that actually does this; all synthesizers I know of ignore RTL delays).

Generally non-blocking (<=) assignments are used for synchronous logic (edge-sensitive flops and level-sensitive latches). Transport delay is the main exception but should only be used for behavioral modeling that will not be synthesized. If you know the amount of filtering your real delay path will have, I suggest coding it as follows:

reg out;
wire #(FILTER) in_filtered = in;
always @* out <= #(TOTAL_DELAY-FILTER) in_filter; // must be >=0.0

Which is cleaner and less CPU intensive then the pure inertial delay approach:

localparam LENGTH = TOTAL_DELAY/FILTER; // must be an integer >=2
wire out;
wire [LENGTH-2 : 0] delay_chain;
assign #(FILTER) {out,delay_chain} = {delay_chain,in};


问:
How to post UTF-8 text from MySQL to Twitter successfully
I have some text in UTF-8. I put it into a MySQL database, collation utf8_general_ci and then I've been auto-posting it to Twitter via Net::Twitter.

But when I post it, even though Twitter itself seems to be expecting UTF-8, going by the content-type in their input pages, I'm getting those artefacts you get when UTF-8 text is misinterpreted: é comes out as Ã© for instance.

So ... at what point is this going wrong? How can I ensure it makes the trip undamaged?

Set my script to treat all text as UTF-8 somehow?

Make sure I extract it from the database in UTF-8?

Tell Net::Twitter that it's posting in UTF-8?

答:
My guess would be the encoding of the database connection, which often is iso-8859-1 by default. That would explain the Ã© - it's a two-byte UTF-8 character displayed in single-byte iso-8859-1.

Does sending a query with SET NAMES utf8; after connecting help? (Or whatever specific command Perl's mySQL client library might have for setting the connection character set.)


问:
Will these object keys always be in same order?
I am making multiple objects, then I am JSON.stringifying them.  Then I am turning them into a hash.  I need all of the properties to be stringified in the same order so my hashes are consistent.  For example:

```<code>function createObj(index, value, key) {
    var obj = {
        value: value,
        index: index,
        key: key
    };

    return obj;
 };

console.log(JSON.stringify(createObj(1, 'blue', 'ABC')));   // =>  {"value":"blue","index":1,"key":"ABC"}
console.log(JSON.stringify(createObj(2, 'red', 'DEF')));    // =>  {"value":"red","index":2,"key":"DEF"}
console.log(JSON.stringify(createObj(3, 'green', 'GHI')));  // =>  {"value":"green","index":3,"key":"GHI"}
</code>```

Can I always expect the keys to be stringified in the order that I have placed them on the object in my createObj function?  I do not add any more properties to the objects after they are created.

If I cannot guarantee this order, can you recommend a way to guarantee the order of the keys for this purpose?

EDIT: I realize that when iterating an object the order of the keys is not guaranteed (for-in and Object.keys) but would the order be guaranteed for stringifying it?

答: The JSON.stringify() documentation at MDN and the ECMAScript Language Specification do not indicate the order in which keys are stringified. While that order my very well be sequential for primitive types like string, number, and boolean, you can't really be sure for objects, functions, arrays, etc. Your best bet would likely be to implement your own version of stringify in order to be 100% certain of the output.

Body:
I am making multiple objects, then I am JSON.stringifying them.  Then I am turning them into a hash.  I need all of the properties to be stringified in the same order so my hashes are consistent.  For example:

function createObj(index, value, key) {
    var obj = {
        value: value,
        index: index,
        key: key
    };

    return obj;
 };

console.log(JSON.stringify(createObj(1, 'blue', 'ABC')));   // =>  {"value":"blue","index":1,"key":"ABC"}
console.log(JSON.stringify(createObj(2, 'red', 'DEF')));    // =>  {"value":"red","index":2,"key":"DEF"}
console.log(JSON.stringify(createObj(3, 'green', 'GHI')));  // =>  {"value":"green","index":3,"key":"GHI"}

Can I always expect the keys to be stringified in the order that I have placed them on the object in my createObj function?  I do not add any more properties to the objects after they are created.

If I cannot guarantee this order, can you recommend a way to guarantee the order of the keys for this purpose?

EDIT: I realize that when iterating an object the order of the keys is not guaranteed (for-in and Object.keys) but would the order be guaranteed for stringifying it?


问:
R data table select entry with largest sum
I have a data table with 3 columns: Field1, Field2 and Value.
For each attribute in Field2, I want to find the attribute in Field1 that corresponds to the largest sum of Value (ie there are multiple Field1 / Field2 rows in the data table).

When I try this: x[,.(Field1 = Field1[which.max(sum(Value))]),.(Field2)] I seem to be getting the first Field1 row for each Field2 rather than the row corresponding to the max sum of Value.

As an extension, what if you wanted to provide both the sum of value, the total number of rows and the Field1 value corresponding to the largest sum across the Value field within Field2?

Below is a reproducible code.

```<code>library(data.table)

#Set random seed
set.seed(2017)

#Create a table with the attributes we need
x = data.table(rbind(data.frame(Field1 = 1:12,Field2 = rep(1:3, each = 4), Value = runif(12)),
               data.frame(Field1 = 1:12,Field2 = rep(1:3, each = 4), Value = runif(12))))

#Let's order by Field2/ Field1 / Value
x = x[order(Field2,Field1,Value)]

#Check
print(x)

# This works, but requires 2 steps which can complicate things when needing
# to pull other attributes too.
(x[,.(Value = sum(Value)),.(Field2,Field1)][,.SD[which.max(Value)],.(Field2)])

#This instead provides the row corresponding to the largest Value.
(x[,.(Field1 = Field1[which.max(Value)]),.(Field2)])

# This is what I was ideally looking for but it only returns the first row of the attribute
# regardless of the value of Value, or the corresponding sum.
(x[,.(Field1 = Field1[which.max(sum(Value))]),.(Field2)])

# This works but seems clumsy

(x[,
.SD[, .(RKCNT=length(.I),TotalValue=sum(Value)), .(Field1)]
[,.(RKCNT = sum(RKCNT), TotalValue = sum(TotalValue),
Field1 = Field1[which.max(TotalValue)])],
.(Field2)])
</code>```

答:
We can use

```<code>x[, .SD[, sum(Value), Field1][which.max(V1)], Field2]
</code>```

Which is concise and thus somewhat easier to read. But does not give any performance improvement.

Body:
I have a data table with 3 columns: Field1, Field2 and Value.
For each attribute in Field2, I want to find the attribute in Field1 that corresponds to the largest sum of Value (ie there are multiple Field1 / Field2 rows in the data table).

When I try this: x[,.(Field1 = Field1[which.max(sum(Value))]),.(Field2)] I seem to be getting the first Field1 row for each Field2 rather than the row corresponding to the max sum of Value.

As an extension, what if you wanted to provide both the sum of value, the total number of rows and the Field1 value corresponding to the largest sum across the Value field within Field2?

Below is a reproducible code.

library(data.table)

#Set random seed
set.seed(2017)

#Create a table with the attributes we need
x = data.table(rbind(data.frame(Field1 = 1:12,Field2 = rep(1:3, each = 4), Value = runif(12)),
               data.frame(Field1 = 1:12,Field2 = rep(1:3, each = 4), Value = runif(12))))

#Let's order by Field2/ Field1 / Value
x = x[order(Field2,Field1,Value)]

#Check
print(x)

# This works, but requires 2 steps which can complicate things when needing
# to pull other attributes too.
(x[,.(Value = sum(Value)),.(Field2,Field1)][,.SD[which.max(Value)],.(Field2)])

#This instead provides the row corresponding to the largest Value.
(x[,.(Field1 = Field1[which.max(Value)]),.(Field2)])

# This is what I was ideally looking for but it only returns the first row of the attribute
# regardless of the value of Value, or the corresponding sum.
(x[,.(Field1 = Field1[which.max(sum(Value))]),.(Field2)])

# This works but seems clumsy

(x[,
.SD[, .(RKCNT=length(.I),TotalValue=sum(Value)), .(Field1)]
[,.(RKCNT = sum(RKCNT), TotalValue = sum(TotalValue),
Field1 = Field1[which.max(TotalValue)])],
.(Field2)])

Body:
We can use

x[, .SD[, sum(Value), Field1][which.max(V1)], Field2]

Which is concise and thus somewhat easier to read. But does not give any performance improvement.


问:
padrino g: cannot load such file -- sequel/plugins/schema
new to Ruby, decided to start with Padrino framework

was following http://padrinorb.com/guides/getting-started/blog-tutorial/

I created my project using padrino g project blog-tutorial -e erb -c scss -s jquery -d sequel -a mysql2 -b, then I tried to make a model padrino g model post title:string body:text created_at:datetime

but instead I get an error:

```<code>/home/user/.rvm/gems/ruby-2.4.1/gems/sequel-5.1.0/lib/sequel/model/base.rb:914:in `require': cannot load such file -- sequel/plugins/schema (LoadError)
        from /home/user/.rvm/gems/ruby-2.4.1/gems/sequel-5.1.0/lib/sequel/model/base.rb:914:in `plugin_module'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/sequel-5.1.0/lib/sequel/model/base.rb:533:in `plugin'
        from /home/user/Sites/blog-tutorial/config/database.rb:1:in `<top (required)>'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-core-0.14.1.1/lib/padrino-core/reloader.rb:91:in `require'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-core-0.14.1.1/lib/padrino-core/reloader.rb:91:in `safe_load'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-core-0.14.1.1/lib/padrino-core/loader.rb:154:in `block in require_dependencies'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-core-0.14.1.1/lib/padrino-core/loader.rb:152:in `each'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-core-0.14.1.1/lib/padrino-core/loader.rb:152:in `require_dependencies'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-core-0.14.1.1/lib/padrino-core/loader.rb:57:in `load!'
        from /home/user/Sites/blog-tutorial/config/boot.rb:60:in `<top (required)>'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-gen-0.14.1.1/lib/padrino-gen/generators/cli.rb:26:in `require'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-gen-0.14.1.1/lib/padrino-gen/generators/cli.rb:26:in `load_boot'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/thor-0.20.0/lib/thor/command.rb:27:in `run'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/thor-0.20.0/lib/thor/invocation.rb:126:in `invoke_command'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/thor-0.20.0/lib/thor/invocation.rb:133:in `block in invoke_all'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/thor-0.20.0/lib/thor/invocation.rb:133:in `each'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/thor-0.20.0/lib/thor/invocation.rb:133:in `map'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/thor-0.20.0/lib/thor/invocation.rb:133:in `invoke_all'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/thor-0.20.0/lib/thor/group.rb:232:in `dispatch'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/thor-0.20.0/lib/thor/base.rb:466:in `start'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-gen-0.14.1.1/bin/padrino-gen:16:in `<main>'
</code>```

can't find a solution for this (mysql-devel is installed, mysql2 gem too)

config/database.rb has valid credentials for db connection, e.g. mysql2://root:1@localhost/my_db. Also tried to pass user/password in parameters

答:
The Sequel gem can't find the schema plugin, but the blog tutorial project doesn't seem to need it. Open up the blog-tutorial/config/database.rb file, and comment out the first line:

```<code>#Sequel::Model.plugin(:schema)
Sequel::Model.raise_on_save_failure = false # Do not throw exceptions on failure
Sequel::Model.db = case Padrino.env
  when :development then Sequel.connect("sqlite://db/blog_tutorial_development.db", :loggers => [logger])
  when :production  then Sequel.connect("sqlite://db/blog_tutorial_production.db",  :loggers => [logger])
  when :test        then Sequel.connect("sqlite://db/blog_tutorial_test.db",        :loggers => [logger])
end
</code>```

I tested the whole project like this, except the RSS feed part at the end, and everything worked for me.

Body:
new to Ruby, decided to start with Padrino framework

was following http://padrinorb.com/guides/getting-started/blog-tutorial/

I created my project using padrino g project blog-tutorial -e erb -c scss -s jquery -d sequel -a mysql2 -b, then I tried to make a model padrino g model post title:string body:text created_at:datetime

but instead I get an error:

/home/user/.rvm/gems/ruby-2.4.1/gems/sequel-5.1.0/lib/sequel/model/base.rb:914:in `require': cannot load such file -- sequel/plugins/schema (LoadError)
        from /home/user/.rvm/gems/ruby-2.4.1/gems/sequel-5.1.0/lib/sequel/model/base.rb:914:in `plugin_module'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/sequel-5.1.0/lib/sequel/model/base.rb:533:in `plugin'
        from /home/user/Sites/blog-tutorial/config/database.rb:1:in `<top (required)>'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-core-0.14.1.1/lib/padrino-core/reloader.rb:91:in `require'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-core-0.14.1.1/lib/padrino-core/reloader.rb:91:in `safe_load'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-core-0.14.1.1/lib/padrino-core/loader.rb:154:in `block in require_dependencies'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-core-0.14.1.1/lib/padrino-core/loader.rb:152:in `each'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-core-0.14.1.1/lib/padrino-core/loader.rb:152:in `require_dependencies'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-core-0.14.1.1/lib/padrino-core/loader.rb:57:in `load!'
        from /home/user/Sites/blog-tutorial/config/boot.rb:60:in `<top (required)>'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-gen-0.14.1.1/lib/padrino-gen/generators/cli.rb:26:in `require'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-gen-0.14.1.1/lib/padrino-gen/generators/cli.rb:26:in `load_boot'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/thor-0.20.0/lib/thor/command.rb:27:in `run'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/thor-0.20.0/lib/thor/invocation.rb:126:in `invoke_command'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/thor-0.20.0/lib/thor/invocation.rb:133:in `block in invoke_all'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/thor-0.20.0/lib/thor/invocation.rb:133:in `each'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/thor-0.20.0/lib/thor/invocation.rb:133:in `map'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/thor-0.20.0/lib/thor/invocation.rb:133:in `invoke_all'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/thor-0.20.0/lib/thor/group.rb:232:in `dispatch'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/thor-0.20.0/lib/thor/base.rb:466:in `start'
        from /home/user/.rvm/gems/ruby-2.4.1/gems/padrino-gen-0.14.1.1/bin/padrino-gen:16:in `'

can't find a solution for this (mysql-devel is installed, mysql2 gem too)

config/database.rb has valid credentials for db connection, e.g. mysql2://root:1@localhost/my_db. Also tried to pass user/password in parameters

Body:
The Sequel gem can't find the schema plugin, but the blog tutorial project doesn't seem to need it. Open up the blog-tutorial/config/database.rb file, and comment out the first line:

#Sequel::Model.plugin(:schema)
Sequel::Model.raise_on_save_failure = false # Do not throw exceptions on failure
Sequel::Model.db = case Padrino.env
  when :development then Sequel.connect("sqlite://db/blog_tutorial_development.db", :loggers => [logger])
  when :production  then Sequel.connect("sqlite://db/blog_tutorial_production.db",  :loggers => [logger])
  when :test        then Sequel.connect("sqlite://db/blog_tutorial_test.db",        :loggers => [logger])
end

I tested the whole project like this, except the RSS feed part at the end, and everything worked for me.


问:
Unseting a list of dynamic variables in Bash
How can I achieve the following with Bash:

```<code>x="search='something something' replace='something' subject=/path/path"

eval "$x"

echo $search
# prints something
# etc.

# (I am trying to do something here)
# So the following wouldn't print **something** anymore

echo $search
</code>```

I basically want to unset the variables that were set using eval initially.

答:
You can fork a subshell, do eval in the subshell and once you're done, exit the subshell:

```<code># do this in a subshell
(
x="search='something' replace='something' subject=/path"
eval "$x"
echo "search=$search"
)

# now out of subshell
echo "search=$search"
</code>```

Body:
How can I achieve the following with Bash:

x="search='something something' replace='something' subject=/path/path"

eval "$x"

echo $search
# prints something
# etc.

# (I am trying to do something here)
# So the following wouldn't print **something** anymore

echo $search

I basically want to unset the variables that were set using eval initially.

Body:
You can fork a subshell, do eval in the subshell and once you're done, exit the subshell:

# do this in a subshell
(
x="search='something' replace='something' subject=/path"
eval "$x"
echo "search=$search"
)

# now out of subshell
echo "search=$search"


问:
MySQL - the cheapest order
I have 2 MySQL tables:

```<code>Persons:
person_id
person_name

Orders:
person_id
cost
order_name
</code>```

I need to make a ONE sql-query to get person name and it's cheapest order.
Want to write some like this: SELECT person_name, order=(SELECT order_name FROM orders WHERE order.person_id = person.person_id ORDER BY order.cost ASC LIMIT 1) FROM person
But it don't work.

答:
remove order= and add AS order_name

Something like this:

```<code>SELECT p.person_name
     , ( SELECT o.order_name
           FROM orders o
          WHERE o.person_id = p.person_id
          ORDER BY o.cost ASC
          LIMIT 1
       ) AS order_name
  FROM person p
 ORDER BY p.person_name
</code>```

Title: MySQL - the cheapest order

Body:
I have 2 MySQL tables:

Persons:
person_id
person_name

Orders:
person_id
cost
order_name

I need to make a ONE sql-query to get person name and it's cheapest order.
Want to write some like this: SELECT person_name, order=(SELECT order_name FROM orders WHERE order.person_id = person.person_id ORDER BY order.cost ASC LIMIT 1) FROM person
But it don't work.

Body:
remove order= and add AS order_name

Something like this:

SELECT p.person_name
     , ( SELECT o.order_name
           FROM orders o
          WHERE o.person_id = p.person_id
          ORDER BY o.cost ASC
          LIMIT 1
       ) AS order_name
  FROM person p
 ORDER BY p.person_name


问:
Designing programs to compile on both 32bit and 64bit in D
I have an open source project that I want to run/compile on both 32 bit and 64 bit architectures. But here comes the problem: it uses dynamic arrays a lot, and needs to mess with their length too. Dynamic arrays have length stored in type size_t, which is ulong on 64bit, and uint on 32 bit systems.

I have code that looks something like this:

```<code>int i = 0;//this HAS to be int, not uint for some reasons
i = dynArray.length;//error, can't implicitly cast ulong to uint
</code>```

I need i to int (on 32bit) and long on (64bit). size_t would have solved the problem, but it is unsigned (either uint or ulong).

So my question here is that: how do I create a integer data type that is int on 32 bit and long on 64 bit? Will it be something like this?:

```<code>32bit{
   //Declaration for 32 bit version
}else{
   //Declaration for 64 bit version
}
</code>```

答:
Try this:</p>

```<code>version (X86)
{
   // Declaration for 32 bit version
   alias myint = int;
}
else
{
   // Declaration for 64 bit version
   alias myint = long;
}
</code>```

Body:
I have an open source project that I want to run/compile on both 32 bit and 64 bit architectures. But here comes the problem: it uses dynamic arrays a lot, and needs to mess with their length too. Dynamic arrays have length stored in type size_t, which is ulong on 64bit, and uint on 32 bit systems.

I have code that looks something like this:

int i = 0;//this HAS to be int, not uint for some reasons
i = dynArray.length;//error, can't implicitly cast ulong to uint

I need i to int (on 32bit) and long on (64bit). size_t would have solved the problem, but it is unsigned (either uint or ulong).

So my question here is that: how do I create a integer data type that is int on 32 bit and long on 64 bit? Will it be something like this?:

32bit{
   //Declaration for 32 bit version
}else{
   //Declaration for 64 bit version
}

Body:
Try this:

version (X86)
{
   // Declaration for 32 bit version
   alias myint = int;
}
else
{
   // Declaration for 64 bit version
   alias myint = long;
}