问:
Webpack 2 refusing to ignore lovell/sharp in node_modules folder
I am trying to create an app in Electron which uses React, Webpack 2 Sharp and Electron.

I just added Sharp (https://github.com/lovell/sharp) and Webpack is adamantly trying to build Sharp but I don't think it should be (I could be wrong and if so, how would I get these files to load)?

I get the following stdout:

```<code>WARNING in ./~/sharp/lib/constructor.js
Module not found: Error: Can't resolve '../vendor/lib/versions.json' in '/Users/andy/Development/image-browser/node_modules/sharp/lib'
@ ./~/sharp/lib/constructor.js 23:15-53
@ ./~/sharp/lib/index.js
@ ./app/src/utils/getImage.js
@ ./app/src/components/Images/image.js
@ ./app/src/components/Images/index.js
@ ./app/src/App.js
@ ./app/src/entry.js

WARNING in ./~/sharp/lib/icc/sRGB.icc
Module parse failed: /Users/andy/Development/image-browser/node_modules/sharp/lib/icc/sRGB.icc Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
@ ./~/sharp/lib ^\.\/.*$
@ ./~/sharp/lib/index.js
@ ./app/src/utils/getImage.js
@ ./app/src/components/Images/image.js
@ ./app/src/components/Images/index.js
@ ./app/src/App.js
@ ./app/src/entry.js

WARNING in ./~/sharp/lib/icc/cmyk.icm
Module parse failed: /Users/andy/Development/image-browser/node_modules/sharp/lib/icc/cmyk.icm Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
@ ./~/sharp/lib ^\.\/.*$
@ ./~/sharp/lib/index.js
@ ./app/src/utils/getImage.js
@ ./app/src/components/Images/image.js
@ ./app/src/components/Images/index.js
@ ./app/src/App.js
@ ./app/src/entry.js

ERROR in ./~/sharp/build/Release/sharp.node
Module parse failed: /Users/andy/Development/image-browser/node_modules/sharp/build/Release/sharp.node Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
@ ./~/sharp/lib/constructor.js 8:14-52
@ ./~/sharp/lib/index.js
@ ./app/src/utils/getImage.js
@ ./app/src/components/Images/image.js
@ ./app/src/components/Images/index.js
@ ./app/src/App.js
@ ./app/src/entry.js
</code>```

webpack.config.js

```<code>const ExtractTextPlugin = require('extract-text-webpack-plugin')

module.exports = {

    watch: true,

    target: 'electron',

    entry: './app/src/entry.js',

    devtool: 'source-map',

    output: {
        path: __dirname + '/app/build',
        publicPath: 'build/',
        filename: 'bundle.js'
    },

    module: {
        rules: [
            {
                test: /\.js$/,
                include: /\/app\/src/,
                // exclude: /(node_modules)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            'env',
                            'react'
                        ]
                    }
                }
            },
            // {
            //     test: /\.node$/,
            //     use: {
            //         loader: 'node-loader'
            //     }
            // },
            {
                test: /\.(sass|scss)$/,
                include: /\/app\/src/,
                // exclude: /(node_modules)/,
                use: [
                    'style-loader',
                    'css-loader',
                    'sass-loader',
                ]
            },
            {
                test: /\.(png|jpg|gif|svg)$/,
                include: /\/app\/src/,
                // exclude: /(node_modules)/,
                use: {
                    loader: 'file-loader',
                    query: {
                        name: '[name].[ext]?[hash]'
                    }
                }
            }
        ]
    },

    plugins: [
        new ExtractTextPlugin({
            filename: 'bundle.css',
            disable: false,
            allChunks: true
        })
    ]
}
</code>```

My babel config (extracted from package.json):

```<code>"babel": {
    "retainLines": true,
    "presets": [
        [
            "env",
            {
            "targets": {
                "electron": 1.6,
                "node": 7.9
            },
                "modules": false,
                "debug": true
            }
        ],
        "es2015",
        "es2016",
        "es2017"
    ]
},
</code>```

Any ideas?

答:
I had the same issue and got some luck with node-loader installed and set the following in the package.json

```<code>{
  test: /\.node$/,
  use: 'node-loader'
},
</code>```

I solved the ERROR in ./~/sharp/build/Release/sharp.node. But I'm not sure if not solving the other three warnings will cause any issues yet.
But at least now my Electron application can be started now.

Body:
I am trying to create an app in Electron which uses React, Webpack 2 Sharp and Electron.

I just added Sharp (https://github.com/lovell/sharp) and Webpack is adamantly trying to build Sharp but I don't think it should be (I could be wrong and if so, how would I get these files to load)?

I get the following stdout:

WARNING in ./~/sharp/lib/constructor.js
Module not found: Error: Can't resolve '../vendor/lib/versions.json' in '/Users/andy/Development/image-browser/node_modules/sharp/lib'
@ ./~/sharp/lib/constructor.js 23:15-53
@ ./~/sharp/lib/index.js
@ ./app/src/utils/getImage.js
@ ./app/src/components/Images/image.js
@ ./app/src/components/Images/index.js
@ ./app/src/App.js
@ ./app/src/entry.js

WARNING in ./~/sharp/lib/icc/sRGB.icc
Module parse failed: /Users/andy/Development/image-browser/node_modules/sharp/lib/icc/sRGB.icc Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
@ ./~/sharp/lib ^\.\/.*$
@ ./~/sharp/lib/index.js
@ ./app/src/utils/getImage.js
@ ./app/src/components/Images/image.js
@ ./app/src/components/Images/index.js
@ ./app/src/App.js
@ ./app/src/entry.js

WARNING in ./~/sharp/lib/icc/cmyk.icm
Module parse failed: /Users/andy/Development/image-browser/node_modules/sharp/lib/icc/cmyk.icm Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
@ ./~/sharp/lib ^\.\/.*$
@ ./~/sharp/lib/index.js
@ ./app/src/utils/getImage.js
@ ./app/src/components/Images/image.js
@ ./app/src/components/Images/index.js
@ ./app/src/App.js
@ ./app/src/entry.js

ERROR in ./~/sharp/build/Release/sharp.node
Module parse failed: /Users/andy/Development/image-browser/node_modules/sharp/build/Release/sharp.node Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
@ ./~/sharp/lib/constructor.js 8:14-52
@ ./~/sharp/lib/index.js
@ ./app/src/utils/getImage.js
@ ./app/src/components/Images/image.js
@ ./app/src/components/Images/index.js
@ ./app/src/App.js
@ ./app/src/entry.js

webpack.config.js

const ExtractTextPlugin = require('extract-text-webpack-plugin')

module.exports = {

    watch: true,

    target: 'electron',

    entry: './app/src/entry.js',

    devtool: 'source-map',

    output: {
        path: __dirname + '/app/build',
        publicPath: 'build/',
        filename: 'bundle.js'
    },

    module: {
        rules: [
            {
                test: /\.js$/,
                include: /\/app\/src/,
                // exclude: /(node_modules)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            'env',
                            'react'
                        ]
                    }
                }
            },
            // {
            //     test: /\.node$/,
            //     use: {
            //         loader: 'node-loader'
            //     }
            // },
            {
                test: /\.(sass|scss)$/,
                include: /\/app\/src/,
                // exclude: /(node_modules)/,
                use: [
                    'style-loader',
                    'css-loader',
                    'sass-loader',
                ]
            },
            {
                test: /\.(png|jpg|gif|svg)$/,
                include: /\/app\/src/,
                // exclude: /(node_modules)/,
                use: {
                    loader: 'file-loader',
                    query: {
                        name: '[name].[ext]?[hash]'
                    }
                }
            }
        ]
    },

    plugins: [
        new ExtractTextPlugin({
            filename: 'bundle.css',
            disable: false,
            allChunks: true
        })
    ]
}

My babel config (extracted from package.json):

"babel": {
    "retainLines": true,
    "presets": [
        [
            "env",
            {
            "targets": {
                "electron": 1.6,
                "node": 7.9
            },
                "modules": false,
                "debug": true
            }
        ],
        "es2015",
        "es2016",
        "es2017"
    ]
},

Any ideas?

Body:
I had the same issue and got some luck with node-loader installed and set the following in the package.json

{
  test: /\.node$/,
  use: 'node-loader'
},

I solved the ERROR in ./~/sharp/build/Release/sharp.node. But I'm not sure if not solving the other three warnings will cause any issues yet.
But at least now my Electron application can be started now.


来源: stackexchange

问:
Phantom Contact Account Appearing - Android
I am writing an app that allows the user to select from a list of names and then add one of the names (with phone number, etc) to their contacts. When I retrieve my phone's list of Contact Accounts, I am getting 3 results: "Phone", "a000000229aa3e....", "Gmail".

The center result, "a000000229aa3e...." is not an account that I have setup or appears anywhere else on my phone. This also does not appear in the emulator.

My coworker ran it on hit Droid (original Droid) and did not get the odd account. I am running it on a Droid X.

Does anyone know where this Contact Group is coming from? Is there something I need to do to filter this out?

I was able to get the name and type for the odd contact account:
Account Name: a00000229aa3e5-8877431712057062230@random.svcmot.com
Account Type: com.motorola.blur.service.bsutils.MOTHER_USER_CREDS_TYPE

答:
I don't know all that much about Android apps, but is your phone made by Motorola? or was your previous phone made by Motorola and you copied settings across?

If so it could be a default account, can you see this account when not using your application?

ContentLicense: CC BY-SA 2.5


问:
Getting Modal to onload when page opens
Can someone help me, Im trying to get a Modal to load when the page does but having some serious issues about it.</p>

```<code><script>
   $('#overlay').modal('show');

setTimeout(function() {
    $('#overlay').modal('hide');
}, 5000);
</script>

</head>

<body>

<div class="modal fade" id="overlay">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>Context here</p>
      </div>
    </div>
  </div>
</div>
</code>```

答:
You have to wrap your call in document ready, to assure it will be called once the page fully loads, like so:

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

          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal title

Context here

```

ContentLicense: CC BY-SA 3.0

Title: Getting Modal to onload when page opens

Body:
Can someone help me, Im trying to get a Modal to load when the page does but having some serious issues about it.

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal title

Context here

Body:
You have to wrap your call in document ready, to assure it will be called once the page fully loads, like so:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script>
  $(document).ready(function() {
    $('#overlay').modal('show');
    setTimeout(function() {
      $('#overlay').modal('hide');
    }, 5000);
  });
</script>

<body>
  <div class="modal fade" id="overlay">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
          <h4 class="modal-title">Modal title</h4>
        </div>
        <div class="modal-body">
          <p>Context here</p>
        </div>
      </div>
    </div>
  </div>
</body>


问:
Find Missing Records From Table A For Table B Where They Don't Exist in Table C
I have 3 tables:

```<code>Customer (CustomerID)
CustomerEvent (CustomerEventID, CustomerID, EventTypeID)
EventType (EventTypeID)
</code>```

Some Customer records have some CustomerEvent records with an EventType, some Customer records have no CustomerEvent records.

How do I identify/insert missing CustomerEvent records of each EventType for each Customer record?

My actual issue is a bit more detailed than that, however, this is the piece I'm struggling with.

Can I use one select statement to identify all missing CustomerEvent records? Or would I need to UNION on each EventType record?

答:
```<code>select * from

CUSTOMEREVENT CE

left join CUSTOMER C ON C.CustomerID = CE.CustomerID

left join EVENTTYPE ET ON CE.EventTypeID = ET.EventTypeID

where
C.CustomerID IS NULL
OR ET.EventTypeID IS NULL
</code>```

Body:
I have 3 tables:

Customer (CustomerID)
CustomerEvent (CustomerEventID, CustomerID, EventTypeID)
EventType (EventTypeID)

Some Customer records have some CustomerEvent records with an EventType, some Customer records have no CustomerEvent records.

How do I identify/insert missing CustomerEvent records of each EventType for each Customer record?

My actual issue is a bit more detailed than that, however, this is the piece I'm struggling with.

Can I use one select statement to identify all missing CustomerEvent records? Or would I need to UNION on each EventType record?


问:
How to register resource providers using Azure fluent resource management?
I'd like to fully automate my resource creation process. Unfortunately brand new subscriptions don't have a few resource providers registered by default. E.g. SQL.
That's easily solved as described here: https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-common-deployment-errors#noregisteredproviderfound

However this only outlines methods using either manually using the portal or using Powershell.

I'm looking for a solution using Microsoft.Azure.Management.ResourceManager.Fluent

It seems inconsistent that I wouldn't be able to do it using C#, but I can't seem to be able to find the functionality anywhere.

How to register resource providers for a new subscription using Azure fluent resource management?

答: Provider Auto registration feature is added in the upcoming release of Azure Management SDK (Fluent) v. 1.1. </p>


问:
how to write exact encryption code in java and node?
I need to translate the following code in Java:

```<code>public static String encode(String chave, final String value)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

    final Key keySpec = new SecretKeySpec(chave.getBytes(), "AES");

    final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

    System.out.println(Hex.encodeHex(new byte[16]));

    cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(new byte[16]));

    final byte[] message = cipher.doFinal(value.getBytes());

    return new String(Hex.encodeHex(message));
}
</code>```

to Node. I am trying:

```<code>var encrypt = function (key, data) {
    var iv = new Buffer('');

    decodeKey = new Buffer(key, "utf-8");
    var cipher = crypto.createCipher('aes-128-cbc', decodeKey, iv);

    cipher.setAutoPadding(true);
    //return cipher.update(data, 'utf8', 'hex') + '   ' + cipher.final('hex');

    var encrypted = Buffer.concat([
        cipher.update(data, "binary"),
        cipher.final()
    ]);

    return encrypted.toString('hex');

};
</code>```

But the result is not the same. It looks like there is an issue in the iv buffer but I can't figure it out.

答:
You have two issues. If you want to provide an IV, you need to call crypto.createCipheriv instead of crypto.createCipher. The latter takes a password instead of a key and derives the key and IV from that using OpenSSL's EVP_BytesToKey.

The other issue is that you should use an IV of correct length: var iv = Buffer.alloc(16);

Other issues could be the encodings that are all over the place:

value.getBytes() uses the default character encoding and my be different from machine to machine. Always define a specific character encoding like: value.getBytes("UTF-8")

cipher.update(data, "binary") assumes that data is Latin1 encoded which doesn't match with the Java code. Use cipher.update(data, "utf-8").

decodeKey = new Buffer(key, "utf-8"); looks bad, because keys should be randomly chosen. A binary representation of a key doesn't usually result in a valid UTF-8 encoding. Remember that keys are not passwords.

Security considerations:

The IV must be unpredictable (read: random). Don't use a static IV, because that makes the cipher deterministic and therefore not semantically secure. An attacker who observes ciphertexts can determine when the same message prefix was sent before. The IV is not secret, so you can send it along with the ciphertext. Usually, it is simply prepended to the ciphertext and sliced off before decryption.

Body:
I need to translate the following code in Java:

public static String encode(String chave, final String value)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

    final Key keySpec = new SecretKeySpec(chave.getBytes(), "AES");

    final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

    System.out.println(Hex.encodeHex(new byte[16]));

    cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(new byte[16]));

    final byte[] message = cipher.doFinal(value.getBytes());

    return new String(Hex.encodeHex(message));
}

to Node. I am trying:

var encrypt = function (key, data) {
    var iv = new Buffer('');

    decodeKey = new Buffer(key, "utf-8");
    var cipher = crypto.createCipher('aes-128-cbc', decodeKey, iv);

    cipher.setAutoPadding(true);
    //return cipher.update(data, 'utf8', 'hex') + '   ' + cipher.final('hex');

    var encrypted = Buffer.concat([
        cipher.update(data, "binary"),
        cipher.final()
    ]);

    return encrypted.toString('hex');

};

But the result is not the same. It looks like there is an issue in the iv buffer but I can't figure it out.


问:
Swift - How to add a layer on a UIImageView inside of a UICollectionViewCell and keep the parallax effect
I'm working on a tvOS project. This project contains a UICollectionView with a UIImageView inside of each UICollectionViewCell. First of all I'm using adjustsImageWhenAncestorFocused on the image, because it looks good when the cell is in focus and I want to have the 'parallax' effect.

When a cell is in focus there should pop up an label over the image(for the title of a product) which is not a problem to make. But I want the title to be good readable so thats why I want to put on a gradient layer on top of the image.

The problem:
When I add the gradient layer to the UIImageView, it goes on top of it but it doesn't 'stick' to it. It should go with the image when the user is doing the parallax thing, but it stays at its position and the original image does move underneath the gradient layer

Screenshot of the problem

The code

```<code>let gradientLayer = CAGradientLayer()

override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {

    gradientLayer.colors = [UIColor(red:0.00, green:1.00, blue:1.00, alpha:0.3).cgColor, UIColor(red:1.00, green:0, blue:1.00, alpha:0.3).cgColor]
    gradientLayer.frame = productImageView.focusedFrameGuide.layoutFrame
    gradientLayer.isHidden = true
    self.productImageView.layer.addSublayer(self.gradientLayer)

    if (self.isFocused){
        gradientLayer.isHidden = false
    }
    else {
        gradientLayer.isHidden = true
    }

}
</code>```

Additional question

Is this a bug? Because I still don't figured it out how to fix this problem. Should I give this to Apple?

答:
Apple introduced overlayContentView in tvOS 11. You should add your label to this view and it will do the focus for you!

For more information read https://developer.apple.com/documentation/uikit/uiimageview/2882128-overlaycontentview?changes=latest_minor

Body:
I'm working on a tvOS project. This project contains a UICollectionView with a UIImageView inside of each UICollectionViewCell. First of all I'm using adjustsImageWhenAncestorFocused on the image, because it looks good when the cell is in focus and I want to have the 'parallax' effect.

When a cell is in focus there should pop up an label over the image(for the title of a product) which is not a problem to make. But I want the title to be good readable so thats why I want to put on a gradient layer on top of the image.

The problem:
When I add the gradient layer to the UIImageView, it goes on top of it but it doesn't 'stick' to it. It should go with the image when the user is doing the parallax thing, but it stays at its position and the original image does move underneath the gradient layer

Screenshot of the problem

The code

let gradientLayer = CAGradientLayer()

override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {

    gradientLayer.colors = [UIColor(red:0.00, green:1.00, blue:1.00, alpha:0.3).cgColor, UIColor(red:1.00, green:0, blue:1.00, alpha:0.3).cgColor]
    gradientLayer.frame = productImageView.focusedFrameGuide.layoutFrame
    gradientLayer.isHidden = true
    self.productImageView.layer.addSublayer(self.gradientLayer)

    if (self.isFocused){
        gradientLayer.isHidden = false
    }
    else {
        gradientLayer.isHidden = true
    }

}

Additional question

Is this a bug? Because I still don't figured it out how to fix this problem. Should I give this to Apple?


问:
Binary Trees -- Tracing through code
Given the binary tree shown below, determine the order in which the nodes of the binary tree shown below are visited assuming the function A(root) is invoked.  Assume that the tree nodes and pointers are defined as shown.  Assume that root is a pointer to the node containing 60.
My answer to this problem is given below. Is it correct? What did I do wrong?

```<code>                                   60
                                 /    \
                                30     90
                               /  \   /
                              5   38  77
                               \  /  / \
                               8 32 62  88

struct treeNode{
  int data;
  struct treeNode *left, *right:
  {

struct treeNode *tree_ptr;

void A(struct treeNode *node_ptr){
    if (node_ptr != NULL){
    printf(“%d ,”,node_ptr->data);
    B(node_ptr->left);
    B(node_ptr->right);
   }
}

void B(struct treeNode *node_ptr){
    if (node_ptr != NULL) {
    A(node_ptr->left);
    printf(“%d ,”,node_ptr->data);
    A(node_ptr->right);
   }
 }
</code>```

Answer:
In void A it says to first print node_ptr-> data so 60 gets printed
Then the function calls B(node_ptr->left) then within B, A gets called (node_ptr->left) then you print that data which is 5. And then A(node_ptr->right) gets called go back up to A, print that data so 8 gets printed. Now Im not so sure what to do next but I get logically it would make sense to print 30 but Im not sure how the ptr gets from 8 to 30. And then if you continue in the same pattern 38 gets printed and 32 gets printed.
For the right subtree...
90 77 62 88

答:
A is a pre-order traversal, whereas B is an in-order traversal.

An easy way for you to figure out the order of printing is to look at how you visit the nodes themselves. I usually draw an outline around the outside of the tree (starting at the root and moving through the left or right based on the sub-tree you are traversing first). If I am doing a pre-order traversal, I print out a node whenever I move along its outside. If I am doing an in-order traversal, I print out a node only when I move under it (this makes sense when you look at in-order traversals, because you end up printing the leaves first; they are the first nodes you move under when you draw the outline). If I am doing a post-order traversal, I print out a node only when I move along its inside.

UPDATE

The reason 30 gets printed out after 5 and 8 is that you are not performing a purely pre-order traversal. You're jumping between a pre-order and an in-order traversal.

An easy way to figure out the order is to actually write down the steps your code goes through as you trace through it (I frequently use pen/pencil and paper to keep the information together). For example, you could do write out a call-stack like this:

```<code>A(60)
  printf(60)
  call B(60.left)
    B(30)
      call A(30.left)
        A(5)
          printf(5)
          call B(5.left)
            B(null)
          call B(5.right)
            B(8)
              call A(8.left)
                A(null)
              printf(8)
              call A(8.right)
                A(null)
      printf(30)
      call A(30.right)
        A(38)
        ...
</code>```

You can easily see the order in which the nodes are printed, and more importantly, why you "jump" from printing 8 to printing 30 (one recursive call has ended and you're falling back one level).

Title: Binary Trees -- Tracing through code

Body:
Given the binary tree shown below, determine the order in which the nodes of the binary tree shown below are visited assuming the function A(root) is invoked.  Assume that the tree nodes and pointers are defined as shown.  Assume that root is a pointer to the node containing 60.
My answer to this problem is given below. Is it correct? What did I do wrong?

                                   60
                                 /    \
                                30     90
                               /  \   /
                              5   38  77
                               \  /  / \
                               8 32 62  88

struct treeNode{
  int data;
  struct treeNode *left, *right:
  {

struct treeNode *tree_ptr;

void A(struct treeNode *node_ptr){
    if (node_ptr != NULL){
    printf(“%d ,”,node_ptr->data);
    B(node_ptr->left);
    B(node_ptr->right);
   }
}

void B(struct treeNode *node_ptr){
    if (node_ptr != NULL) {
    A(node_ptr->left);
    printf(“%d ,”,node_ptr->data);
    A(node_ptr->right);
   }
 }

Answer:
In void A it says to first print node_ptr-> data so 60 gets printed
Then the function calls B(node_ptr->left) then within B, A gets called (node_ptr->left) then you print that data which is 5. And then A(node_ptr->right) gets called go back up to A, print that data so 8 gets printed. Now Im not so sure what to do next but I get logically it would make sense to print 30 but Im not sure how the ptr gets from 8 to 30. And then if you continue in the same pattern 38 gets printed and 32 gets printed.
For the right subtree...
90 77 62 88

Body:
A is a pre-order traversal, whereas B is an in-order traversal.

An easy way for you to figure out the order of printing is to look at how you visit the nodes themselves. I usually draw an outline around the outside of the tree (starting at the root and moving through the left or right based on the sub-tree you are traversing first). If I am doing a pre-order traversal, I print out a node whenever I move along its outside. If I am doing an in-order traversal, I print out a node only when I move under it (this makes sense when you look at in-order traversals, because you end up printing the leaves first; they are the first nodes you move under when you draw the outline). If I am doing a post-order traversal, I print out a node only when I move along its inside.

UPDATE

The reason 30 gets printed out after 5 and 8 is that you are not performing a purely pre-order traversal. You're jumping between a pre-order and an in-order traversal.

An easy way to figure out the order is to actually write down the steps your code goes through as you trace through it (I frequently use pen/pencil and paper to keep the information together). For example, you could do write out a call-stack like this:

A(60)
  printf(60)
  call B(60.left)
    B(30)
      call A(30.left)
        A(5)
          printf(5)
          call B(5.left)
            B(null)
          call B(5.right)
            B(8)
              call A(8.left)
                A(null)
              printf(8)
              call A(8.right)
                A(null)
      printf(30)
      call A(30.right)
        A(38)
        ...

You can easily see the order in which the nodes are printed, and more importantly, why you "jump" from printing 8 to printing 30 (one recursive call has ended and you're falling back one level).


问:
New to Angular 2, attempting to load data into a table
Let me start this off by saying I am very new to Angular2. So I am trying to load the list EMPS into my table. Here's my app.component.ts file which has the majority of my code so far

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

export class Emp {
  name: string;
  email: string;
  office: string;
}

const EMPS: Emp[] = [
  { name: 'test1', email: 'test1@test.com', office: 'NY' },
  { name: 'test2', email: 'test2@test.com', office: 'LA' },
  { name: 'test3', email: 'test3@test.com', office: 'CHA' }
];

@Component({
  selector: 'my-app',
  template: `
<h1>{{ title }}</h1>
<div *ngFor="let d of data | async">
    <table border=1>
        <tr>
            <td>
                <h3>name: {{ d.name }}</h3>
            </td>
            <td>
                <h3>email: {{ d.email }}</h3>
            </td>
            <td>
                <h3>office: {{ d.office }}</h3>
            </td>
            <td>
        </tr>
    </table>
</div>
  `,
  styles: [`

  `]
})
export class AppComponent {
  title = 'TestTable';
  emps = EMPS;
  data = this.emps;

}
</code>```

Here are the errors I am getting:

I am pretty lost at the moment and I have no clue what to do. Can anyone help me out?

答: Drop the use of the async pipe in your *ngFor. That should be used for iterating an Observable. You're using "static" content, not an Observable.

Body:
Let me start this off by saying I am very new to Angular2. So I am trying to load the list EMPS into my table. Here's my app.component.ts file which has the majority of my code so far

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

export class Emp {
  name: string;
  email: string;
  office: string;
}

const EMPS: Emp[] = [
  { name: 'test1', email: 'test1@test.com', office: 'NY' },
  { name: 'test2', email: 'test2@test.com', office: 'LA' },
  { name: 'test3', email: 'test3@test.com', office: 'CHA' }
];

@Component({
  selector: 'my-app',
  template: `

{{ title }}

name: {{ d.name }}

email: {{ d.email }}

office: {{ d.office }}

  `,
  styles: [`

  `]
})
export class AppComponent {
  title = 'TestTable';
  emps = EMPS;
  data = this.emps;

}

Here are the errors I am getting:

I am pretty lost at the moment and I have no clue what to do. Can anyone help me out?


问:
Why won't org.apache.httpcomponents work in Java?
So, the problem is: I cannot load the imports. Help...

I got this code from online just to experiment with how it works. The problem is that the error that a "class, interface, or enum expected." It just won't compile and keeps asking for a JAR due to the dependencies at the top. I don't even know what dependencies were until I saw this program. Can someone please tell me why it's not working, and attempt to fix it? I tried all the .JAR Intellij suggested, then I tried searching up the issue but most of the answers were irrelevant or too complicated involving Maven or something. Please help...

```<code><dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>

import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpDocumentExistsWithHttpClient {

/**
 * check if a document exists in a sharepoint library
 */
public static void main(String[] args) throws Exception{
    CloseableHttpClient httpclient = HttpClients.custom()
            .setRetryHandler(new DefaultHttpRequestRetryHandler(0,false))
            .build();

    String user = "myusername";
    String pwd = "mypassword";
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY,
            new NTCredentials(user, pwd, "", ""));

    // You may get 401 if you go through a load-balancer.
    // To fix this, go directly to one of the sharepoint web server or
    // change the config. See this article :
    // http://blog.crsw.com/2008/10/14/unauthorized-401-1-exception-calling-web-services-in-sharepoint/
    HttpHost target = new HttpHost("web01.mysharepoint.local", 80, "http");
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);

    // The authentication is NTLM.
    // To trigger it, we send a minimal http request
    HttpHead request1 = new HttpHead("/");
    CloseableHttpResponse response1 = null;
    try {
        response1 = httpclient.execute(target, request1, context);
        EntityUtils.consume(response1.getEntity());
        System.out.println("1 : " + response1.getStatusLine().getStatusCode());
    }
    finally {
        if (response1 != null ) response1.close();
    }

    // The real request, reuse authentication
    String file = "/30500C/PubDoc/TEST/jira.log";  // source
    HttpGet request2 = new HttpGet("/_api/web/GetFileByServerRelativeUrl('" + file + "')/Etag");
    CloseableHttpResponse response2 = null;
    try {
        response2 = httpclient.execute(target, request2, context);
        EntityUtils.consume(response2.getEntity());
        int rc = response2.getStatusLine().getStatusCode();
        String reason = response2.getStatusLine().getReasonPhrase();
        if (rc != HttpStatus.SC_OK) {
            System.out.println(file + " is missing.  Reason : "
                    + reason + "   rc : " + rc + "(500 is the equivalent of NOT FOUND)");
        }
        else {
            System.out.println(file + " exists.");
        }
    }
    finally {
        if (response2 != null) response2.close();
    }
    return;
}
}
</code>```

I'm literally just trying to compile this in JGrasp and IntelliJ. Not that experienced with Java.

答:
First of all, Maven is a dependency management and build tool, which can download dependencies automatically for you, if it is set-up.

The first piece of code (<dependency>...) are instructions to maven to fetch the dependencies. it belongs into a pom.xml file not in your class.

If you are not set-up for this and don't want to get into it you can download the needed JARs at https://hc.apache.org/downloads.cgi. And make sure to add this to the classpath.

I do recommend that you get familiar with a tool like Maven as you will encounter dependencies all along when working with Java and it does simplify a lot of things in the long run.

Body:
So, the problem is: I cannot load the imports. Help...

I got this code from online just to experiment with how it works. The problem is that the error that a "class, interface, or enum expected." It just won't compile and keeps asking for a JAR due to the dependencies at the top. I don't even know what dependencies were until I saw this program. Can someone please tell me why it's not working, and attempt to fix it? I tried all the .JAR Intellij suggested, then I tried searching up the issue but most of the answers were irrelevant or too complicated involving Maven or something. Please help...

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>

import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpDocumentExistsWithHttpClient {

/**
 * check if a document exists in a sharepoint library
 */
public static void main(String[] args) throws Exception{
    CloseableHttpClient httpclient = HttpClients.custom()
            .setRetryHandler(new DefaultHttpRequestRetryHandler(0,false))
            .build();

    String user = "myusername";
    String pwd = "mypassword";
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY,
            new NTCredentials(user, pwd, "", ""));

    // You may get 401 if you go through a load-balancer.
    // To fix this, go directly to one of the sharepoint web server or
    // change the config. See this article :
    // http://blog.crsw.com/2008/10/14/unauthorized-401-1-exception-calling-web-services-in-sharepoint/
    HttpHost target = new HttpHost("web01.mysharepoint.local", 80, "http");
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);

    // The authentication is NTLM.
    // To trigger it, we send a minimal http request
    HttpHead request1 = new HttpHead("/");
    CloseableHttpResponse response1 = null;
    try {
        response1 = httpclient.execute(target, request1, context);
        EntityUtils.consume(response1.getEntity());
        System.out.println("1 : " + response1.getStatusLine().getStatusCode());
    }
    finally {
        if (response1 != null ) response1.close();
    }

    // The real request, reuse authentication
    String file = "/30500C/PubDoc/TEST/jira.log";  // source
    HttpGet request2 = new HttpGet("/_api/web/GetFileByServerRelativeUrl('" + file + "')/Etag");
    CloseableHttpResponse response2 = null;
    try {
        response2 = httpclient.execute(target, request2, context);
        EntityUtils.consume(response2.getEntity());
        int rc = response2.getStatusLine().getStatusCode();
        String reason = response2.getStatusLine().getReasonPhrase();
        if (rc != HttpStatus.SC_OK) {
            System.out.println(file + " is missing.  Reason : "
                    + reason + "   rc : " + rc + "(500 is the equivalent of NOT FOUND)");
        }
        else {
            System.out.println(file + " exists.");
        }
    }
    finally {
        if (response2 != null) response2.close();
    }
    return;
}
}

I'm literally just trying to compile this in JGrasp and IntelliJ. Not that experienced with Java.


问:
Cloudability AWS Amazon API Gateway Widget Set Up
I am trying to set up a widget in Cloudability that will track the costs of a specific Amazon API Gateway. In the filter steps I set Service Equals Amazon API Gateway but I am unsure which further filters I need. The gateway resources are

What are the correct filter steps I need here?

答: Here is the response from Cloudability support: "after digging, I do not believe that there is a way to surface the key/value stage variables for the API Gateways at this time"</p>


问:
Is there a way to dynamically identify and expand an embedded table's columns?
If I want to expand this embedded table...

...and I click on the expand button, I'm presented with the dropdown to select which columns I want to expand:

However, if I choose '(Select All Columns)' to expand them all, Power Query turns that into hard-coded column names of all the columns at the time I do that. Like this:

```<code>= Table.ExpandTableColumn(Source, "AllData", {"Column1", "Column2", "Column3", "Column4", "Custom"}, {"Column1", "Column2", "Column3", "Column4", "Custom"})
</code>```

After that, if the underlying embedded table's columns change, the hard-coded column names will no longer be relevant and the query will "break."

So how can I tell it to dynamically identify and extract all of the current columns of the embedded table?

答:
You can do something like this to get the list of column names:

List.Accumulate(Source[AllData], {}, (state, current) => List.Union({state, Table.ColumnNames(current)}))

This goes through each cell in the column, gets the column names from the table in that cell, and adds the new names to the result. It's easier to store this in a new step and then reference that in your next step.

Keep in mind that this method can be much slower than passing in the list of names you know about because it has to scan through the entire table to get the column names. You may also have problems if you use this for the third parameter in Table.ExpandTableColumn because it could use a column name that already exists.

Body:
If I want to expand this embedded table...

...and I click on the expand button, I'm presented with the dropdown to select which columns I want to expand:

However, if I choose '(Select All Columns)' to expand them all, Power Query turns that into hard-coded column names of all the columns at the time I do that. Like this:

= Table.ExpandTableColumn(Source, "AllData", {"Column1", "Column2", "Column3", "Column4", "Custom"}, {"Column1", "Column2", "Column3", "Column4", "Custom"})

After that, if the underlying embedded table's columns change, the hard-coded column names will no longer be relevant and the query will "break."

So how can I tell it to dynamically identify and extract all of the current columns of the embedded table?


问:
Count the number of null values into an Oracle table?
I need to count the number of null values of all the columns in a table in Oracle.

For instance, I execute the following statements to create a table TEST and insert data.

```<code> CREATE TABLE TEST
 (  A VARCHAR2(20 BYTE),
    B VARCHAR2(20 BYTE),
    C VARCHAR2(20 BYTE)
  );
Insert into TEST (A) values ('a');
Insert into TEST (B) values ('b');
Insert into TEST (C) values ('c');
</code>```

Now, I write the following code to compute the number of null values in the table TEST:

```<code>declare
cnt number :=0;
temp number :=0;
begin
  for r in ( select column_name, data_type
             from    user_tab_columns
             where table_name = upper('test')
             order by column_id )
  loop
      if r.data_type <> 'NOT NULL' then
         select count(*) into temp FROM TEST where r.column_name IS NULL;
         cnt := cnt + temp;
      END IF;
  end loop;
   dbms_output.put_line('Total: '||cnt);
end;
/
</code>```

It returns 0, when the expected value is 6.

Where is the error?

Thanks in advance.

答:
```<code>select COUNT(1) TOTAL from table where COLUMN is NULL;
</code>```

Body:
I need to count the number of null values of all the columns in a table in Oracle.

For instance, I execute the following statements to create a table TEST and insert data.

 CREATE TABLE TEST
 (  A VARCHAR2(20 BYTE),
    B VARCHAR2(20 BYTE),
    C VARCHAR2(20 BYTE)
  );
Insert into TEST (A) values ('a');
Insert into TEST (B) values ('b');
Insert into TEST (C) values ('c');

Now, I write the following code to compute the number of null values in the table TEST:

declare
cnt number :=0;
temp number :=0;
begin
  for r in ( select column_name, data_type
             from    user_tab_columns
             where table_name = upper('test')
             order by column_id )
  loop
      if r.data_type <> 'NOT NULL' then
         select count(*) into temp FROM TEST where r.column_name IS NULL;
         cnt := cnt + temp;
      END IF;
  end loop;
   dbms_output.put_line('Total: '||cnt);
end;
/

It returns 0, when the expected value is 6.

Where is the error?

Thanks in advance.


问:
Oracle sql pattern sorting
I have a pattern like this - "pqrst ##ind##123456##ind## hggff 1234". I have to extract numbers between ##ind## and ##ind##. Using pl/sql. Suggest</p>

答:
SQL

```<code>WITH d
     AS (SELECT 'pqrst ##ind##123456##ind## hggff 1234'       expr,
                '.*[\#]{2}ind[\#]{2}(\d+)[\#]{2}ind[\#]{2}.*' match
           FROM DUAL)
SELECT expr, REGEXP_REPLACE (expr, match, '\1') n
  FROM d
/
</code>```

PL/SQL

```<code>DECLARE
   expr    VARCHAR2 (64) := 'pqrst ##ind##123456##ind## hggff 1234';
   match   VARCHAR2 (64) := '.*[\#]{2}ind[\#]{2}(\d+)[\#]{2}ind[\#]{2}.*';
BEGIN
   DBMS_OUTPUT.PUT_LINE (REGEXP_REPLACE (expr, match, '\1'));
END;
/
</code>```

Title: Oracle sql pattern sorting

Body:
SQL

WITH d
     AS (SELECT 'pqrst ##ind##123456##ind## hggff 1234'       expr,
                '.*[\#]{2}ind[\#]{2}(\d+)[\#]{2}ind[\#]{2}.*' match
           FROM DUAL)
SELECT expr, REGEXP_REPLACE (expr, match, '\1') n
  FROM d
/

PL/SQL

DECLARE
   expr    VARCHAR2 (64) := 'pqrst ##ind##123456##ind## hggff 1234';
   match   VARCHAR2 (64) := '.*[\#]{2}ind[\#]{2}(\d+)[\#]{2}ind[\#]{2}.*';
BEGIN
   DBMS_OUTPUT.PUT_LINE (REGEXP_REPLACE (expr, match, '\1'));
END;
/


问:
How to Find The Earliest Date in Each Month From a List?
Consider the following list:

```<code>15/5/2017,
3/5/2017,
7/4/2017,
4/4/2017,
1/4/2017,
31/3/2017,
22/3/2017,
5/3/2017,
2/3/2017
</code>```

We expect the output to be:

```<code>3/5/2017,
1/4/2017,
2/3/2017
</code>```

I tried

```<code>        List<StockValue> monthlyStocks = new List<StockValue>();
        List<StockValue> MonthlyFirstStock = new List<StockValue>();
        foreach(StockValue st in data)
        {
            if(monthlyStocks.Count > 0)
            {
                if(st.Date.Month != monthlyStocks.Last().Date.Month)
                {
                    MonthlyFirstStock.Add(monthlyStocks.OrderBy(x => x.Date).FirstOrDefault());
                    monthlyStocks = new List<StockValue>();
                }
            }

            monthlyStocks.Add(st);
        }
        MonthlyFirstStock.Add(monthlyStocks.OrderBy(x => x.Date).FirstOrDefault());
</code>```

答:
Explanation in comments.</p>

```<code>public class Program
{
    public static void Main(string[] args)
    {
        var dates = new List<DateTime>();
        dates.Add(new DateTime(2017, 5, 15));
        dates.Add(new DateTime(2017, 5, 3));
        dates.Add(new DateTime(2017, 4, 7));
        dates.Add(new DateTime(2017, 4, 4));
        dates.Add(new DateTime(2017, 4, 1));
        dates.Add(new DateTime(2017, 3, 31));
        dates.Add(new DateTime(2017, 3, 22));
        dates.Add(new DateTime(2017, 3, 5));
        dates.Add(new DateTime(2017, 3, 2));

        var firstOfEachMonths = dates
            // Group the dates by their month.
            .GroupBy(date => date.Month)
            // Project each group into the earliest day.
            .Select(group => group
                    .OrderBy(date => date.Day)
                    .First())
            .ToList();

        /*
         * Output:
         * 03.05.2017 00:00:00
         * 01.04.2017 00:00:00
         * 02.03.2017 00:00:00
         */
        foreach (var firstOfEachMonth in firstOfEachMonths)
        {
            Console.Out.WriteLine(firstOfEachMonth);
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Consider the following list:

15/5/2017,
3/5/2017,
7/4/2017,
4/4/2017,
1/4/2017,
31/3/2017,
22/3/2017,
5/3/2017,
2/3/2017

We expect the output to be:

3/5/2017,
1/4/2017,
2/3/2017

I tried

        List<StockValue> monthlyStocks = new List<StockValue>();
        List<StockValue> MonthlyFirstStock = new List<StockValue>();
        foreach(StockValue st in data)
        {
            if(monthlyStocks.Count > 0)
            {
                if(st.Date.Month != monthlyStocks.Last().Date.Month)
                {
                    MonthlyFirstStock.Add(monthlyStocks.OrderBy(x => x.Date).FirstOrDefault());
                    monthlyStocks = new List<StockValue>();
                }
            }

            monthlyStocks.Add(st);
        }
        MonthlyFirstStock.Add(monthlyStocks.OrderBy(x => x.Date).FirstOrDefault());

Body:
Explanation in comments.

public class Program
{
    public static void Main(string[] args)
    {
        var dates = new List<DateTime>();
        dates.Add(new DateTime(2017, 5, 15));
        dates.Add(new DateTime(2017, 5, 3));
        dates.Add(new DateTime(2017, 4, 7));
        dates.Add(new DateTime(2017, 4, 4));
        dates.Add(new DateTime(2017, 4, 1));
        dates.Add(new DateTime(2017, 3, 31));
        dates.Add(new DateTime(2017, 3, 22));
        dates.Add(new DateTime(2017, 3, 5));
        dates.Add(new DateTime(2017, 3, 2));

        var firstOfEachMonths = dates
            // Group the dates by their month.
            .GroupBy(date => date.Month)
            // Project each group into the earliest day.
            .Select(group => group
                    .OrderBy(date => date.Day)
                    .First())
            .ToList();

        /*
         * Output:
         * 03.05.2017 00:00:00
         * 01.04.2017 00:00:00
         * 02.03.2017 00:00:00
         */
        foreach (var firstOfEachMonth in firstOfEachMonths)
        {
            Console.Out.WriteLine(firstOfEachMonth);
        }
    }
}


问:
Why Spark explain these two query differently?
So I have these two queries to achieve the same goal. Using Spark-SQL.

Query A:

```<code>SELECT * FROM inspex.defect_parquet a
INNER JOIN inspex.layer_parquet b
ON a.id = b.id
AND b.name = 'Example1';
</code>```

Query B:

```<code>SELECT * FROM inspex.defect_parquet
WHERE inspex.layer_scan_index
IN    (SELECT layer_scan_index
      FROM inspex.layer_parquet
      WHERE name = 'Example1');
</code>```

defect_parquet is a pretty large table and layer_parquet is a small table with several hundreds kb.

Query B is 80% faster than A. And when I see the explanation of how Spark run this. Here is for Query A:
Here is for Query B:

Seems like Spark handles these differently. Could someone explain this to me? And why is Query B faster?

答:
I think that statistics tells everything:

both version uses broadcast join

however, in  the second query you make project in subquery, so the output table is much smaller - that causes much smaller broadcast size and shorter time

first query tries to pre-filter large dataset, however without many changes - dataset is still big, so this optimization only slows down your query number one

Body:
So I have these two queries to achieve the same goal. Using Spark-SQL.

Query A:

SELECT * FROM inspex.defect_parquet a
INNER JOIN inspex.layer_parquet b
ON a.id = b.id
AND b.name = 'Example1';

Query B:

SELECT * FROM inspex.defect_parquet
WHERE inspex.layer_scan_index
IN    (SELECT layer_scan_index
      FROM inspex.layer_parquet
      WHERE name = 'Example1');

defect_parquet is a pretty large table and layer_parquet is a small table with several hundreds kb.

Query B is 80% faster than A. And when I see the explanation of how Spark run this. Here is for Query A:
Here is for Query B:

Seems like Spark handles these differently. Could someone explain this to me? And why is Query B faster?


问:
looking for a way to partition bigQuery tables by column value
I am working with genomic data. There is no outdated data so i can not partition by date and the data mass is large.

Is there a way to partition by column value? can it be automated somehow?
I would like to use it for visualization and the preferred size is 1 GB table
ay idea?

thanks,
eilalan

答:
As of today - there is no way to partition table by column value

There is a Partition on non-date field - feature request for this that you can star to vote for it


问:
Perl Regex - Exact Match
I am trying to put together a regex that searches logs for commands run against a file (".pan").

For example:

cat .pan

less .pan

cp .pan somedir

The file will only be named ".pan"

I am interested in any thing before or after the file name, but the regex should only be interested in the file named ".pan".

Originally I was using the regex:

```<code>.\.pan
</code>```

But I started seeing results such as:

```<code>command .pans
command .panyx extra characters
</code>```

Any suggestions would be appreciated.

Thank You!

答:
You may use a non-word boundary (\B) before . and a word boundary (\b) after pan:

```<code>\B\.pan\b
</code>```

See the regex demo

The \B\. will match any dot that is not preceded with a word char and n\b will match any n that is not followed with a word char.

Title: Perl Regex - Exact Match

Body:
I am trying to put together a regex that searches logs for commands run against a file (".pan").

For example:

cat .pan

less .pan

cp .pan somedir

The file will only be named ".pan"

I am interested in any thing before or after the file name, but the regex should only be interested in the file named ".pan".

Originally I was using the regex:

.\.pan

But I started seeing results such as:

command .pans
command .panyx extra characters

Any suggestions would be appreciated.

Thank You!

Body:
You may use a non-word boundary (\B) before . and a word boundary (\b) after pan:

\B\.pan\b

See the regex demo

The \B\. will match any dot that is not preceded with a word char and n\b will match any n that is not followed with a word char.


问:
c# messenger, send commands over network, protocol?
I'm making a c# messenger application just for fun, but I wanna do it good.
I want the possibility to send commands like a chat message, kick comand etc, but i dont know a good way to control it.

I could send an object over the networkstream, or I could send a string like: stream.write("command##");

maybe you know another way to fix this things, but I'm in stackoverflow atm.
Thanks.

答: If you want to turn your "for fun" project into a "professional development" project (as in, develop your skills, not professional-quality) try WCF.  It will handle the entire messaging architecture for you, and let you focus on your functionality.  Plus, WCF looks good on the resume.</p>


问:
$_POST method turns empty
Firstable, hello everyone. I have issue about the $_POST method, when I write this code block;

```<code>if (isset($_POST['menuduzenle'])) {

$menu_id=$_POST['menu_id']; //It didn't turn with value in mysql

$ayarguncelle=mysql_query("update menuler set menu_ad='".$_POST['menu_ad']."',menu_link='".$_POST['menu_link']."'where menu_id='$menu_id'");

if(mysql_affected_rows())
{

    header("Location:../menuleriduzenle.php?guncelleme=basarili&menu_id=$menu_id");
}else{

    header("Location:../menuleriduzenle.php?guncelleme=basarisiz&menu_id=$menu_id");}

}
</code>```

menu_id turns emty, what I need to do for solve this?

and here it's html code

form

```<code><form action="network/islem.php" method="POST">

     <div class="col-md-12">

        <div class="form-group col-md-9">
            <label>Menu Adı: </label>
            <input class="form-control" name="menu_ad" value="<?php echo $menucek['menu_ad']; ?>" />
        </div>

    </div>

    <div class="col-md-12">

        <div class="form-group col-md-9">
            <label>Menu Link: </label>
            <input class="form-control" name="menu_link" value="<?php echo $menucek['menu_link']; ?>" />
        </div>

    </div>

    <div class="col-md-12">
        <div class="form-group col-md-6">
            <input class="btn btn-primary col-md-3" type="submit" name="menuduzenle" value="Edit Menu">
        </div>

    </form>
</code>```

and

```<code> <td><a href="menuleriduzenle.php?menu_id=<?php echo $menucek['menu_id'] ?>" type="submit"><button class="btn btn-primary col-md-12">Edit</button></a></td>
</code>```

答:
You not send any one input with name 'menu_id' on your from.

```<code><form action="network/islem.php" method="POST">

     <div class="col-md-12">

        <div class="form-group col-md-9">
            <label>Menu Adı: </label>
            <input class="form-control" name="menu_ad" value="<?php echo $menucek['menu_ad']; ?>" />
        </div>

    </div>

    <div class="col-md-12">

        <div class="form-group col-md-9">
            <label>Menu Link: </label>
            <input class="form-control" name="menu_link" value="<?php echo $menucek['menu_link']; ?>" />
        </div>

    </div>

    <div class="col-md-12">
        <div class="form-group col-md-6">
            <input class="btn btn-primary col-md-3" type="submit" name="menuduzenle" value="Edit Menu">
   </div>
   <input type="hidden" name="menu_id" value="<?php echo $_GET['menu_id'] ?>" />

    </form>
</code>```

You input name "menu_ad" would be "menu_id" or fault other input with name "menu_id" on you sample.

Title: $_POST method turns empty

Body:
Firstable, hello everyone. I have issue about the $_POST method, when I write this code block;

if (isset($_POST['menuduzenle'])) {

$menu_id=$_POST['menu_id']; //It didn't turn with value in mysql

$ayarguncelle=mysql_query("update menuler set menu_ad='".$_POST['menu_ad']."',menu_link='".$_POST['menu_link']."'where menu_id='$menu_id'");

if(mysql_affected_rows())
{

    header("Location:../menuleriduzenle.php?guncelleme=basarili&menu_id=$menu_id");
}else{

    header("Location:../menuleriduzenle.php?guncelleme=basarisiz&menu_id=$menu_id");}

}

menu_id turns emty, what I need to do for solve this?

and here it's html code

form

<form action="network/islem.php" method="POST">

            Menu Adı:
            <input class="form-control" name="menu_ad" value="<?php echo $menucek['menu_ad']; ?>" />

            Menu Link:
            <input class="form-control" name="menu_link" value="<?php echo $menucek['menu_link']; ?>" />

            <input class="btn btn-primary col-md-3" type="submit" name="menuduzenle" value="Edit Menu">

    </form>

and

 <a href="menuleriduzenle.php?menu_id=<?php echo $menucek['menu_id'] ?>" type="submit"><button class="btn btn-primary col-md-12">Edit</button>

Body:
You not send any one input with name 'menu_id' on your from.

<form action="network/islem.php" method="POST">

     <div class="col-md-12">

        <div class="form-group col-md-9">
            <label>Menu Adı: </label>
            <input class="form-control" name="menu_ad" value="<?php echo $menucek['menu_ad']; ?>" />
        </div>

    </div>

    <div class="col-md-12">

        <div class="form-group col-md-9">
            <label>Menu Link: </label>
            <input class="form-control" name="menu_link" value="<?php echo $menucek['menu_link']; ?>" />
        </div>

    </div>

    <div class="col-md-12">
        <div class="form-group col-md-6">
            <input class="btn btn-primary col-md-3" type="submit" name="menuduzenle" value="Edit Menu">
   </div>
   <input type="hidden" name="menu_id" value="<?php echo $_GET['menu_id'] ?>" />

    </form>

You input name "menu_ad" would be "menu_id" or fault other input with name "menu_id" on you sample.


问:
How two components communicate, in angular 2?
I wrote two components, as follows:

DynSelectionComponent.ts (generic select tag, because the select tag does not support multi-select, filter, so this component uses ng2-selet).

user-list.component.ts (this component corresponds to the html template using DynSelectionComponent, and provides a collection for DynSelectionComponent shown as option).

DynSelectionComponent.ts

```<code>import { Component, OnInit, ViewEncapsulation, Input, SimpleChanges } from '@angular/core';

@Component({
    selector: 'dyn-selection',
    template: `
    <ng-select [allowClear]="true"
                [items]="items"
                [disabled]="disabled"
                (data)="refreshValue($event)"
                (selected)="selected($event)"
                (removed)="removed($event)"
                (typed)="typed($event)"
                [placeholder]="placeholder">
    </ng-select>
    `,
})

export class DynSelectionComponent implements OnInit {
    @Input() inputItems: any[];//The other components are passed over the collection

    private value: any = {};
    private disabled: boolean = false;
    private placeholder: string = '';
    items: Array<any> = [];

    ngOnChanges(changes: SimpleChanges) {
        let newItems: any[] = [];
        for (let propName in changes) {
            if (propName == 'inputItems') {
                this.inputItems.forEach((compay: { companyId: string, companyName: string }) => {
                    newItems.push({
                        id: compay.companyId,
                        text: `${compay.companyName}`
                    });
                });
                this.items = newItems;
            }
        }
    }

    public selected(value: any): void {
        console.log('Selected value is: ', value);
    }
    public removed(value: any): void {
        console.log('Removed value is: ', value);
    }
    public typed(value: any): void {
        console.log('New search input: ', value);
    }
    public refreshValue(value: any): void {
        this.value = value;
    }
}
</code>```

user-list.html(This file uses DynSelectionComponent)

```<code><dyn-selection [inputItems]='companies' name="companyId" id="companyId"></dyn-selection>
</code>```

user-list.component.ts(This component assigns a value for the companies property)

```<code>getCompanies(){
    var url = "/api/company/queryCompany";
    this.httpPlus.post(url, {
        data:"c"
    }).subscribe((data: any) => {
        this.companies = data.data;
    }, (err)=> {
        this.companies = [];
    });
}
</code>```

This time, user-list.html file can normally use DynSelectionComponent component, the normal display companies collection.

However, when  triggers the onchange event, how does the user-list.component.ts component get the modified value of companyId ?

What should I do ? Thank you for your reply.

答:
Components can communicate in two ways
1. parent and child relation. through @Input, @output and eventemitter
2. Through shared service.

https://angular.io/docs/ts/latest/cookbook/component-communication.html

If you have complex arch then you can use ngrx/store.

Body:
I wrote two components, as follows:

DynSelectionComponent.ts (generic select tag, because the select tag does not support multi-select, filter, so this component uses ng2-selet).

user-list.component.ts (this component corresponds to the html template using DynSelectionComponent, and provides a collection for DynSelectionComponent shown as option).

DynSelectionComponent.ts

import { Component, OnInit, ViewEncapsulation, Input, SimpleChanges } from '@angular/core';

@Component({
    selector: 'dyn-selection',
    template: `
    <ng-select [allowClear]="true"
                [items]="items"
                [disabled]="disabled"
                (data)="refreshValue($event)"
                (selected)="selected($event)"
                (removed)="removed($event)"
                (typed)="typed($event)"
                [placeholder]="placeholder">
    </ng-select>
    `,
})

export class DynSelectionComponent implements OnInit {
    @Input() inputItems: any[];//The other components are passed over the collection

    private value: any = {};
    private disabled: boolean = false;
    private placeholder: string = '';
    items: Array<any> = [];

    ngOnChanges(changes: SimpleChanges) {
        let newItems: any[] = [];
        for (let propName in changes) {
            if (propName == 'inputItems') {
                this.inputItems.forEach((compay: { companyId: string, companyName: string }) => {
                    newItems.push({
                        id: compay.companyId,
                        text: `${compay.companyName}`
                    });
                });
                this.items = newItems;
            }
        }
    }

    public selected(value: any): void {
        console.log('Selected value is: ', value);
    }
    public removed(value: any): void {
        console.log('Removed value is: ', value);
    }
    public typed(value: any): void {
        console.log('New search input: ', value);
    }
    public refreshValue(value: any): void {
        this.value = value;
    }
}

user-list.html(This file uses DynSelectionComponent)

<dyn-selection [inputItems]='companies' name="companyId" id="companyId"></dyn-selection>

user-list.component.ts(This component assigns a value for the companies property)

getCompanies(){
    var url = "/api/company/queryCompany";
    this.httpPlus.post(url, {
        data:"c"
    }).subscribe((data: any) => {
        this.companies = data.data;
    }, (err)=> {
        this.companies = [];
    });
}

This time, user-list.html file can normally use DynSelectionComponent component, the normal display companies collection.

However, when  triggers the onchange event, how does the user-list.component.ts component get the modified value of companyId ?

What should I do ? Thank you for your reply.


问:
Java 8: Can we use map to make an instance method ref in a stream?
I'm trying to refactor some of my code to Java 8. Is it possible to make an instance method ref to a method that takes 2 params with map method in streams? Below is my code.

```<code>for (SubjectAreaMappings pageFromEnum : SubjectAreaMappings.values()) {
    if (page.equals(pageFromEnum.toString())) {
        for (SubjectAreaCode subjectAreaCode : pageFromEnum.getCodes()) {
            list.addAll(areaDAO.getData(context, subjectAreaCode));
        }
    }
}
</code>```

I'm trying to refactor the inner for loop to something like the following code, but is it map() that I should be using or reduce()? How can I pass the 2 params context and subjectAreaCode?

```<code>Arrays.asList(pageFromEnum.getCode()).stream().map(somethng wrt method ref here).collect(toList())
</code>```

答:
Here is a little shorter code by StreamEx:

```<code>StreamEx.of(subjectAreaMappings.values())
        .filter(p -> page.equals(p.toString()))
        .flatMap(p -> StreamEx.of(p.getCodes()))
        .flatMap(c -> StreamEx.of(areaDAO.getData(context, c)))
        .toList();
</code>```

if areaDAO.getData is a database access, it's a good example to use parallel stream here:

```<code>StreamEx.of(subjectAreaMappings.values())
        .filter(p -> page.equals(p.toString()))
        .flatMap(p -> StreamEx.of(p.getCodes()))
        .parallel()
        .flatMap(c -> StreamEx.of(areaDAO.getData(context, c)))
        .toList();
</code>```

Body:
I'm trying to refactor some of my code to Java 8. Is it possible to make an instance method ref to a method that takes 2 params with map method in streams? Below is my code.

for (SubjectAreaMappings pageFromEnum : SubjectAreaMappings.values()) {
    if (page.equals(pageFromEnum.toString())) {
        for (SubjectAreaCode subjectAreaCode : pageFromEnum.getCodes()) {
            list.addAll(areaDAO.getData(context, subjectAreaCode));
        }
    }
}

I'm trying to refactor the inner for loop to something like the following code, but is it map() that I should be using or reduce()? How can I pass the 2 params context and subjectAreaCode?

Arrays.asList(pageFromEnum.getCode()).stream().map(somethng wrt method ref here).collect(toList())

Body:
Here is a little shorter code by StreamEx:

StreamEx.of(subjectAreaMappings.values())
        .filter(p -> page.equals(p.toString()))
        .flatMap(p -> StreamEx.of(p.getCodes()))
        .flatMap(c -> StreamEx.of(areaDAO.getData(context, c)))
        .toList();

if areaDAO.getData is a database access, it's a good example to use parallel stream here:

StreamEx.of(subjectAreaMappings.values())
        .filter(p -> page.equals(p.toString()))
        .flatMap(p -> StreamEx.of(p.getCodes()))
        .parallel()
        .flatMap(c -> StreamEx.of(areaDAO.getData(context, c)))
        .toList();


问:
Asynchronous App for multiplication can not be compiled
i try to make my 1st AsyncTask in App. This application should download from 2 field numbers, then multiplication and display score in 3rd field.

It is easy, but i want to learn how to use AsyncTask and i want this metod(for multiplication) put in other thread.

In my opinion it look fine, but AndroidStudio underline my class MyTask. And suggets impement that same method... :

```<code>@Override
protected Void doInBackground(Double... params) {
    return null;
}
</code>```

Can i ask for tips, how i should do now ?

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

    private Button button;
    private EditText editText,editText2,editText3;
    private String a,b,c;
    private Double x1,x2,x3;

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

        button = (Button) findViewById(R.id.button);
        editText = (EditText) findViewById(R.id.editText);
        editText2 = (EditText) findViewById(R.id.editText2);
        editText3 = (EditText) findViewById(R.id.editText3);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                a = editText.getText().toString();
                b = editText2.getText().toString();
                x1 = Double.parseDouble(a);
                x2 = Double.parseDouble(b);

                calc();

            }

        });

    }

    private class MyTask extends AsyncTask<Double, Void, Void>{

        @Override
        protected Void doInBackground(Double x1, Double x2) {

            x3 = x1 * x2;
            c = String.valueOf(x3);
            editText3.setText(c);

            return null;
        }

    }

    private void calc() {
        new MyTask().execute();
    }

}
</code>```

答:
So you need replace
protected Void doInBackground(Double x1, Double x2)
in your code with
protected Void doInBackground(Double... params)
and you can access parameters like params[0] params[1] etc

See examples e.g. here
How can you pass multiple primitive parameters to AsyncTask?

Body:
i try to make my 1st AsyncTask in App. This application should download from 2 field numbers, then multiplication and display score in 3rd field.

It is easy, but i want to learn how to use AsyncTask and i want this metod(for multiplication) put in other thread.

In my opinion it look fine, but AndroidStudio underline my class MyTask. And suggets impement that same method... :

@Override
protected Void doInBackground(Double... params) {
    return null;
}

Can i ask for tips, how i should do now ?

public class MainActivity extends AppCompatActivity {

    private Button button;
    private EditText editText,editText2,editText3;
    private String a,b,c;
    private Double x1,x2,x3;

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

        button = (Button) findViewById(R.id.button);
        editText = (EditText) findViewById(R.id.editText);
        editText2 = (EditText) findViewById(R.id.editText2);
        editText3 = (EditText) findViewById(R.id.editText3);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                a = editText.getText().toString();
                b = editText2.getText().toString();
                x1 = Double.parseDouble(a);
                x2 = Double.parseDouble(b);

                calc();

            }

        });

    }

    private class MyTask extends AsyncTask<Double, Void, Void>{

        @Override
        protected Void doInBackground(Double x1, Double x2) {

            x3 = x1 * x2;
            c = String.valueOf(x3);
            editText3.setText(c);

            return null;
        }

    }

    private void calc() {
        new MyTask().execute();
    }

}


问:
angular 2 ngif not working even though function return true
I'm using Angular 2. I have an array and I am looping through each item and setting a boolean. I'm console logging to make sure it's being set properly.  However when I use this function against an *ngif it doesn't work. What crucial piece am I missing here?

template:

```<code> <div *ngFor="let item of viewableItems>
        <div class="thermometerMercury" *ngIf="showThermometer"></div>
 </div>
</code>```

.ts

```<code>  processedItems: Item[] = [];
  showThermometer: boolean;

  checkDonation() {
      for (let i = 0; i < this.processedItems.length; i++) {
          let out = this.processedItems[i];
      if (out.isDonation && out.donationAmountDonatedByClient === 0) {
        this.showThermometer = true;
      } else {
        this.showThermometer = false;
      }
      console.log(i, this.showThermometer);
    }
  }
</code>```

答:
This might be the issue:
1) processedItems is an array, which is being processed and getting validated each object.
2) showThermometer is not specific to Object(s) of array and it looks global.
3) Even showThermometer is true for object 1, there is chance of changing the value as false by object 2 ( when the condition is not satified )
4) The same variable is using by *ngFor

So, changes would be like below:

mplate:

```<code><div *ngFor="let item of processedItems>
        <div class="thermometerMercury" *ngIf="item.showThermometer"></div>
 </div>
</code>```

.ts

```<code>processedItems: Item[] = [];

  checkDonation() {
      for (let i = 0; i < this.processedItems.length; i++) {
          let out = this.processedItems[i];
      if (out.isDonation && out.donationAmountDonatedByClient === 0) {
        out.showThermometer = true;
      } else {
        out.showThermometer = false;
      }
      console.log(i, out.showThermometer);
    }
  }
</code>```

Body:
I'm using Angular 2. I have an array and I am looping through each item and setting a boolean. I'm console logging to make sure it's being set properly.  However when I use this function against an *ngif it doesn't work. What crucial piece am I missing here?

template:

.ts

  processedItems: Item[] = [];
  showThermometer: boolean;

  checkDonation() {
      for (let i = 0; i < this.processedItems.length; i++) {
          let out = this.processedItems[i];
      if (out.isDonation && out.donationAmountDonatedByClient === 0) {
        this.showThermometer = true;
      } else {
        this.showThermometer = false;
      }
      console.log(i, this.showThermometer);
    }
  }

Body:
This might be the issue:
1) processedItems is an array, which is being processed and getting validated each object.
2) showThermometer is not specific to Object(s) of array and it looks global.
3) Even showThermometer is true for object 1, there is chance of changing the value as false by object 2 ( when the condition is not satified )
4) The same variable is using by *ngFor

So, changes would be like below:

mplate:

<div *ngFor="let item of processedItems>
        <div class="thermometerMercury" *ngIf="item.showThermometer"></div>
 </div>

.ts

processedItems: Item[] = [];

  checkDonation() {
      for (let i = 0; i < this.processedItems.length; i++) {
          let out = this.processedItems[i];
      if (out.isDonation && out.donationAmountDonatedByClient === 0) {
        out.showThermometer = true;
      } else {
        out.showThermometer = false;
      }
      console.log(i, out.showThermometer);
    }
  }


问:
Date Range Formula
Page1:

From Date: TXTBOX1   To Date: TXTBOX2

BTNSUBMIT-CLICK
{
server.transfer("page2.aspx");
}

Page 2:

if (PreviousPage != null)
        {
            TextBox txt1 = PreviousPage.FindControl("TXTBOX1") as TextBox;
            TextBox txt2 = PreviousPage.FindControl("TXTBOX2") as TextBox;

```<code>        if (txt1.Text.Length != 0 && txt2.Text.Length != 0)
        {

         ReportDocument cryRpt = new ReportDocument();
         cryRpt.Load("MyReport.rpt");

            ParameterFieldDefinitions crParameterFieldDefinitions;
            ParameterFieldDefinition crParameterFieldDefinition;
            ParameterValues crParameterValues = new ParameterValues();
            ParameterDiscreteValue crParameterDiscreteValue = new
            ParameterDiscreteValue();

            crParameterDiscreteValue.Value = txt1.Text + txt2.Text;
            crParameterFieldDefinitions =
            cryRpt.DataDefinition.ParameterFields;
            crParameterFieldDefinition =
            crParameterFieldDefinitions["MyParameter"];
            crParameterValues = crParameterFieldDefinition.CurrentValues;

            crParameterValues.Clear();
            crParameterValues.Add(crParameterDiscreteValue);
            crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);

            CrystalReportViewer1.ReportSource = cryRpt;

        }

     }
</code>```

Formula In Formula Editor:

{Command.Date} >= {?MyParameter} and {Command.Date} <= {?MyParameter}

It works fine If report is displayed for single date. Not for Date Range.

Any Suggestions? Where i am wrong in formula / code ???

答:
You should pass the date fields as separate parameters, and reference them in your Formula Editor like this:</p>

```<code>{Command.Date} >= {?ParamDateFrom} and {Command.Date} <= {?ParamDateTo}
</code>```

Title: Date Range Formula

Body:
Page1:

From Date: TXTBOX1   To Date: TXTBOX2

BTNSUBMIT-CLICK
{
server.transfer("page2.aspx");
}

Page 2:

if (PreviousPage != null)
        {
            TextBox txt1 = PreviousPage.FindControl("TXTBOX1") as TextBox;
            TextBox txt2 = PreviousPage.FindControl("TXTBOX2") as TextBox;

        if (txt1.Text.Length != 0 && txt2.Text.Length != 0)
        {

         ReportDocument cryRpt = new ReportDocument();
         cryRpt.Load("MyReport.rpt");

            ParameterFieldDefinitions crParameterFieldDefinitions;
            ParameterFieldDefinition crParameterFieldDefinition;
            ParameterValues crParameterValues = new ParameterValues();
            ParameterDiscreteValue crParameterDiscreteValue = new
            ParameterDiscreteValue();

            crParameterDiscreteValue.Value = txt1.Text + txt2.Text;
            crParameterFieldDefinitions =
            cryRpt.DataDefinition.ParameterFields;
            crParameterFieldDefinition =
            crParameterFieldDefinitions["MyParameter"];
            crParameterValues = crParameterFieldDefinition.CurrentValues;

            crParameterValues.Clear();
            crParameterValues.Add(crParameterDiscreteValue);
            crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);

            CrystalReportViewer1.ReportSource = cryRpt;

        }

     }

Formula In Formula Editor:

{Command.Date} >= {?MyParameter} and {Command.Date} <= {?MyParameter}

It works fine If report is displayed for single date. Not for Date Range.

Any Suggestions? Where i am wrong in formula / code ???

Body:
You should pass the date fields as separate parameters, and reference them in your Formula Editor like this:

{Command.Date} >= {?ParamDateFrom} and {Command.Date} <= {?ParamDateTo}


问:
Error in reading contact information from Contact picker intent
I am making an app that reads contact name and number from contact intent and adds a note related to the corresponding contact.My should Add_note.java activity read information from contactscontract and set it onto the edit texts respectively.But it is showing some error.
Here is my Add_note.java activity:

```<code>package com.example.shubhangi.contactnotes;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;

public class Add_note extends AppCompatActivity {
    private static final int RESULT_PICK_CONTACT=1001;
    private EditText name;
    private EditText number;
    private EditText contactnot;
    ArrayList<NoteView> notes= new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_note);
        name=(EditText) findViewById(R.id.con_name);
        name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
                startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
            }
        });
        number=(EditText) findViewById(R.id.con_numb);
        contactnot=(EditText) findViewById(R.id.con_note);
        if(contactnot.getText()!=null){
            Button add=(Button)findViewById(R.id.save);
            add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String n1=name.getText().toString();
                    String n2=number.getText().toString();
                    String n3=contactnot.getText().toString();
                    NoteView nv =new NoteView();
                    nv.setName_contact(n1);
                    nv.setPhno_contact(n2);
                    nv.setNote_contact(n3);
                    notes.add(nv);
                    Intent i=new Intent(Add_note.this,MainActivity.class);
                    i.putExtra("Note list",notes);
                    startActivity(i);
                }
            });
        }
    }

    @Override
    public void onBackPressed() {
        Intent i=new Intent(Add_note.this,MainActivity.class);
        i.putExtra("Note list",notes);
        startActivity(i);
        super.onBackPressed();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // check whether the result is ok
        if (resultCode == RESULT_OK) {
            // Check for the request code, we might be usign multiple startActivityForReslut
            switch (requestCode) {
                case RESULT_PICK_CONTACT:
                    contactPicked(data);
                    break;
            }
        } else {
            Toast.makeText(Add_note.this, "Could not load contact", Toast.LENGTH_SHORT).show();
        }
    }
    private void contactPicked(Intent data)
    {
        Cursor cursor;
        try {
            Uri uri = data.getData();
            //Query the content uri
            String id = uri.getLastPathSegment();
            Integer id_c=Integer.parseInt(id);
            cursor = getContentResolver().query(uri, null, null, null, null);

            if(cursor.moveToNext()) {
                int columnIndex_name = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
                String stringName = cursor.getString(columnIndex_name);

                int columnIndex_HASPHONENUMBER = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
                String stringHasPhoneNumber = cursor.getString(columnIndex_HASPHONENUMBER);
                String stringNumber;
                if (stringHasPhoneNumber.equalsIgnoreCase("1")) {
                    Cursor cursorNum = getContentResolver().query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id_c,
                            null,
                            null);
                    int columnIndex_number = cursorNum.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    stringNumber = cursorNum.getString(columnIndex_number);
                    number.setText(stringNumber);
                    cursorNum.close();
                }
                name.setText(stringName);
                cursor.close();
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

    }
}
</code>```

And here is my log:

```<code>android.database.CursorIndexOutOfBoundsException: Index -1 reques android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
06-08 22:56:14.349 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
06-08 22:56:14.349 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:146)
06-08 22:56:14.349 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:60)
06-08 22:56:14.349 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.database.CursorWrapper.getString(CursorWrapper.java:114)
06-08 22:56:14.349 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at com.example.shubhangi.contactnotes.Add_note.contactPicked(Add_note.java:105)
06-08 22:56:14.349 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at com.example.shubhangi.contactnotes.Add_note.onActivityResult(Add_note.java:73)
06-08 22:56:14.349 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.app.Activity.dispatchActivityResult(Activity.java:6168)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.app.ActivityThread.deliverResults(ActivityThread.java:3733)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes D/ActivityThread: SEND_RESULT handled : 0 / ResultData{token=android.os.BinderProxy@60b629b results[ResultInfo{who=null, request=1001, result=-1, data=Intent { dat=content://com.android.contacts/data/13049 flg=0x1 }}]}
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3780)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.app.ActivityThread.access$1300(ActivityThread.java:162)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes V/ActivityThread: Performing resume of ActivityRecord{2e7cd6aa token=android.os.BinderProxy@60b629b {com.example.shubhangi.contactnotes/com.example.shubhangi.contactnotes.Add_note}} finished=false
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1461)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:106)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.os.Looper.loop(Looper.java:189)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5530)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
</code>```

答:
After you execute query, you must call cursor.moveToFirst()...

Try this one

```<code>    Cursor cursor = getContentResolver().query(Contacts.CONTENT_URI,
   null, null, null, null);

if(cursor != null && cursor.moveToFirst())
{
   String id = cursor.getString(cur.getColumnIndex(Contacts._ID));

    if (cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
     ...
</code>```

Body:
I am making an app that reads contact name and number from contact intent and adds a note related to the corresponding contact.My should Add_note.java activity read information from contactscontract and set it onto the edit texts respectively.But it is showing some error.
Here is my Add_note.java activity:

package com.example.shubhangi.contactnotes;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;

public class Add_note extends AppCompatActivity {
    private static final int RESULT_PICK_CONTACT=1001;
    private EditText name;
    private EditText number;
    private EditText contactnot;
    ArrayList<NoteView> notes= new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_note);
        name=(EditText) findViewById(R.id.con_name);
        name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
                startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
            }
        });
        number=(EditText) findViewById(R.id.con_numb);
        contactnot=(EditText) findViewById(R.id.con_note);
        if(contactnot.getText()!=null){
            Button add=(Button)findViewById(R.id.save);
            add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String n1=name.getText().toString();
                    String n2=number.getText().toString();
                    String n3=contactnot.getText().toString();
                    NoteView nv =new NoteView();
                    nv.setName_contact(n1);
                    nv.setPhno_contact(n2);
                    nv.setNote_contact(n3);
                    notes.add(nv);
                    Intent i=new Intent(Add_note.this,MainActivity.class);
                    i.putExtra("Note list",notes);
                    startActivity(i);
                }
            });
        }
    }

    @Override
    public void onBackPressed() {
        Intent i=new Intent(Add_note.this,MainActivity.class);
        i.putExtra("Note list",notes);
        startActivity(i);
        super.onBackPressed();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // check whether the result is ok
        if (resultCode == RESULT_OK) {
            // Check for the request code, we might be usign multiple startActivityForReslut
            switch (requestCode) {
                case RESULT_PICK_CONTACT:
                    contactPicked(data);
                    break;
            }
        } else {
            Toast.makeText(Add_note.this, "Could not load contact", Toast.LENGTH_SHORT).show();
        }
    }
    private void contactPicked(Intent data)
    {
        Cursor cursor;
        try {
            Uri uri = data.getData();
            //Query the content uri
            String id = uri.getLastPathSegment();
            Integer id_c=Integer.parseInt(id);
            cursor = getContentResolver().query(uri, null, null, null, null);

            if(cursor.moveToNext()) {
                int columnIndex_name = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
                String stringName = cursor.getString(columnIndex_name);

                int columnIndex_HASPHONENUMBER = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
                String stringHasPhoneNumber = cursor.getString(columnIndex_HASPHONENUMBER);
                String stringNumber;
                if (stringHasPhoneNumber.equalsIgnoreCase("1")) {
                    Cursor cursorNum = getContentResolver().query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id_c,
                            null,
                            null);
                    int columnIndex_number = cursorNum.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    stringNumber = cursorNum.getString(columnIndex_number);
                    number.setText(stringNumber);
                    cursorNum.close();
                }
                name.setText(stringName);
                cursor.close();
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

    }
}

And here is my log:

android.database.CursorIndexOutOfBoundsException: Index -1 reques android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
06-08 22:56:14.349 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
06-08 22:56:14.349 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:146)
06-08 22:56:14.349 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:60)
06-08 22:56:14.349 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.database.CursorWrapper.getString(CursorWrapper.java:114)
06-08 22:56:14.349 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at com.example.shubhangi.contactnotes.Add_note.contactPicked(Add_note.java:105)
06-08 22:56:14.349 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at com.example.shubhangi.contactnotes.Add_note.onActivityResult(Add_note.java:73)
06-08 22:56:14.349 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.app.Activity.dispatchActivityResult(Activity.java:6168)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.app.ActivityThread.deliverResults(ActivityThread.java:3733)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes D/ActivityThread: SEND_RESULT handled : 0 / ResultData{token=android.os.BinderProxy@60b629b results[ResultInfo{who=null, request=1001, result=-1, data=Intent { dat=content://com.android.contacts/data/13049 flg=0x1 }}]}
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3780)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.app.ActivityThread.access$1300(ActivityThread.java:162)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes V/ActivityThread: Performing resume of ActivityRecord{2e7cd6aa token=android.os.BinderProxy@60b629b {com.example.shubhangi.contactnotes/com.example.shubhangi.contactnotes.Add_note}} finished=false
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1461)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:106)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.os.Looper.loop(Looper.java:189)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5530)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
06-08 22:56:14.350 12446-12446/com.example.shubhangi.contactnotes W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)

Body:
After you execute query, you must call cursor.moveToFirst()...

Try this one

    Cursor cursor = getContentResolver().query(Contacts.CONTENT_URI,
   null, null, null, null);

if(cursor != null && cursor.moveToFirst())
{
   String id = cursor.getString(cur.getColumnIndex(Contacts._ID));

    if (cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
     ...