问:
Loaders failing in Webpack 2. They work separately, but fail when both are included in config file
I have the following in my webpack.config.js file:

```<code>const webpack = require('webpack');
const path = require('path');

const config = {
  context: path.resolve(__dirname, 'src'),
  entry: './app.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        exclude: path.resolve(__dirname, 'node_modules'),
        use: [ 'style-loader', 'css-loader' ]
      },
      {
        test: /\.js$/,
        exclude: path.resolve(__dirname, 'node_modules'),
        use: [{
          loader: 'babel-loader',
          options: {
            presets: [
              ['es2015']
            ]
          }
        }]
      }
    ]
  }
};

module.exports = config;
</code>```

When I run webpack I get the following errors:

```<code>ERROR in (webpack)/~/buffer/index.js
Module build failed: Error: Couldn't find preset "es2015" relative to directory "/home/echessa/node/node-v6.9.1-linux-x64/lib/node_modules/webpack/node_modules/buffer"
    at /home/echessa/Documents/DEV/demo-project/node_modules/babel-core/lib/transformation/file/options/option-manager.js:293:19
    at Array.map (native)
    at OptionManager.resolvePresets (/home/echessa/Documents/DEV/demo-project/node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
    at OptionManager.mergePresets (/home/echessa/Documents/DEV/demo-project/node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
    at OptionManager.mergeOptions (/home/echessa/Documents/DEV/demo-project/node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)
    at OptionManager.init (/home/echessa/Documents/DEV/demo-project/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
    at File.initOptions (/home/echessa/Documents/DEV/demo-project/node_modules/babel-core/lib/transformation/file/index.js:212:65)
    at new File (/home/echessa/Documents/DEV/demo-project/node_modules/babel-core/lib/transformation/file/index.js:135:24)
    at Pipeline.transform (/home/echessa/Documents/DEV/demo-project/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
    at transpile (/home/echessa/Documents/DEV/demo-project/node_modules/babel-loader/lib/index.js:48:20)
    at Object.module.exports (/home/echessa/Documents/DEV/demo-project/node_modules/babel-loader/lib/index.js:163:20)
 @ ../~/css-loader/lib/css-base.js 1:0-117
 @ ../~/css-loader!./main.css
 @ ./main.css
 @ ./app.js
</code>```

I'm using Webpack version 2.3.2.

The following are the dev dependencies I'm using:

```<code>"devDependencies": {
  "babel-core": "^6.24.0",
  "babel-loader": "^7.0.0-beta.1",
  "babel-preset-es2015": "^6.24.0",
  "css-loader": "^0.27.3",
  "style-loader": "^0.16.1"
}
</code>```

For babel-loader, I'm using a beta version because version 7.x is recommended for use with Webpack 2. The following is from the Github repo:

webpack 1.x | babel-loader <= 6.x

webpack 2.x | babel-loader >= 7.x (recommended) (^6.2.10 will also work, but with deprecation warnings)

Version 7.0.0 isn't out yet, so I'm using the beta. I've tried using 6.2.10 but I still get the same bugs.

When I only use one of the rules, webpack builds successfully. E.g. when I only have the js rules (and remove CSS files), it works.

```<code>module: {
  rules: [
    {
      test: /\.js$/,
      exclude: path.resolve(__dirname, 'node_modules'),
      use: [{
        loader: 'babel-loader',
        options: {
          presets: [
            ['es2015']
          ]
        }
      }]
    }
  ]
}
</code>```

Or when I only have the CSS rules (and remove any ES6 code), it works.

```<code>module: {
  rules: [
    {
      test: /\.css$/,
      exclude: path.resolve(__dirname, 'node_modules'),
      use: [ 'style-loader', 'css-loader' ]
    }
  ]
}
</code>```

What could be up? Could it be an issue with babel-loader or is my config file not structured correctly?

答:
I've found a solution that works. If I move the following from the webpack.config.js file to a .babelrc file, then webpack runs fine.

```<code>{
  "presets": ["es2015"]
}
</code>```

I'm not sure why having the presets in the config file wasn't working. Any Webpack 2 guide I've seen online has them in the config file. Anyway, I thought I should leave this solution here in case someone else gets stuck.

Body:
I have the following in my webpack.config.js file:

const webpack = require('webpack');
const path = require('path');

const config = {
  context: path.resolve(__dirname, 'src'),
  entry: './app.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        exclude: path.resolve(__dirname, 'node_modules'),
        use: [ 'style-loader', 'css-loader' ]
      },
      {
        test: /\.js$/,
        exclude: path.resolve(__dirname, 'node_modules'),
        use: [{
          loader: 'babel-loader',
          options: {
            presets: [
              ['es2015']
            ]
          }
        }]
      }
    ]
  }
};

module.exports = config;

When I run webpack I get the following errors:

ERROR in (webpack)/~/buffer/index.js
Module build failed: Error: Couldn't find preset "es2015" relative to directory "/home/echessa/node/node-v6.9.1-linux-x64/lib/node_modules/webpack/node_modules/buffer"
    at /home/echessa/Documents/DEV/demo-project/node_modules/babel-core/lib/transformation/file/options/option-manager.js:293:19
    at Array.map (native)
    at OptionManager.resolvePresets (/home/echessa/Documents/DEV/demo-project/node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
    at OptionManager.mergePresets (/home/echessa/Documents/DEV/demo-project/node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
    at OptionManager.mergeOptions (/home/echessa/Documents/DEV/demo-project/node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)
    at OptionManager.init (/home/echessa/Documents/DEV/demo-project/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
    at File.initOptions (/home/echessa/Documents/DEV/demo-project/node_modules/babel-core/lib/transformation/file/index.js:212:65)
    at new File (/home/echessa/Documents/DEV/demo-project/node_modules/babel-core/lib/transformation/file/index.js:135:24)
    at Pipeline.transform (/home/echessa/Documents/DEV/demo-project/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
    at transpile (/home/echessa/Documents/DEV/demo-project/node_modules/babel-loader/lib/index.js:48:20)
    at Object.module.exports (/home/echessa/Documents/DEV/demo-project/node_modules/babel-loader/lib/index.js:163:20)
 @ ../~/css-loader/lib/css-base.js 1:0-117
 @ ../~/css-loader!./main.css
 @ ./main.css
 @ ./app.js

I'm using Webpack version 2.3.2.

The following are the dev dependencies I'm using:

"devDependencies": {
  "babel-core": "^6.24.0",
  "babel-loader": "^7.0.0-beta.1",
  "babel-preset-es2015": "^6.24.0",
  "css-loader": "^0.27.3",
  "style-loader": "^0.16.1"
}

For babel-loader, I'm using a beta version because version 7.x is recommended for use with Webpack 2. The following is from the Github repo:

webpack 1.x | babel-loader <= 6.x

webpack 2.x | babel-loader >= 7.x (recommended) (^6.2.10 will also work, but with deprecation warnings)

Version 7.0.0 isn't out yet, so I'm using the beta. I've tried using 6.2.10 but I still get the same bugs.

When I only use one of the rules, webpack builds successfully. E.g. when I only have the js rules (and remove CSS files), it works.

module: {
  rules: [
    {
      test: /\.js$/,
      exclude: path.resolve(__dirname, 'node_modules'),
      use: [{
        loader: 'babel-loader',
        options: {
          presets: [
            ['es2015']
          ]
        }
      }]
    }
  ]
}

Or when I only have the CSS rules (and remove any ES6 code), it works.

module: {
  rules: [
    {
      test: /\.css$/,
      exclude: path.resolve(__dirname, 'node_modules'),
      use: [ 'style-loader', 'css-loader' ]
    }
  ]
}

What could be up? Could it be an issue with babel-loader or is my config file not structured correctly?

Body:
I've found a solution that works. If I move the following from the webpack.config.js file to a .babelrc file, then webpack runs fine.

{
  "presets": ["es2015"]
}

I'm not sure why having the presets in the config file wasn't working. Any Webpack 2 guide I've seen online has them in the config file. Anyway, I thought I should leave this solution here in case someone else gets stuck.


来源: stackexchange

问:
Java Recursion Advance
I am trying to write a java program which uses recursion to compute the power tower function. Your function will take as input  three values: base, power, and height. It should then compute something like (((2^2)^2)^2).
I am not getting the right computation, please tell me what is wrong.

This is what I have:

```<code>public double powerTower(double base, int power, int height){

    if (base == 0) {
        return 0;
    } else if (power == 1) {
        return base;
    } else if(height == 1){
        return base * powerTower(base, power - 1, height - 1);
    }else if(power == 0){
        return 1;
    }else {
        return base * powerTower(base, power -1, height-1) * Math.pow(base, height*power);
        //return Math.pow(base, power*height)*base;
    }
}
</code>```

答:
Your description of the "power tower" function is not quite clear. Here I expect that height can never be less than 1 and that

```<code>powerTower(2,3,4) = ((((2^3)^3)^3)^3)
</code>```

i.e. power is replicated height times. I think in this case the simplest solution is to first introduce a helper funciton for just power and then use it to calcualte powerTower

```<code>static double power(double base, int power)
{
    if ((base == 0) || (base == 1))
    {
        return base;
    }
    else if (power == 0)
    {
        return 1.0;
    }
    else if (power == 1)
    {
        return base;
    }
    else
    {
        return base * power(base, power - 1);
    }
}

public static double powerTower(double base, int power, int height)
{
    if (height == 1)
    {
        return power(base, power);
    }
    else
    {
        double newBase = powerTower(base, power, height - 1);
        return power(newBase, power);
    }
}
</code>```

P.S. actually if my understanding of the definition of power-tower is correct than

```<code>powerTower(base, power, height) = base^(power^height)
</code>```

which can be implemented in a simpler way but I expect such implementation is not what is expected from you.

ContentLicense: CC BY-SA 3.0

Title: Java Recursion Advance

Body:
I am trying to write a java program which uses recursion to compute the power tower function. Your function will take as input  three values: base, power, and height. It should then compute something like (((2^2)^2)^2).
I am not getting the right computation, please tell me what is wrong.

This is what I have:

public double powerTower(double base, int power, int height){

    if (base == 0) {
        return 0;
    } else if (power == 1) {
        return base;
    } else if(height == 1){
        return base * powerTower(base, power - 1, height - 1);
    }else if(power == 0){
        return 1;
    }else {
        return base * powerTower(base, power -1, height-1) * Math.pow(base, height*power);
        //return Math.pow(base, power*height)*base;
    }
}

Body:
Your description of the "power tower" function is not quite clear. Here I expect that height can never be less than 1 and that

powerTower(2,3,4) = ((((2^3)^3)^3)^3)

i.e. power is replicated height times. I think in this case the simplest solution is to first introduce a helper funciton for just power and then use it to calcualte powerTower

static double power(double base, int power)
{
    if ((base == 0) || (base == 1))
    {
        return base;
    }
    else if (power == 0)
    {
        return 1.0;
    }
    else if (power == 1)
    {
        return base;
    }
    else
    {
        return base * power(base, power - 1);
    }
}

public static double powerTower(double base, int power, int height)
{
    if (height == 1)
    {
        return power(base, power);
    }
    else
    {
        double newBase = powerTower(base, power, height - 1);
        return power(newBase, power);
    }
}

P.S. actually if my understanding of the definition of power-tower is correct than

powerTower(base, power, height) = base^(power^height)

which can be implemented in a simpler way but I expect such implementation is not what is expected from you.


问:
growing box dont work
I like the left box to grow as the content to the right expand the whole wrapper... i mean vertical scaling.... not horizontal !

reference page

i'm sure it's only a matter of css propriety somewhere... can you help ?

答:
Try to avoid floats, floats are for images and text. People often use floats where absolute positioning is far more appropriate.

Basically what you do is add a margin to your right pane that is about as wide as your left pane. Then absolute position your left pane on top of the right pane and set the height to 100% so it is as high as the container. the container will have the same height as the content.

Here's a sample for you:

```<code><!DOCTYPE HTML>
<html>
  <head>
    <style type="text/css">
      body { width: 800px; margin: 0px auto; position: relative; }

      #nav {
        width: 200px; height: 100%;
        position: absolute; left: 0px; top 0px;
        background: #F00;
      }

      #content {
        margin: 0px 0px 0px 200px;
        heigth: 1000px;
        background: #0F0;
      }
    </style>
  </head>
  <body>
    <div id="nav">
    </div>
    <div id="content">
    </div>
  </body>
</html>
</code>```

ContentLicense: CC BY-SA 2.5

Title: growing box dont work

Body:
Try to avoid floats, floats are for images and text. People often use floats where absolute positioning is far more appropriate.

Basically what you do is add a margin to your right pane that is about as wide as your left pane. Then absolute position your left pane on top of the right pane and set the height to 100% so it is as high as the container. the container will have the same height as the content.

Here's a sample for you:

<!DOCTYPE HTML>
<html>
  <head>
    <style type="text/css">
      body { width: 800px; margin: 0px auto; position: relative; }

      #nav {
        width: 200px; height: 100%;
        position: absolute; left: 0px; top 0px;
        background: #F00;
      }

      #content {
        margin: 0px 0px 0px 200px;
        heigth: 1000px;
        background: #0F0;
      }
    </style>
  </head>
  <body>
    <div id="nav">
    </div>
    <div id="content">
    </div>
  </body>
</html>


问:
What can I use for Android Developement
Hello I'm an informatics apprentice and already learned to program a bit.

In my first year we developed an Android App with Android Studio (Java) and I was thinking this is the only way to create an Android App but then I saw someone creating a game with  Unity (C#).

Now I'm wondering if these 2 options are the only 2 or are there more? And if yes which ones?

答:
I recommend sticking to Android Studio to learn coding in Android. This is due to three reasons:

Android Studio is officially supported by Android, which means they have more documentation and project examples that follow the Android Studio project structure.

Android Studio is good development IDE for both beginners and experts alike.

Android Studio is a PITA to get set up for total beginners, but the learning experience goes a long way.

If you want another platform, better try something like MIT App Inventor (You won't learn much with this) or Xamarin.

Xamarin is also another highly recommended platform that you might want to learn. The main advantage is that it is cross-platform, which will let you code apps for multiple mobile platforms at once.

Title: What can I use for Android Developement


问:
Login issue using password hash and password verify in php
Signup code:

```<code>    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    $contact = $_POST['contact'];
    $address = $_POST['address'];

    $query = "INSERT INTO `tbl_user`(`first_name`, `last_name` , `email` , `password`,`contact`, `address`) VALUES
        ('$first_name','$last_name','$email','$hashed_password','$contact','$address')";
    $sql = mysqli_query($con,$query);
</code>```

Login code :

```<code>    $email = $_POST['email'];
    $password = $_POST['password'];
    $query = "SELECT * FROM `tbl_user` WHERE `email` = '$email'";
    $sql = mysqli_query($con,$query);
    $row = mysqli_fetch_array($sql);
    if (password_verify('$password', $row['hashed_password'])) {
        echo 'Password is valid!';
    } else {
        echo 'Invalid password.';
    }
</code>```

But everytime it is showing Invalid Password even if i enter the correct credentials.

答:
Error: '$password' instead use it as just $password.

Change this to:

```<code>if (password_verify('$password', $row['hashed_password'])) {
</code>```

This:

```<code>if (password_verify($password, $row['hashed_password'])) {
</code>```

Body:
Signup code:

    $first_name = $_POST['first_name'];
    $last_name = $_POST['last_name'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    $contact = $_POST['contact'];
    $address = $_POST['address'];

    $query = "INSERT INTO `tbl_user`(`first_name`, `last_name` , `email` , `password`,`contact`, `address`) VALUES
        ('$first_name','$last_name','$email','$hashed_password','$contact','$address')";
    $sql = mysqli_query($con,$query);

Login code :

    $email = $_POST['email'];
    $password = $_POST['password'];
    $query = "SELECT * FROM `tbl_user` WHERE `email` = '$email'";
    $sql = mysqli_query($con,$query);
    $row = mysqli_fetch_array($sql);
    if (password_verify('$password', $row['hashed_password'])) {
        echo 'Password is valid!';
    } else {
        echo 'Invalid password.';
    }

But everytime it is showing Invalid Password even if i enter the correct credentials.

Body:
Error: '$password' instead use it as just $password.

Change this to:

if (password_verify('$password', $row['hashed_password'])) {

This:

if (password_verify($password, $row['hashed_password'])) {


问:
Why are bit fields not allowed as static data members of a class
Can anyone explain the reason behind not allowing bit fields as static member of a class? For example, a class defined like:

```<code>class A{
public:
    A() {}
    ~A(){}
private:
    static int mem :10;
};
int A::mem;
</code>```

doesn't compile.

Compiling this class with different compilers:-

1- g++ throws error:-

error: static member 'mem' cannot be a bit-field

```<code>static int mem :10;
</code>```

error: ‘int A::mem’ is not a static data member of ‘class A’

int A::mem;

2- clang throws error:-

error: static member 'mem' cannot be a bit-field

```<code>static int mem :10;
</code>```

3-Visual Studio 15 throws error:-

'A::mem'::illegal storage class

'int A::mem':member function redeclaration not allowed

答:
The main reason is because that's what the C++ standard says explicitly:

[class.bit] 12.2.4/3

A bit-field shall not be a static member. A bit-field shall have integral or enumeration type ([basic.fundamental]). A bool value can successfully be stored in a bit-field of any nonzero size. The address-of operator & shall not be applied to a bit-field, so there are no pointers to bit-fields. A non-const reference shall not be bound to a bit-field ([dcl.init.ref]). [ Note: If the initializer for a reference of type const T& is an lvalue that refers to a bit-field, the reference is bound to a temporary initialized to hold the value of the bit-field; the reference is not bound to the bit-field directly. See [dcl.init.ref].  — end note ]

The reasoning for it? Well, bit-fields are a carry-over from C. They are allowed only as struct or union fields there to begin with. Personally, I can't think of a context where a static bit-field member can be useful.

Furthermore, practically everything about bit-fields is implementation defined already, and letting static data behave in a completely implementation defined manner, is IMHO a very bad idea.

Body:
Can anyone explain the reason behind not allowing bit fields as static member of a class? For example, a class defined like:

class A{
public:
    A() {}
    ~A(){}
private:
    static int mem :10;
};
int A::mem;

doesn't compile.

Compiling this class with different compilers:-

1- g++ throws error:-

error: static member 'mem' cannot be a bit-field

static int mem :10;

error: ‘int A::mem’ is not a static data member of ‘class A’

int A::mem;

2- clang throws error:-

error: static member 'mem' cannot be a bit-field

static int mem :10;

3-Visual Studio 15 throws error:-

'A::mem'::illegal storage class

'int A::mem':member function redeclaration not allowed


问:
How to determine a NSInteger is in the NSRange?
For example,a NSInteger 8 ,is in the NSRange (4,10).
I have checked NSRange API and didn't find one method to determine it.

答:
Use NSLocationInRange:

```<code>NSInteger num = 8;
NSRange range = NSMakeRange(4, 10); // 4 - 14
if (NSLocationInRange(num, range)) {
    // num in range
}
</code>```

Body:
Use NSLocationInRange:

NSInteger num = 8;
NSRange range = NSMakeRange(4, 10); // 4 - 14
if (NSLocationInRange(num, range)) {
    // num in range
}


问:
Retrieve file from database using python
I have a column FileContent (datatype image) in the database which store pdf, zip and docx file.

The FileContent column has the following value in database: 0x2550444...

I read the SQL table into DF using python and the values in column FileContent contains weird text instead of the 0x2550444... :

%PDF-1.7\n\n4 0 obj\n(Identity)\nendobj\n5 0 obj(Adobe)endobj8 0 obj> stream xœì½x\ÅÕ7>sïÝÞ«¶hµ»ZíJòªKV³,Õb[’eK²eKVqaÝmlÜ0ÍÑƒ˜NB Á$ÙÆ¢›¼¦…’˜4JpH€ " éæÎcxóþŸïý¾G#Ÿ=¿™;3wæÌ™3gæÞ]#Œ²Ã‡€:Ê›fWÕþ°ã ’ý~+Bž£¥åó_{óÒÕ¿™€õ®ŠÒº²‹U3Â¯ý!E¤ª¼¢rÁ«|ˆ{w!..................................

Is there a way to retrieve the file or convert the text above into a file (e.g. PDF) using python?

Will appreciate your input. Thank you.

My ultimate goal is to:
- retrieve the file from the column FileContent and extract the text within the files later on.

Code:

```<code>import pymssql
conn = pymssql.connect(server="",user="",password="",database="")
stmt = "SELECT FileContent FROM [tablename]"
df = pd.read_sql(stmt,conn)
df.head()
print(df)
</code>```

答:
ASCII codes for '%PDF-1.7\n are '0x25', '0x50', '0x44', '0x46', '0x2d', '0x31', '0x2e', '0x37', '0xa'

So 0x255044462d302e370a is just the ASCII representation of that string. And '%PDF-1.7\n is the preamble of a pdf file. That means that you have correctly extracted the content of a PDF file from the database. You have just to save it to a file with a .pdf extension to be able to use it.

So assuming that the text above is contained in a variable fileContent its conversion to a pdf file is just:

```<code>with open('file.pdf', 'wb') as fd:   # binary mode
    fd.write(fileContent)
</code>```

Body:
I have a column FileContent (datatype image) in the database which store pdf, zip and docx file.

The FileContent column has the following value in database: 0x2550444...

I read the SQL table into DF using python and the values in column FileContent contains weird text instead of the 0x2550444... :

%PDF-1.7\n\n4 0 obj\n(Identity)\nendobj\n5 0 obj(Adobe)endobj8 0 obj> stream xœì½x\ÅÕ7>sïÝÞ«¶hµ»ZíJòªKV³,Õb[’eK²eKVqaÝmlÜ0ÍÑƒ˜NB Á$ÙÆ¢›¼¦…’˜4JpH€ " éæÎcxóþŸïý¾G#Ÿ=¿™;3wæÌ™3gæÞ]#Œ²Ã‡€:Ê›fWÕþ°ã ’ý~+Bž£¥åó_{óÒÕ¿™€õ®ŠÒº²‹U3Â¯ý!E¤ª¼¢rÁ«|ˆ{w!..................................

Is there a way to retrieve the file or convert the text above into a file (e.g. PDF) using python?

Will appreciate your input. Thank you.

My ultimate goal is to:
- retrieve the file from the column FileContent and extract the text within the files later on.

Code:

import pymssql
conn = pymssql.connect(server="",user="",password="",database="")
stmt = "SELECT FileContent FROM [tablename]"
df = pd.read_sql(stmt,conn)
df.head()
print(df)

Body:
ASCII codes for '%PDF-1.7\n are '0x25', '0x50', '0x44', '0x46', '0x2d', '0x31', '0x2e', '0x37', '0xa'

So 0x255044462d302e370a is just the ASCII representation of that string. And '%PDF-1.7\n is the preamble of a pdf file. That means that you have correctly extracted the content of a PDF file from the database. You have just to save it to a file with a .pdf extension to be able to use it.

So assuming that the text above is contained in a variable fileContent its conversion to a pdf file is just:

with open('file.pdf', 'wb') as fd:   # binary mode
    fd.write(fileContent)


问:
Finding patterns in a list of dataframes using R
I have a list L of dataframes where each dataframe consists of the variable Var and one observation that consists of different numbers. Each number in each observation belongs to the set {1,2,3,4,5,11,12,13,14,15}. L could, as an example, look like:

```<code>> L
[[1]]
                   Var
1 "3", "11", "1", "15",

[[2]]
                   Var
1 "5", 13", "3", "12",

[[3]]
                   Var
1 "4", "1", "2", "5",
</code>```

The problem I am trying to solve is the following. I want to know if there is a positive number x = {1,2,3,4,5} such that when added to each number in a given observation, that observation becomes equivalent to another. For example, consider the first 2 elements of L and let x=2, then, adding x to the first element of L yields:

```<code>> L[[1]]
                   Var
1 "5", "13", "3", "17",
</code>```

The number 17 does not meet the conditions of the set defined above. I want the following constraints to apply on x. Let y denote a number in an obs. in a dataframe of L:

```<code>if y + x > 15 then subtract 5
if 5 < y + x < 11 then subtract 5
</code>```

The same example with these constraints would yield:

```<code>> L[[1]]
                   Var
1 "5", "13", "3", "12",
</code>```

And L[[1]] would become equivalent to L[[2]]. In my world, L[[1]] and L[[2]] share the same pattern. What I want to do is to match elements of L based on equivalent (in the sense described above) patterns and sort the groups according to "the number of members". So in the example here I'd like to detect that L[[1]] and L[[2]] are in one group and that this is the group with most members, followed by the next group, that in this example only consists of L[[3]]. I am very new to R and any guidance would be appreciated!

答:
It looks like your "constraints" define a mathematical equivalence relation. That means that your groups are really equivalence classes in the mathematical sense and that you can define a unique representative for each group. If you do this, you can easily check for equivalence (= elements belonging to the same group) by comparing their representatives.

Let's define the representative as the element in your equivalence class that starts with "1", i.e., for each list element we add the integer in 1:5, following your defined constraints, so that the first element equals one. We can do that for every element in your list L and then compare which elements have the same representative.

Implementation in R:

Let's start with your list L:

```<code>L <- list(structure(list(Var = c("3", "11", "1", "15")), .Names = "Var",
                row.names = c(NA, -4L), class = "data.frame"),
        structure(list(Var = c("5", "13", "3", "12")), .Names = "Var",
                row.names = c(NA, -4L), class = "data.frame"),
        structure(list(Var = c("4", "1", "2", "5")), .Names = "Var",
                row.names = c(NA, -4L), class = "data.frame"))
</code>```

First, we simplify the list by converting it into a list of numerical vectors:

```<code>## Simplify list: convert to list of numerical vectors:
L2 <- lapply(L, function(x) as.numeric(x$Var))

> L2
[[1]]
[1]  3 11  1 15

[[2]]
[1]  5 13  3 12

[[3]]
[1] 4 1 2 5
</code>```

Then we define the function to perform the addition, following your constraints and find the representative for each element:

```<code>## Function to implement the addition rules:
addConstant <- function(myVec, constant){
    outVec <- myVec + constant
    outVec <- ifelse(((outVec > 5) & (outVec < 11)) |(outVec > 15),
        outVec - 5, outVec)
}

## Define representative of equivalence class as the one starting with a "1":
representativesList <- lapply(L2, function(myVec) addConstant(myVec, 6 - myVec[1]))

> representativesList
[[1]]
[1]  1 14  4 13

[[2]]
[1]  1 14  4 13

[[3]]
[1] 1 3 4 2
</code>```

Now we can define the groups, in your example there are two groups. We will call them group1 and group2:

```<code>## Define groups: Unique representatives:
groupList <- unique(representativesList)
names(groupList) <- paste0("group", seq(along = groupList))

> groupList
$group1
[1]  1 14  4 13

$group2
[1] 1 3 4 2
</code>```

Lastly, we check which group each observation belongs to:

```<code>## Find group:
groupAffiliationVec <- vapply(representativesList, function(x){
            flagVec <- vapply(groupList, function(y, x) identical(x,y), logical(1), x)
            names(groupList[flagVec])
        }, character(1))

> groupAffiliationVec
[1] "group1" "group1" "group2"
</code>```

We know now that observations 1 and 2 belog to the same group (group1) and that observation 3 belongs to group1. Using table(groupAffiliationVec), you can compute the number of members for each group.

Body:
I have a list L of dataframes where each dataframe consists of the variable Var and one observation that consists of different numbers. Each number in each observation belongs to the set {1,2,3,4,5,11,12,13,14,15}. L could, as an example, look like:

> L
[[1]]
                   Var
1 "3", "11", "1", "15",

[[2]]
                   Var
1 "5", 13", "3", "12",

[[3]]
                   Var
1 "4", "1", "2", "5",

The problem I am trying to solve is the following. I want to know if there is a positive number x = {1,2,3,4,5} such that when added to each number in a given observation, that observation becomes equivalent to another. For example, consider the first 2 elements of L and let x=2, then, adding x to the first element of L yields:

> L[[1]]
                   Var
1 "5", "13", "3", "17",

The number 17 does not meet the conditions of the set defined above. I want the following constraints to apply on x. Let y denote a number in an obs. in a dataframe of L:

if y + x > 15 then subtract 5
if 5 < y + x < 11 then subtract 5

The same example with these constraints would yield:

> L[[1]]
                   Var
1 "5", "13", "3", "12",

And L[[1]] would become equivalent to L[[2]]. In my world, L[[1]] and L[[2]] share the same pattern. What I want to do is to match elements of L based on equivalent (in the sense described above) patterns and sort the groups according to "the number of members". So in the example here I'd like to detect that L[[1]] and L[[2]] are in one group and that this is the group with most members, followed by the next group, that in this example only consists of L[[3]]. I am very new to R and any guidance would be appreciated!

Body:
It looks like your "constraints" define a mathematical equivalence relation. That means that your groups are really equivalence classes in the mathematical sense and that you can define a unique representative for each group. If you do this, you can easily check for equivalence (= elements belonging to the same group) by comparing their representatives.

Let's define the representative as the element in your equivalence class that starts with "1", i.e., for each list element we add the integer in 1:5, following your defined constraints, so that the first element equals one. We can do that for every element in your list L and then compare which elements have the same representative.

Implementation in R:

Let's start with your list L:

L <- list(structure(list(Var = c("3", "11", "1", "15")), .Names = "Var",
                row.names = c(NA, -4L), class = "data.frame"),
        structure(list(Var = c("5", "13", "3", "12")), .Names = "Var",
                row.names = c(NA, -4L), class = "data.frame"),
        structure(list(Var = c("4", "1", "2", "5")), .Names = "Var",
                row.names = c(NA, -4L), class = "data.frame"))

First, we simplify the list by converting it into a list of numerical vectors:

## Simplify list: convert to list of numerical vectors:
L2 <- lapply(L, function(x) as.numeric(x$Var))

> L2
[[1]]
[1]  3 11  1 15

[[2]]
[1]  5 13  3 12

[[3]]
[1] 4 1 2 5

Then we define the function to perform the addition, following your constraints and find the representative for each element:

## Function to implement the addition rules:
addConstant <- function(myVec, constant){
    outVec <- myVec + constant
    outVec <- ifelse(((outVec > 5) & (outVec < 11)) |(outVec > 15),
        outVec - 5, outVec)
}

## Define representative of equivalence class as the one starting with a "1":
representativesList <- lapply(L2, function(myVec) addConstant(myVec, 6 - myVec[1]))

> representativesList
[[1]]
[1]  1 14  4 13

[[2]]
[1]  1 14  4 13

[[3]]
[1] 1 3 4 2

Now we can define the groups, in your example there are two groups. We will call them group1 and group2:

## Define groups: Unique representatives:
groupList <- unique(representativesList)
names(groupList) <- paste0("group", seq(along = groupList))

> groupList
$group1
[1]  1 14  4 13

$group2
[1] 1 3 4 2

Lastly, we check which group each observation belongs to:

## Find group:
groupAffiliationVec <- vapply(representativesList, function(x){
            flagVec <- vapply(groupList, function(y, x) identical(x,y), logical(1), x)
            names(groupList[flagVec])
        }, character(1))

> groupAffiliationVec
[1] "group1" "group1" "group2"

We know now that observations 1 and 2 belog to the same group (group1) and that observation 3 belongs to group1. Using table(groupAffiliationVec), you can compute the number of members for each group.


问:
Not able to install docker-machine in Centos 7
Docker is installed in my Centos 7 machine:

```<code>Client: Version:      17.03.1-ce API version:  1.27
Server:  Version:      17.03.1-ce  API version:  1.27 (minimum version 1.12)
</code>```

But I am not able to install docker-machine. Below is how I try to install it:

```<code>wget https://github.com/docker/machine/releases/download/v0.6.0/docker-machine-$(uname
-s)-$(uname -m)
mv docker-machine-Linux-x86_64 docker-machine
chmod +x docker-machine
sudo mv docker-machine /usr/local/bin
</code>```

And when I check for the docker-machine version,

```<code>docker-machine version
</code>```

I get below error:

```<code>bash: docker-machine: command not found...
</code>```

答:
Try to add the docker-machine to your path as shown here:
Docker Installing bash completion

If not are you able to run /usr/local/bin/docker-machine version

Any errors and full output would be appreciated!

Body:
Docker is installed in my Centos 7 machine:

Client: Version:      17.03.1-ce API version:  1.27
Server:  Version:      17.03.1-ce  API version:  1.27 (minimum version 1.12)

But I am not able to install docker-machine. Below is how I try to install it:

wget https://github.com/docker/machine/releases/download/v0.6.0/docker-machine-$(uname
-s)-$(uname -m)
mv docker-machine-Linux-x86_64 docker-machine
chmod +x docker-machine
sudo mv docker-machine /usr/local/bin

And when I check for the docker-machine version,

docker-machine version

I get below error:

bash: docker-machine: command not found...


问:
How to save a jsoup document as text file
I am trying to save all of the readable words on a web page into one text document while ignoring html markup.
Using JSoup to parse all of the words on a webpage, my only guess of how to seperate the real words from the code is through elements.

Is it possible to convert multiple elements of the jsoup document into a text file?

i.e.:

```<code>        Elements titles = doc.select("title");
        Elements paragraphs = doc.select("p");
        Elements links = doc.select("a[href]");
        Elements smallText = doc.select("a");
</code>```

Currently saving the parse as a document with:

```<code> Document doc = Jsoup.connect("https:// (enter a url)").get();
</code>```

答:
Its simple way</p>

```<code>Document doc = Jsoup.connect("https:// (enter a url)").get();
        BufferedWriter  writer = null;
        try
        {
            writer = new BufferedWriter( new FileWriter("d://test.txt"));
            writer.write(doc.toString());

        }
        catch ( IOException e)
        {
        }
</code>```

Body:
I am trying to save all of the readable words on a web page into one text document while ignoring html markup.
Using JSoup to parse all of the words on a webpage, my only guess of how to seperate the real words from the code is through elements.

Is it possible to convert multiple elements of the jsoup document into a text file?

i.e.:

        Elements titles = doc.select("title");
        Elements paragraphs = doc.select("p");
        Elements links = doc.select("a[href]");
        Elements smallText = doc.select("a");

Currently saving the parse as a document with:

 Document doc = Jsoup.connect("https:// (enter a url)").get();

Body:
Its simple way

Document doc = Jsoup.connect("https:// (enter a url)").get();
        BufferedWriter  writer = null;
        try
        {
            writer = new BufferedWriter( new FileWriter("d://test.txt"));
            writer.write(doc.toString());

        }
        catch ( IOException e)
        {
        }


问:
Angular: Observable model property does not exist
After upgrading from Angular 2 to Angular 4 I get these errors when trying to compile using AOT:

```<code>Property 'total' does not exist on type 'Observable<any>'.
</code>```

This is how I have used observables until now...

First I have assigned a variable like this:

```<code>public myData: Observable<any>;
</code>```

Then I have a call to my service which I subscribe to like this:

```<code>this.mySubscription = this.apiService.get('URL-HERE')
                        .subscribe(
                            response => this.myData = response,
                            error => this.feedbackService.displayError(<any>error),
                            () => this.feedbackService.stopLoading()
                        );
</code>```

This works in development mode (ng serve), and I can use stuff like *ngFor to iterate over the results.

After getting these errors I tried to add a model class like this:

```<code>export class MyData {
    total: number;
    count: number;
    data: Array<any> = [];
}
... rest of component here
</code>```

And then use it with my observable like this:

```<code>public myData: Observable<MyData>;
</code>```

But I still get errors when trying to compile:

```<code>Property 'total' does not exist on type 'Observable<MyData>'.
</code>```

What am I doing wrong?

Update:

This is what the service method looka like:

```<code>return this.http
        .get(apiUrl + apiPath, {headers: headersWithToken})
        .timeoutWith(appSettings.maxTimeHttpCalls, Observable.defer(() => Observable.throw(this.feedbackService.timeout())))
        .map((response: Response) => {
            return response.json();
        })
        .catch((err: Response) => {
            return err.json();
        });
</code>```

All values (including total) exists on the returned JSON and I can use it in my HTML without a problem.

答:
Turns out AOT doesn't like elvis operators in Angular 4.

I kept Observable<any> on all components and wrapped all entries containing stuff like {{myData?.total}} inside an *ngIf check (and removed ?) and the errors went away.

Body:
After upgrading from Angular 2 to Angular 4 I get these errors when trying to compile using AOT:

Property 'total' does not exist on type 'Observable<any>'.

This is how I have used observables until now...

First I have assigned a variable like this:

public myData: Observable<any>;

Then I have a call to my service which I subscribe to like this:

this.mySubscription = this.apiService.get('URL-HERE')
                        .subscribe(
                            response => this.myData = response,
                            error => this.feedbackService.displayError(<any>error),
                            () => this.feedbackService.stopLoading()
                        );

This works in development mode (ng serve), and I can use stuff like *ngFor to iterate over the results.

After getting these errors I tried to add a model class like this:

export class MyData {
    total: number;
    count: number;
    data: Array<any> = [];
}
... rest of component here

And then use it with my observable like this:

public myData: Observable<MyData>;

But I still get errors when trying to compile:

Property 'total' does not exist on type 'Observable<MyData>'.

What am I doing wrong?

Update:

This is what the service method looka like:

return this.http
        .get(apiUrl + apiPath, {headers: headersWithToken})
        .timeoutWith(appSettings.maxTimeHttpCalls, Observable.defer(() => Observable.throw(this.feedbackService.timeout())))
        .map((response: Response) => {
            return response.json();
        })
        .catch((err: Response) => {
            return err.json();
        });

All values (including total) exists on the returned JSON and I can use it in my HTML without a problem.


问:
redirect url using javascript/jquery (mobile)
I have a problem here: I'm trying out to redirect my ulr to a specific url when a user gets log out(in a form). the problem is that this url: http:champions2017/ have a form to log in and works perfecly well, but whenever a user clicks on log out button, my site redirects the url to http:champions2017/auth/logout where the session is destroyed, and the same log in form is displayed and here the problem comes out, here the user is unable to log in again, so I'm asking if there is a way to redirect to http:champions2017/ once the session is destoyed. I know I can use location.href or a header(location) in php but no, I already did something like this: https://api.jquerymobile.com/navigate/ but no.

答:
For redirect the page you can to use jQuery:

window.location.href="http:champions2017/";

window.location.replace("http:champions2017/");

You also can create fn() and call them as require.


问:
How can i make drop-down list using multiple attribute in HTML
I am trying use multiple attributes where I make the dropdown list, however it is working but default browser changing. Is there any way I can make it drop-down. Please see the code..

```<code>    <select name="cars" multiple>
       <option value="volvo">Volvo</option>
       <option value="saab">Saab</option>
       <option value="opel">Opel</option>
       <option value="audi">Audi</option>
    </select>
</code>```

But if I remove multiple attribute, I can see only drop-down list. Why is it showing different HTML control when I use multiple. I circled correct control with blue that's how I want to use multiple. Is there any suggestion or any ideas.

答:
try Bootstrap Multiselect JS library :

http://davidstutz.github.io/bootstrap-multiselect/

Body:
I am trying use multiple attributes where I make the dropdown list, however it is working but default browser changing. Is there any way I can make it drop-down. Please see the code..

    <select name="cars" multiple>
       <option value="volvo">Volvo</option>
       <option value="saab">Saab</option>
       <option value="opel">Opel</option>
       <option value="audi">Audi</option>
    </select>

But if I remove multiple attribute, I can see only drop-down list. Why is it showing different HTML control when I use multiple. I circled correct control with blue that's how I want to use multiple. Is there any suggestion or any ideas.


问:
Javascript factory function not working properly
according to the tutorial i'm watching this code is supposed to return "John Doe." Presently, it only returns "[object, Object]", what am I doing wrong?

```<code><p id="para"></p>

function createPerson(firstName, lastName) {
    return {
        firstName: firstName,
        lastName: lastName,
        getFullName: function() {
            return this.firstName + " " + this.lastName;
        }
    };
}

var person = createPerson("John", "Doe");

document.getElementById("para").innerHTML = person;
</code>```

Any thoughts?

答:
Object key function was missing .you are only post with object not mention with function in object .So mention the function name of object key.

like this

```<code> 1. person.getFullName();// for function call
 2. person.firstName
 3. person.lastName
</code>```

For more understanding refer this article

function createPerson(firstName, lastName) {
  return {
    firstName: firstName,
    lastName: lastName,
    getFullName: function() {
      return this.firstName + " " + this.lastName;
    }
  };
}

var person = createPerson("John", "Doe");

document.getElementById("para").innerHTML = person.getFullName();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="para"></p></code>```

Body:
according to the tutorial i'm watching this code is supposed to return "John Doe." Presently, it only returns "[object, Object]", what am I doing wrong?

function createPerson(firstName, lastName) {
    return {
        firstName: firstName,
        lastName: lastName,
        getFullName: function() {
            return this.firstName + " " + this.lastName;
        }
    };
}

var person = createPerson("John", "Doe");

document.getElementById("para").innerHTML = person;

Any thoughts?

Body:
Object key function was missing .you are only post with object not mention with function in object .So mention the function name of object key.

like this

 1. person.getFullName();// for function call
 2. person.firstName
 3. person.lastName

For more understanding refer this article

function createPerson(firstName, lastName) {
  return {
    firstName: firstName,
    lastName: lastName,
    getFullName: function() {
      return this.firstName + " " + this.lastName;
    }
  };
}

var person = createPerson("John", "Doe");

document.getElementById("para").innerHTML = person.getFullName();

<p id="para"></p>


问:
Accessing localhost (xampp) from another computer over LAN network - how to?
I have just set up a wi-fi network at home. I have all my files on my desktop computer (192.168.1.56) and want to access localhost over there from another computer (192.168.1.2).

On my desktop I can access localhost through the normal http://localhost. Apache is running on port 80 as usual.

What do I have to do to achieve this? There is documentation on the net but they either don't work or are too fragmented and confusing to understand.

I think I have to make changes to my apache's httpd.conf file and the hosts file. Any ideas as to what changes to make?

答:
Go to xampp-control in the Taskbar

```<code>xampp-control -> Apache --> Config --> httpd.conf
</code>```

Notepad will open with the config file

Search for

Listen 80

One line above it, there will be something like this: 12.34.56:80

Change it

```<code>12.34.56:80 --> <your_ip_address eg:192.168.1.5>:80
</code>```

Restart the apache service and check it,
Hopefully it should work...

ContentLicense: CC BY-SA 4.0

Body:
Go to xampp-control in the Taskbar

xampp-control -> Apache --> Config --> httpd.conf

Notepad will open with the config file

Search for

Listen 80

One line above it, there will be something like this: 12.34.56:80

Change it

12.34.56:80 --> <your_ip_address eg:192.168.1.5>:80

Restart the apache service and check it,
Hopefully it should work...


问:
PostgreSQL 9.6.1 Add new entry to pg_ts_config
Currently the below query gives me only one result, I need english to be included as well.

```<code> select * from pg_ts_config;
"simple";11;10;3722
</code>```

I also need English in the list to create a full text search on a table.

答:
This is a limitation from google cloud SQl for Postgres Beta release. More TEXT SEARCH CONFIGURATIONS are awaited in coming releases.
https://groups.google.com/forum/#!topic/google-cloud-sql-discuss/oK6aWw2nHOo</p>

Body:
Currently the below query gives me only one result, I need english to be included as well.

 select * from pg_ts_config;
"simple";11;10;3722

I also need English in the list to create a full text search on a table.


问:
Django Content-Type : Checking if a field is declared as Many-to-Many field
I checking few field names passed by the APIs from the browser and validating them before passing to Django ORM queries.

The question is for a given mode and given field name, how can I determine if the field is declared as Many-to-Many field using the Content-Type framework?

答:
You might not require content-type for this to be precise. If you already have the model or an instance handy, you would get the list of m2m fields as below

```<code>m2m_fields = [field.name for field in _object._meta.many_to_many]
</code>```

If you are after just the field name a.k.a concrete fields use as below

```<code>fields = [field.name for field in _object._meta.concrete_fields ]
</code>```

Body:
You might not require content-type for this to be precise. If you already have the model or an instance handy, you would get the list of m2m fields as below

m2m_fields = [field.name for field in _object._meta.many_to_many]

If you are after just the field name a.k.a concrete fields use as below

fields = [field.name for field in _object._meta.concrete_fields ]


问:
getting my divs to flow horizontally
Regardless of what I've tried, I cannot get my inner divs to flow horizonatally within the outer div. Please help!!!</p>

```<code><style type="text/css">

#gallery {
width: 688px;
height: 360px;
border: solid;
}

#galleryelements {
width: 650px;
height: 320px;
display:inline;
background-color:#0FF;
}

.s-thumbnail {
width: 50px;
height: 75px;
border: solid;
}

.thumbnail {
width: 100px;
height: 150px;
border: solid;
}

#left {
float:left;
}

#right {
float:right;
}

#Mimage {
width: 200px;
height: 300px;
border: solid;
}
</style>

<body>
<div id="gallery">
<div id="galleryelements">
<div class="s-thumbnail" id="left"></div>
<div class="thumbnail" id="left"></div>
<div id="Mimage"></div>
<div class="thumbnail" id="right"></div>
<div class="s-thumbnail" id="right"></div>
</div>
</div>
</body>
</html>
</code>```

答:
It would appear that you have your classes and id's mixed up.  You are re-using the left and right ids.  You probably want a float on Mimage too to make it display horizontally.

I changed your code slightly, is this what the result should look like?

http://jsfiddle.net/WcEAb/1/

Title: getting my divs to flow horizontally


问:
How to get individual values from JSON object
I'm using PubNub API in android to fetch real time data but I need some particular value instead of whole. How can I get value for example c7 & c9. I want them to plot a real time graph.

```<code> @Override
        public void message(PubNub pubnub, PNMessageResult message) {
            System.out.println(message);
        }
</code>```

The result I'm getting :-

PNMessageResult (message={"c1":27,"c2":3,"c3":2017,"c4":15,"c5":56,"c6":52,"c7":15.07,"c8":"P&Q","c9":24.86,"c10":82,"c11":32.74}`

答:
Your JSON message contains int, double and string values. You need to use Iterator to get all KEY(c1, c2...c11) and also need to check its type(int, double, string). Finally use Key(c7, c9..) values as per you needs.

Here is an working code. Try this:

```<code>public void parseJson() {

    // Your PNMessageResult JSON string
    // {"c1":27,"c2":3,"c3":2017,"c4":15,"c5":56,"c6":52,"c7":15.07,"c8":"P&Q","c9":24.86,"c10":82,"c11":32.74}
    String jsonStr = "{\"c1\":27,\"c2\":3,\"c3\":2017,\"c4\":15,\"c5\":56,\"c6\":52,\"c7\":15.07,\"c8\":\"P&Q\",\"c9\":24.86,\"c10\":82,\"c11\":32.74}";

    if (jsonStr != null) {

        try {
            JSONObject jsonObj = new JSONObject(jsonStr);

            // Keys: c1, c2, c3.....c11
            Iterator<String> keys = jsonObj.keys();

            while(keys.hasNext()) {

                String key = keys.next();

                Object object = jsonObj.get(key);

                if (object instanceof Integer || object instanceof Long) {
                    long valueLong = ((Number)object).longValue();
                    Log.d("SUCCESS", "Int value: " + valueLong + "\n" + key + ": " + valueLong);

                    // Do something with value
                } else if (object instanceof Float || object instanceof Double) {
                    double valueDouble = ((Number)object).doubleValue();
                    Log.d("SUCCESS", "Double value: " + valueDouble + "\n" + key + ": " + valueDouble);

                    // Do something with value
                } else if (JSONObject.NULL.equals(object)) {
                    Object valueNull = null;

                    // Do something with value
                } else {
                    String valueString = jsonObj.getString(key);
                    Log.d("SUCCESS", "String value: " + valueString + "\n" + key + ": " + valueString);

                    // Do something with value
                }

            }
        } catch (final JSONException e) {
            Log.e("FAILED", "Json parsing error: " + e.getMessage());
        }
    }
}
</code>```

Here is the output:

```<code>03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/MESSAGE: PNMessage: {"c1":27,"c2":3,"c3":2017,"c4":15,"c5":56,"c6":52,"c7":15.07,"c8":"P&Q","c9":24.86,"c10":82,"c11":32.74}
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Int value: 27
                                                                         c1: 27
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Int value: 3
                                                                         c2: 3
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Int value: 2017
                                                                         c3: 2017
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Int value: 15
                                                                         c4: 15
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Int value: 56
                                                                         c5: 56
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Int value: 52
                                                                         c6: 52
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Double value: 15.07
                                                                         c7: 15.07
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: String value: P&Q
                                                                         c8: P&Q
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Double value: 24.86
                                                                         c9: 24.86
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Int value: 82
                                                                         c10: 82
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Double value: 32.74
                                                                         c11: 32.74
</code>```

Hope this will help~

Body:
I'm using PubNub API in android to fetch real time data but I need some particular value instead of whole. How can I get value for example c7 & c9. I want them to plot a real time graph.

 @Override
        public void message(PubNub pubnub, PNMessageResult message) {
            System.out.println(message);
        }

The result I'm getting :-

PNMessageResult (message={"c1":27,"c2":3,"c3":2017,"c4":15,"c5":56,"c6":52,"c7":15.07,"c8":"P&Q","c9":24.86,"c10":82,"c11":32.74}`

Body:
Your JSON message contains int, double and string values. You need to use Iterator to get all KEY(c1, c2...c11) and also need to check its type(int, double, string). Finally use Key(c7, c9..) values as per you needs.

Here is an working code. Try this:

public void parseJson() {

    // Your PNMessageResult JSON string
    // {"c1":27,"c2":3,"c3":2017,"c4":15,"c5":56,"c6":52,"c7":15.07,"c8":"P&Q","c9":24.86,"c10":82,"c11":32.74}
    String jsonStr = "{\"c1\":27,\"c2\":3,\"c3\":2017,\"c4\":15,\"c5\":56,\"c6\":52,\"c7\":15.07,\"c8\":\"P&Q\",\"c9\":24.86,\"c10\":82,\"c11\":32.74}";

    if (jsonStr != null) {

        try {
            JSONObject jsonObj = new JSONObject(jsonStr);

            // Keys: c1, c2, c3.....c11
            Iterator<String> keys = jsonObj.keys();

            while(keys.hasNext()) {

                String key = keys.next();

                Object object = jsonObj.get(key);

                if (object instanceof Integer || object instanceof Long) {
                    long valueLong = ((Number)object).longValue();
                    Log.d("SUCCESS", "Int value: " + valueLong + "\n" + key + ": " + valueLong);

                    // Do something with value
                } else if (object instanceof Float || object instanceof Double) {
                    double valueDouble = ((Number)object).doubleValue();
                    Log.d("SUCCESS", "Double value: " + valueDouble + "\n" + key + ": " + valueDouble);

                    // Do something with value
                } else if (JSONObject.NULL.equals(object)) {
                    Object valueNull = null;

                    // Do something with value
                } else {
                    String valueString = jsonObj.getString(key);
                    Log.d("SUCCESS", "String value: " + valueString + "\n" + key + ": " + valueString);

                    // Do something with value
                }

            }
        } catch (final JSONException e) {
            Log.e("FAILED", "Json parsing error: " + e.getMessage());
        }
    }
}

Here is the output:

03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/MESSAGE: PNMessage: {"c1":27,"c2":3,"c3":2017,"c4":15,"c5":56,"c6":52,"c7":15.07,"c8":"P&Q","c9":24.86,"c10":82,"c11":32.74}
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Int value: 27
                                                                         c1: 27
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Int value: 3
                                                                         c2: 3
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Int value: 2017
                                                                         c3: 2017
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Int value: 15
                                                                         c4: 15
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Int value: 56
                                                                         c5: 56
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Int value: 52
                                                                         c6: 52
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Double value: 15.07
                                                                         c7: 15.07
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: String value: P&Q
                                                                         c8: P&Q
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Double value: 24.86
                                                                         c9: 24.86
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Int value: 82
                                                                         c10: 82
03-29 12:15:26.848 12536-12536/com.ferdous.collapsibletoolbar D/SUCCESS: Double value: 32.74
                                                                         c11: 32.74

Hope this will help~


问:
How to create inshorts like notifications for android
How to create inshorts like push notifications for andriod. The notifications include full image with text at the bottom of the notification.

The small notification is just the text but while u expand it, it shows the image in background with text at bottom.

Can some one please help me with this. Below are the screenshots

答:
You need to inflate a custom remote view as a layout for the notification as follows :

layout_custom_notification.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/image_news"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@mipmap/dine_main_item_bg1" />

    <TextView
        android:id="@+id/tv_news_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp"
        android:layout_toLeftOf="@+id/tv_news_time"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:text="Trump signs order to roll back Obama-era climate policies"
        android:textColor="@android:color/white"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/tv_news_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="20dp"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:text="9:14 AM"
        android:textColor="@android:color/white"
        android:textSize="16sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginTop="20dp"
        android:padding="8dp"
        android:text="Share"
        android:textColor="@android:color/white"
        android:textSize="16sp" />

</RelativeLayout>
</code>```

Thereafter, set this layout as a contentview in notification as follows :

```<code>RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.layout_custom_notification);
        contentView.setImageViewResource(R.id.image_news, R.drawable.ic_launcher);
        contentView.setTextViewText(R.id.tv_news_time, "9:14 AM");
        contentView.setTextViewText(R.id.tv_news_title, "Trump signs order to roll back Obama-era climate policies");

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(icon)
            .setContent(contentView)
            .setContentTitle("Custom Notification")
            .setContentIntent(contentIntent)
            .setWhen(when);

...
mNotificationManager.notify(1, notificationBuilder.build());
</code>```

Body:
You need to inflate a custom remote view as a layout for the notification as follows :

layout_custom_notification.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/image_news"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@mipmap/dine_main_item_bg1" />

    <TextView
        android:id="@+id/tv_news_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp"
        android:layout_toLeftOf="@+id/tv_news_time"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:text="Trump signs order to roll back Obama-era climate policies"
        android:textColor="@android:color/white"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/tv_news_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="20dp"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:text="9:14 AM"
        android:textColor="@android:color/white"
        android:textSize="16sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginTop="20dp"
        android:padding="8dp"
        android:text="Share"
        android:textColor="@android:color/white"
        android:textSize="16sp" />

</RelativeLayout>

Thereafter, set this layout as a contentview in notification as follows :

RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.layout_custom_notification);
        contentView.setImageViewResource(R.id.image_news, R.drawable.ic_launcher);
        contentView.setTextViewText(R.id.tv_news_time, "9:14 AM");
        contentView.setTextViewText(R.id.tv_news_title, "Trump signs order to roll back Obama-era climate policies");

        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(icon)
            .setContent(contentView)
            .setContentTitle("Custom Notification")
            .setContentIntent(contentIntent)
            .setWhen(when);

...
mNotificationManager.notify(1, notificationBuilder.build());


问:
What can be used instead of tree.dataProvider in adobe flex?
I have my .mxml as below:

```<code>  <fx:Declarations>
    <fx:XMLList id="data">
        <node>
            <node label="Inbox">
                <node label="Marketing"/>
                <node label="Product Management"/>
                <node label="Personal"/>
            </node>
            <node label="Outbox">
                <node label="Professional"/>
                <node label="Private"/>
            </node>
            <node label="Spam">kushal</node>
            <node label="Sent"/>
        </node>
    </fx:XMLList>
</fx:Declarations>

<mx:VBox>
    <mx:Button label="Search by name" click="findByName()" />

    <mx:Tree id="tree" width="500" height="500"
             showRoot="false" dataProvider="{data}"
             labelField="@label" />
</mx:VBox>
</code>```

I'm trying to click     findByName()  on click of a button:
which is:

```<code>private function findByName():void
    {

        var mixml:XMLList = new XMLList(data);

        var searchStr:String = "Outbox";
        //child.expandChildrenOf(myXML[0], false);

        //mixml=data;

        searchResult= mixml.node.(@label==searchStr);

        var xn:XML = searchResult[searchResultIndex];
        Alert.show("xn"+ xn);

            searchResultIndex = 0;
        if (searchResult[searchResultIndex] != undefined)

            var xmlNode:XML = searchResult[searchResultIndex];

        while (xmlNode.parent() != null) {

            Alert.show("xmlNodeBefore"+ xmlNode);
            xmlNode = xmlNode.parent();

            Alert.show("xmlNodeAfter"+ xmlNode);

            //checkpoint 1

            tree.expandItem(xmlNode, true, false);
            tree.selectedItem = searchResult[searchResultIndex];

            Alert.show(" tree.selectedItem " + tree.selectedItem );
        }
    }
</code>```

If here instead of    data
I use      tree.dataProvider then this code doesn't work, can somebody tell me why?

答:
Your code does not work when you use tree.dataProvider because it's of the type XMLListCollection, which is a wrapper on top of the XMLList object. Flex internally transforms the XMLList into a XMLListCollection, because XMLListCollection has capabilities of providing change notifications via events, which XMLList does not.

So in your code, if you use tree.dataProvider at the following line :

```<code>var mixml:XMLList = new XMLList(tree.dataProvider);
</code>```

You are actually trying to type cast and convert an XMLListCollection into a XMLList, which is why it does not work.

Interestingly, the XMLListCollection has public properties (like most collections in Flex) which can be used to access the underlying XMLList source from which it is made up of. So, to access the data from the tree, one correct way would be:

```<code>var mixml:XMLList = new XMLList(tree.dataProvider.source);
</code>```

I have tried this in your code and it seems to do the same job as your above code.

You can read more about this here :

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/collections/XMLListCollection.html#source

Hope this explanation works and it answers your question overall.

Cheers.

Body:
I have my .mxml as below:

  <fx:Declarations>
    <fx:XMLList id="data">
        <node>
            <node label="Inbox">
                <node label="Marketing"/>
                <node label="Product Management"/>
                <node label="Personal"/>
            </node>
            <node label="Outbox">
                <node label="Professional"/>
                <node label="Private"/>
            </node>
            <node label="Spam">kushal</node>
            <node label="Sent"/>
        </node>
    </fx:XMLList>
</fx:Declarations>

<mx:VBox>
    <mx:Button label="Search by name" click="findByName()" />

    <mx:Tree id="tree" width="500" height="500"
             showRoot="false" dataProvider="{data}"
             labelField="@label" />
</mx:VBox>

I'm trying to click     findByName()  on click of a button:
which is:

private function findByName():void
    {

        var mixml:XMLList = new XMLList(data);

        var searchStr:String = "Outbox";
        //child.expandChildrenOf(myXML[0], false);

        //mixml=data;

        searchResult= mixml.node.(@label==searchStr);

        var xn:XML = searchResult[searchResultIndex];
        Alert.show("xn"+ xn);

            searchResultIndex = 0;
        if (searchResult[searchResultIndex] != undefined)

            var xmlNode:XML = searchResult[searchResultIndex];

        while (xmlNode.parent() != null) {

            Alert.show("xmlNodeBefore"+ xmlNode);
            xmlNode = xmlNode.parent();

            Alert.show("xmlNodeAfter"+ xmlNode);

            //checkpoint 1

            tree.expandItem(xmlNode, true, false);
            tree.selectedItem = searchResult[searchResultIndex];

            Alert.show(" tree.selectedItem " + tree.selectedItem );
        }
    }

If here instead of    data
I use      tree.dataProvider then this code doesn't work, can somebody tell me why?

Body:
Your code does not work when you use tree.dataProvider because it's of the type XMLListCollection, which is a wrapper on top of the XMLList object. Flex internally transforms the XMLList into a XMLListCollection, because XMLListCollection has capabilities of providing change notifications via events, which XMLList does not.

So in your code, if you use tree.dataProvider at the following line :

var mixml:XMLList = new XMLList(tree.dataProvider);

You are actually trying to type cast and convert an XMLListCollection into a XMLList, which is why it does not work.

Interestingly, the XMLListCollection has public properties (like most collections in Flex) which can be used to access the underlying XMLList source from which it is made up of. So, to access the data from the tree, one correct way would be:

var mixml:XMLList = new XMLList(tree.dataProvider.source);

I have tried this in your code and it seems to do the same job as your above code.

You can read more about this here :

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/collections/XMLListCollection.html#source

Hope this explanation works and it answers your question overall.

Cheers.


问:
Binding to Self/'this' in XAML
Simple WPF/XAML question. In XAML, how do I reference the Self/this object in a given context? In a very basic app with a main window, one control, and a coded C# property of the window, I want to bind a property of the control to the hand coded property of the window.

In code, this is very easy - in the Window's constructor, I added this:

```<code>Binding bind = new Binding();
bind.Source = this;
bind.Path = new PropertyPath("ButtonWidth");
button1.SetBinding(WidthProperty, bind);
</code>```

Obviously, I have a property called ButtonWidth, and a control called button1. I can't figure out how to do this in XAML. Various attempts like the following example have not worked:

```<code><Button x:Name="button1" Width="{Binding Source=Self Path=ButtonWidth}"/>

<Button x:Name="button1" Width="{Binding RelativeSource={RelativeSource Self} Path=ButtonWidth}"/>
</code>```

etc

Thanks

答:
One way I get around having to deal with RelativeSource and the like is to name the root XAML element:

```<code><Window x:Class="TestApp2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    x:Name="_this"
    >
    <Grid>
        <Button x:Name="button" Width="{Binding ElementName=_this,Path=ButtonWidth}" />
    </Grid>
</Window>
</code>```

If you want to set the DataContext you could also do this:

```<code><Window x:Class="TestApp2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    x:Name="_this"
    >
    <Grid DataContext="{Binding ElementName=_this}">
        <Button x:Name="button" Width="{Binding Path=ButtonWidth}" />
    </Grid>
</Window>
</code>```

I find this to be a good trick to not have to remember all the complexities of the RelativeSource binding.

Title: Binding to Self/'this' in XAML

Body:
Simple WPF/XAML question. In XAML, how do I reference the Self/this object in a given context? In a very basic app with a main window, one control, and a coded C# property of the window, I want to bind a property of the control to the hand coded property of the window.

In code, this is very easy - in the Window's constructor, I added this:

Binding bind = new Binding();
bind.Source = this;
bind.Path = new PropertyPath("ButtonWidth");
button1.SetBinding(WidthProperty, bind);

Obviously, I have a property called ButtonWidth, and a control called button1. I can't figure out how to do this in XAML. Various attempts like the following example have not worked:

<Button x:Name="button1" Width="{Binding Source=Self Path=ButtonWidth}"/>

<Button x:Name="button1" Width="{Binding RelativeSource={RelativeSource Self} Path=ButtonWidth}"/>

etc

Thanks

Body:
One way I get around having to deal with RelativeSource and the like is to name the root XAML element:

<Window x:Class="TestApp2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    x:Name="_this"
    >
    <Grid>
        <Button x:Name="button" Width="{Binding ElementName=_this,Path=ButtonWidth}" />
    </Grid>
</Window>

If you want to set the DataContext you could also do this:

<Window x:Class="TestApp2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    x:Name="_this"
    >
    <Grid DataContext="{Binding ElementName=_this}">
        <Button x:Name="button" Width="{Binding Path=ButtonWidth}" />
    </Grid>
</Window>

I find this to be a good trick to not have to remember all the complexities of the RelativeSource binding.


问:
Xamarin Image Grid from Folder
I am trying to display an Image Grid with Text. Using Images from a Folder. I have tries various approaches and tutorials with no success. I have both READ and WRITE permissions for the Internal and External Storage. Whenever I debug the application all I get is a blank screen. I have tried setting a breakpoint on the Adapters GetView() method which never gets hit.

Here is my MainActivity OnCreate() method:

```<code>protected override void OnCreate(Bundle bundle)
{
    if (!_dir.Exists()) { _dir.Mkdir(); }

    base.OnCreate(bundle);
    SetContentView(R.Layout.Main);

    string[] FilePath = null;
    string[] FileName = null;

    if (_dir.IsDirectory)
    {
        DroidIO.File[] imageList = _dir.ListFiles();
        FilePath = new string[imageList.Length];
        FileName = new string[imageList.Length];

        for (int i = 0; i < imageList.Length; i++)
        {
            FilePath[i] = imageList[i].AbsolutePath;
            FileName[i] = imageList[i].Name;
        }
    }

    var gvImageList = FindViewById<GridView>(R.Id.gvImageList);
    gvImageList.SetAdapter(new ImagesFromFolderAdapter(this, FilePath, FileName));
    gvImageList.ItemClick += delegate { gvImageList_ItemClick(); };
}
</code>```

And my Image Adapter Class:

```<code>public class ImagesFromFolderAdapter : BaseAdapter
{
    private Activity context;
    private string[] filePath;
    private string[] fileName;

    public  ImagesFromFolderAdapter(Activity c, string[] fp, string[] fn)
    {
        this.context = c;
        this.fileName = fn;
        this.filePath = fp;
    }

    public override int Count { get; }

    public int GetCount()
    {
        return filePath.Length;
    }

    public override Java.Lang.Object GetItem(int position)
    {
        return position;
    }

    public override long GetItemId(int position)
    {
        return position;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        View view = convertView;
        if (view == null)
            view = context.LayoutInflater.Inflate(R.Layout.gallery_item_layout, null);

        view.FindViewById<ImageView>(R.Id.gitemImage).SetImageBitmap(BitmapFactory.DecodeFile(filePath[position]));
        view.FindViewById<TextView>(R.Id.gitemText).Text = fileName[position];

        return view;

    }
}
</code>```

Any ideas where I am going wrong? I am currently using an LG G3 as a debug device if this helps. Thankyou for any help in advance.

答:
You returned a zero count for your grid adapter.

Change

public override int Count { get; }

To

```<code> public override int Count
 {
      get { return filePath.Length; }
 }
</code>```

Title: Xamarin Image Grid from Folder

Body:
I am trying to display an Image Grid with Text. Using Images from a Folder. I have tries various approaches and tutorials with no success. I have both READ and WRITE permissions for the Internal and External Storage. Whenever I debug the application all I get is a blank screen. I have tried setting a breakpoint on the Adapters GetView() method which never gets hit.

Here is my MainActivity OnCreate() method:

protected override void OnCreate(Bundle bundle)
{
    if (!_dir.Exists()) { _dir.Mkdir(); }

    base.OnCreate(bundle);
    SetContentView(R.Layout.Main);

    string[] FilePath = null;
    string[] FileName = null;

    if (_dir.IsDirectory)
    {
        DroidIO.File[] imageList = _dir.ListFiles();
        FilePath = new string[imageList.Length];
        FileName = new string[imageList.Length];

        for (int i = 0; i < imageList.Length; i++)
        {
            FilePath[i] = imageList[i].AbsolutePath;
            FileName[i] = imageList[i].Name;
        }
    }

    var gvImageList = FindViewById<GridView>(R.Id.gvImageList);
    gvImageList.SetAdapter(new ImagesFromFolderAdapter(this, FilePath, FileName));
    gvImageList.ItemClick += delegate { gvImageList_ItemClick(); };
}

And my Image Adapter Class:

public class ImagesFromFolderAdapter : BaseAdapter
{
    private Activity context;
    private string[] filePath;
    private string[] fileName;

    public  ImagesFromFolderAdapter(Activity c, string[] fp, string[] fn)
    {
        this.context = c;
        this.fileName = fn;
        this.filePath = fp;
    }

    public override int Count { get; }

    public int GetCount()
    {
        return filePath.Length;
    }

    public override Java.Lang.Object GetItem(int position)
    {
        return position;
    }

    public override long GetItemId(int position)
    {
        return position;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        View view = convertView;
        if (view == null)
            view = context.LayoutInflater.Inflate(R.Layout.gallery_item_layout, null);

        view.FindViewById<ImageView>(R.Id.gitemImage).SetImageBitmap(BitmapFactory.DecodeFile(filePath[position]));
        view.FindViewById<TextView>(R.Id.gitemText).Text = fileName[position];

        return view;

    }
}

Any ideas where I am going wrong? I am currently using an LG G3 as a debug device if this helps. Thankyou for any help in advance.

Body:
You returned a zero count for your grid adapter.

Change

public override int Count { get; }

To

 public override int Count
 {
      get { return filePath.Length; }
 }


问:
Cassandra query failure (Tombstones)
So this is driving me crazy. i tried querying one of my table in Cassandra and it showed query failure. i tried digging dip in to the reason behind it and found that it was because of tombstone. i changed GC_GRACE_SECONDS to Zero and triggered Compaction using nodetool, And when i queried again it worked fine. however on a subsequent calls query failed again with a same reason. i am using cassandra-nodejs driver.
This is my data model.

```<code>CREATE TABLE my_table (
    firstname text,
    lastname text,
    email text,
    mobile text,
    date timeuuid,
    value float,
    PRIMARY KEY (firstname, lastname, email, mobile)
) WITH CLUSTERING ORDER BY (lastname ASC, email ASC, mobile ASC);
</code>```

this is the query i want to perform on that data model.

```<code>SELECT firstname, email, toDate(date) as date, mobile, value FROM my_table  WHERE date >= minTimeuuid('2017-03-25 00:00:00+0000') AND date <= minTimeuuid('2017-03-28 23:59:59+0000') ALLOW FILTERING;
</code>```

the result will have approx 40k rows.
this shows that if we delete something it will be marked as tombstone and will get deleted After GC_GRACE_SECONDS setted for given table. If i understand it correctly then.

how come there be tombstone problem when i never delete any row of table?

Is that true a row will be marked as Tombstone if and only if we delete a row?

clearing tombstones and then querying the same works sometimes and sometimes it does not, why is so?.

is it a good idea to increase tombstone_failure_threshold value? (single node cluster application)

I am using cassandra 3.5, with cqlsh version 5.0.1. And the query works fine with terminal, but gives error when we execute using external client (express app using nodejs driver for cassandra). i have a single node cluster app.

EDIT 1

This is the log of my Inserted null value in field (i inserted only name and timestamp);

```<code>  activity                                                                                | timestamp                  | source        | source_elapsed
-------------------------------------------------------------------------------------------------+----------------------------+---------------+----------------
                                                                              Execute CQL3 query | 2017-03-29 10:28:27.342000 | 172.31.34.179 |              0
                   Parsing select * FROM testtomb WHERE name = 'Dhaval45'; [SharedPool-Worker-2] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |             64
                                                       Preparing statement [SharedPool-Worker-2] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            101
                              Executing single-partition query on testtomb [SharedPool-Worker-3] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            210
                                              Acquiring sstable references [SharedPool-Worker-3] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            223
 Skipped 0/0 non-slice-intersecting sstables, included 0 due to tombstones [SharedPool-Worker-3] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            243
                                 Merged data from memtables and 0 sstables [SharedPool-Worker-3] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            288
                                         Read 2 live and 0 tombstone cells [SharedPool-Worker-3] | 2017-03-29 10:28:27.342001 | 172.31.34.179 |            310
                                 Merged data from memtables and 0 sstables [SharedPool-Worker-3] | 2017-03-29 10:28:27.342001 | 172.31.34.179 |            323
                                                                                Request complete | 2017-03-29 10:28:27.342385 | 172.31.34.179 |            385
</code>```

And this is the log when i query on filed which i have executed a delete query. Initially  user Dhaval15 has firstname 'aaaa' and then i the cell aaa. then again executing select query on same user gave me this log.

```<code>       activity                                                                                | timestamp                  | source        | source_elapsed
-------------------------------------------------------------------------------------------------+----------------------------+---------------+----------------
                                                                              Execute CQL3 query | 2017-03-29 10:35:18.581000 | 172.31.34.179 |              0
                   Parsing select * FROM testtomb WHERE name = 'Dhaval15'; [SharedPool-Worker-1] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |             65
                                                       Preparing statement [SharedPool-Worker-1] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |            113
                              Executing single-partition query on testtomb [SharedPool-Worker-3] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |            223
                                              Acquiring sstable references [SharedPool-Worker-3] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |            235
 Skipped 0/0 non-slice-intersecting sstables, included 0 due to tombstones [SharedPool-Worker-3] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |            256
                                 Merged data from memtables and 0 sstables [SharedPool-Worker-3] | 2017-03-29 10:35:18.581001 | 172.31.34.179 |            305
                                         Read 1 live and 1 tombstone cells [SharedPool-Worker-3] | 2017-03-29 10:35:18.581001 | 172.31.34.179 |            338
                                 Merged data from memtables and 0 sstables [SharedPool-Worker-3] | 2017-03-29 10:35:18.581001 | 172.31.34.179 |            351
                                                                                Request complete | 2017-03-29 10:35:18.581430 | 172.31.34.179 |            430
</code>```

答:
In Cassandra tombstone created even if you don't execute delete query, when you insert null value.

Tombstone consume space. When you execute select query cassandra needs to filter out data by tombstone. If huge tombstone generated your select query performance will degrade.

Your query failing because of huge tombstone and ALLOW FILTERING. Don't use ALLOW FILTERING on production. it's very costy. When you execute query without specifying partition key, Cassandra needs to scan all the row of all the nodes.

Change your data model to like the below one :

```<code>CREATE TABLE my_table (
    year int,
    month int,
    date timeuuid,
    email text,
    firstname text,
    lastname text,
    mobile text,
    value float,
    PRIMARY KEY ((year, month), date)
);
</code>```

Here you can specify year and month extract from the date.

Now you can query with specifying partition key :

```<code>SELECT * FROM my_table WHERE year = 2017 AND month = 03 AND date >= minTimeuuid('2017-03-25 00:00:00+0000') AND date <= minTimeuuid('2017-03-28 23:59:59+0000') ;
</code>```

This will return result very efficiently and will not fail.

If you need to query with firstname and lastname create an index on them

```<code>CREATE INDEX index_firstname ON my_table (firstname) ;
CREATE INDEX index_lastname ON my_table (lastname) ;
</code>```

Then you can query with firstname or last name

```<code>SELECT * FROM my_table WHERE firstname = 'ashraful' ;
SELECT * FROM my_table WHERE lastname  = 'islam' ;
</code>```

Here i have not create index on email and phone because of high cardinality problem. Instead create materialized view or another table to query with phone or email

```<code>CREATE MATERIALIZED VIEW mview_mobile AS
    SELECT *
    FROM my_table
    WHERE mobile IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND date IS NOT NULL
    PRIMARY KEY (mobile, year, month, date);

CREATE MATERIALIZED VIEW mview_email AS
        SELECT *
        FROM my_table
        WHERE email IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND date IS NOT NULL
        PRIMARY KEY (email, year, month, date);
</code>```

Now you can query with phone or email

```<code>SELECT * FROM mview_mobile WHERE mobile = '018..';
SELECT * FROM mview_email WHERE email = 'ashraful@...';
</code>```

More about cassandra tombstone : http://thelastpickle.com/blog/2016/07/27/about-deletes-and-tombstones.html

Title: Cassandra query failure (Tombstones)

Body:
So this is driving me crazy. i tried querying one of my table in Cassandra and it showed query failure. i tried digging dip in to the reason behind it and found that it was because of tombstone. i changed GC_GRACE_SECONDS to Zero and triggered Compaction using nodetool, And when i queried again it worked fine. however on a subsequent calls query failed again with a same reason. i am using cassandra-nodejs driver.
This is my data model.

CREATE TABLE my_table (
    firstname text,
    lastname text,
    email text,
    mobile text,
    date timeuuid,
    value float,
    PRIMARY KEY (firstname, lastname, email, mobile)
) WITH CLUSTERING ORDER BY (lastname ASC, email ASC, mobile ASC);

this is the query i want to perform on that data model.

SELECT firstname, email, toDate(date) as date, mobile, value FROM my_table  WHERE date >= minTimeuuid('2017-03-25 00:00:00+0000') AND date <= minTimeuuid('2017-03-28 23:59:59+0000') ALLOW FILTERING;

the result will have approx 40k rows.
this shows that if we delete something it will be marked as tombstone and will get deleted After GC_GRACE_SECONDS setted for given table. If i understand it correctly then.

how come there be tombstone problem when i never delete any row of table?

Is that true a row will be marked as Tombstone if and only if we delete a row?

clearing tombstones and then querying the same works sometimes and sometimes it does not, why is so?.

is it a good idea to increase tombstone_failure_threshold value? (single node cluster application)

I am using cassandra 3.5, with cqlsh version 5.0.1. And the query works fine with terminal, but gives error when we execute using external client (express app using nodejs driver for cassandra). i have a single node cluster app.

EDIT 1

This is the log of my Inserted null value in field (i inserted only name and timestamp);

  activity                                                                                | timestamp                  | source        | source_elapsed
-------------------------------------------------------------------------------------------------+----------------------------+---------------+----------------
                                                                              Execute CQL3 query | 2017-03-29 10:28:27.342000 | 172.31.34.179 |              0
                   Parsing select * FROM testtomb WHERE name = 'Dhaval45'; [SharedPool-Worker-2] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |             64
                                                       Preparing statement [SharedPool-Worker-2] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            101
                              Executing single-partition query on testtomb [SharedPool-Worker-3] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            210
                                              Acquiring sstable references [SharedPool-Worker-3] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            223
 Skipped 0/0 non-slice-intersecting sstables, included 0 due to tombstones [SharedPool-Worker-3] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            243
                                 Merged data from memtables and 0 sstables [SharedPool-Worker-3] | 2017-03-29 10:28:27.342000 | 172.31.34.179 |            288
                                         Read 2 live and 0 tombstone cells [SharedPool-Worker-3] | 2017-03-29 10:28:27.342001 | 172.31.34.179 |            310
                                 Merged data from memtables and 0 sstables [SharedPool-Worker-3] | 2017-03-29 10:28:27.342001 | 172.31.34.179 |            323
                                                                                Request complete | 2017-03-29 10:28:27.342385 | 172.31.34.179 |            385

And this is the log when i query on filed which i have executed a delete query. Initially  user Dhaval15 has firstname 'aaaa' and then i the cell aaa. then again executing select query on same user gave me this log.

       activity                                                                                | timestamp                  | source        | source_elapsed
-------------------------------------------------------------------------------------------------+----------------------------+---------------+----------------
                                                                              Execute CQL3 query | 2017-03-29 10:35:18.581000 | 172.31.34.179 |              0
                   Parsing select * FROM testtomb WHERE name = 'Dhaval15'; [SharedPool-Worker-1] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |             65
                                                       Preparing statement [SharedPool-Worker-1] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |            113
                              Executing single-partition query on testtomb [SharedPool-Worker-3] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |            223
                                              Acquiring sstable references [SharedPool-Worker-3] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |            235
 Skipped 0/0 non-slice-intersecting sstables, included 0 due to tombstones [SharedPool-Worker-3] | 2017-03-29 10:35:18.581000 | 172.31.34.179 |            256
                                 Merged data from memtables and 0 sstables [SharedPool-Worker-3] | 2017-03-29 10:35:18.581001 | 172.31.34.179 |            305
                                         Read 1 live and 1 tombstone cells [SharedPool-Worker-3] | 2017-03-29 10:35:18.581001 | 172.31.34.179 |            338
                                 Merged data from memtables and 0 sstables [SharedPool-Worker-3] | 2017-03-29 10:35:18.581001 | 172.31.34.179 |            351
                                                                                Request complete | 2017-03-29 10:35:18.581430 | 172.31.34.179 |            430

Body:
In Cassandra tombstone created even if you don't execute delete query, when you insert null value.

Tombstone consume space. When you execute select query cassandra needs to filter out data by tombstone. If huge tombstone generated your select query performance will degrade.

Your query failing because of huge tombstone and ALLOW FILTERING. Don't use ALLOW FILTERING on production. it's very costy. When you execute query without specifying partition key, Cassandra needs to scan all the row of all the nodes.

Change your data model to like the below one :

CREATE TABLE my_table (
    year int,
    month int,
    date timeuuid,
    email text,
    firstname text,
    lastname text,
    mobile text,
    value float,
    PRIMARY KEY ((year, month), date)
);

Here you can specify year and month extract from the date.

Now you can query with specifying partition key :

SELECT * FROM my_table WHERE year = 2017 AND month = 03 AND date >= minTimeuuid('2017-03-25 00:00:00+0000') AND date <= minTimeuuid('2017-03-28 23:59:59+0000') ;

This will return result very efficiently and will not fail.

If you need to query with firstname and lastname create an index on them

CREATE INDEX index_firstname ON my_table (firstname) ;
CREATE INDEX index_lastname ON my_table (lastname) ;

Then you can query with firstname or last name

SELECT * FROM my_table WHERE firstname = 'ashraful' ;
SELECT * FROM my_table WHERE lastname  = 'islam' ;

Here i have not create index on email and phone because of high cardinality problem. Instead create materialized view or another table to query with phone or email

CREATE MATERIALIZED VIEW mview_mobile AS
    SELECT *
    FROM my_table
    WHERE mobile IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND date IS NOT NULL
    PRIMARY KEY (mobile, year, month, date);

CREATE MATERIALIZED VIEW mview_email AS
        SELECT *
        FROM my_table
        WHERE email IS NOT NULL AND year IS NOT NULL AND month IS NOT NULL AND date IS NOT NULL
        PRIMARY KEY (email, year, month, date);

Now you can query with phone or email

SELECT * FROM mview_mobile WHERE mobile = '018..';
SELECT * FROM mview_email WHERE email = 'ashraful@...';

More about cassandra tombstone : http://thelastpickle.com/blog/2016/07/27/about-deletes-and-tombstones.html