问:
font-awesome installation in ionic 3 project
I am trying to install font-awesome in my ionic 3 project.
I used the command :

```<code>npm install font-awesome --save
</code>```

Here is the content of the package.json file

```<code>    {
       "name": "ionic-hello-world",
       "version": "0.0.0",
      "author": "Ionic Framework",
      "homepage": "http://ionicframework.com/",
      "private": true,
      "scripts": {
        "clean": "ionic-app-scripts clean",
        "build": "ionic-app-scripts build",
        "lint": "ionic-app-scripts lint",
        "ionic:build": "ionic-app-scripts build",
        "ionic:serve": "ionic-app-scripts serve"
      },
      "config": {
        "ionic_copy": "./config/copy.config.js"
      },
      "dependencies": {
        "@angular/common": "4.1.3",
        "@angular/compiler": "4.1.3",
        "@angular/compiler-cli": "4.1.3",
        "@angular/core": "4.1.3",
        "@angular/forms": "4.1.3",
        "@angular/http": "4.1.3",
        "@angular/platform-browser": "4.1.3",
        "@angular/platform-browser-dynamic": "4.1.3",
        "@ionic-native/camera": "^3.13.1",
        "@ionic-native/core": "3.10.2",
        "@ionic-native/network": "^4.2.1",
        "@ionic-native/splash-screen": "3.10.2",
        "@ionic-native/status-bar": "3.10.2",
        "@ionic/storage": "2.0.1",
        "angularfire2": "^4.0.0-rc0",
        "firebase": "^3.9.0",
        "font-awesome": "^4.7.0",
        "ionic-angular": "3.4.2",
        "ionicons": "3.0.0",
        "promise-polyfill": "^6.0.2",
        "rxjs": "5.4.0",
        "sw-toolbox": "3.6.0",
        "typings": "^2.1.1",
        "zone.js": "0.8.12"
      },
      "devDependencies": {
        "@ionic/app-scripts": "1.3.7",
        "typescript": "2.3.3"
      },
      "cordovaPlugins": [
        "cordova-plugin-whitelist",
        "cordova-plugin-console",
        "cordova-plugin-statusbar",
        "cordova-plugin-device",
        "cordova-plugin-splashscreen",
        "ionic-plugin-keyboard"
      ],
      "cordovaPlatforms": [],
      "description": "loginApp: An Ionic project"
    }
</code>```

After installation, I created a directory called config in the root of the project folder. In that directory, i added the file copy.config.js copied from node_modules/ionic/app-scripts/config/copy.config.js, in which i added these two copy tasks :

```<code>    copyFontawesomeFonts: {
      src: ['{{ROOT}}/node_modules/font-awesome/fonts/**/*'],
      dest: '{{WWW}}/assets/fonts'
    },
    copyFontawesomeCss: {
      src: ['{{ROOT}}/node_modules/font-awesome/css/font-awesome.min.css'],
      dest: '{{WWW}}/assets/css'
    },
</code>```

But unfortunately, the copy is not made, and all the necessary files are not copied to assets/fonts and assets/css. I copied theses files manually in the assets and fonts folders and I can use font-awesome in my project, but I would like to know why the copy tasks does not work.

Any help will be useful. Thanks.

答:
I installed font awesome in a different way.

Step 1) Add to node_modules/@ionic/app-scripts/config/sass.config.js

```<code>  includePaths: [
    'node_modules/ionic-angular/themes',
    'node_modules/ionicons/dist/scss',
    'node_modules/ionic-angular/fonts',
    'node_modules/font-awesome/scss'
  ],
</code>```

Step 2) Add to variables.scss

```<code>@import "font-awesome";
</code>```

Step 3) Copy the required font awesome fonts to build area.

package.json

```<code>"config": {
    "ionic_copy": "./copy-from.js"
},
</code>```

copy-from.js

```<code>var fs = require('fs-extra')

// we will add config later here, right now the translation files are not being copied even though
// they are in assets.
var dependencies = [
  ['node_modules/font-awesome/fonts/', 'www/fonts']
];

console.log('Executing application custom copies...', dependencies);
dependencies.forEach(function (value) {
  fs.copy(value[0], value[1], function (err) {
    if (err) return console.error(err)
    console.log("success!")
  });

});
</code>```

At this point there is probably a better way to do step 3.

Body:
I am trying to install font-awesome in my ionic 3 project.
I used the command :

npm install font-awesome --save

Here is the content of the package.json file

    {
       "name": "ionic-hello-world",
       "version": "0.0.0",
      "author": "Ionic Framework",
      "homepage": "http://ionicframework.com/",
      "private": true,
      "scripts": {
        "clean": "ionic-app-scripts clean",
        "build": "ionic-app-scripts build",
        "lint": "ionic-app-scripts lint",
        "ionic:build": "ionic-app-scripts build",
        "ionic:serve": "ionic-app-scripts serve"
      },
      "config": {
        "ionic_copy": "./config/copy.config.js"
      },
      "dependencies": {
        "@angular/common": "4.1.3",
        "@angular/compiler": "4.1.3",
        "@angular/compiler-cli": "4.1.3",
        "@angular/core": "4.1.3",
        "@angular/forms": "4.1.3",
        "@angular/http": "4.1.3",
        "@angular/platform-browser": "4.1.3",
        "@angular/platform-browser-dynamic": "4.1.3",
        "@ionic-native/camera": "^3.13.1",
        "@ionic-native/core": "3.10.2",
        "@ionic-native/network": "^4.2.1",
        "@ionic-native/splash-screen": "3.10.2",
        "@ionic-native/status-bar": "3.10.2",
        "@ionic/storage": "2.0.1",
        "angularfire2": "^4.0.0-rc0",
        "firebase": "^3.9.0",
        "font-awesome": "^4.7.0",
        "ionic-angular": "3.4.2",
        "ionicons": "3.0.0",
        "promise-polyfill": "^6.0.2",
        "rxjs": "5.4.0",
        "sw-toolbox": "3.6.0",
        "typings": "^2.1.1",
        "zone.js": "0.8.12"
      },
      "devDependencies": {
        "@ionic/app-scripts": "1.3.7",
        "typescript": "2.3.3"
      },
      "cordovaPlugins": [
        "cordova-plugin-whitelist",
        "cordova-plugin-console",
        "cordova-plugin-statusbar",
        "cordova-plugin-device",
        "cordova-plugin-splashscreen",
        "ionic-plugin-keyboard"
      ],
      "cordovaPlatforms": [],
      "description": "loginApp: An Ionic project"
    }

After installation, I created a directory called config in the root of the project folder. In that directory, i added the file copy.config.js copied from node_modules/ionic/app-scripts/config/copy.config.js, in which i added these two copy tasks :

    copyFontawesomeFonts: {
      src: ['{{ROOT}}/node_modules/font-awesome/fonts/**/*'],
      dest: '{{WWW}}/assets/fonts'
    },
    copyFontawesomeCss: {
      src: ['{{ROOT}}/node_modules/font-awesome/css/font-awesome.min.css'],
      dest: '{{WWW}}/assets/css'
    },

But unfortunately, the copy is not made, and all the necessary files are not copied to assets/fonts and assets/css. I copied theses files manually in the assets and fonts folders and I can use font-awesome in my project, but I would like to know why the copy tasks does not work.

Any help will be useful. Thanks.

Body:
I installed font awesome in a different way.

Step 1) Add to node_modules/@ionic/app-scripts/config/sass.config.js

  includePaths: [
    'node_modules/ionic-angular/themes',
    'node_modules/ionicons/dist/scss',
    'node_modules/ionic-angular/fonts',
    'node_modules/font-awesome/scss'
  ],

Step 2) Add to variables.scss

@import "font-awesome";

Step 3) Copy the required font awesome fonts to build area.

package.json

"config": {
    "ionic_copy": "./copy-from.js"
},

copy-from.js

var fs = require('fs-extra')

// we will add config later here, right now the translation files are not being copied even though
// they are in assets.
var dependencies = [
  ['node_modules/font-awesome/fonts/', 'www/fonts']
];

console.log('Executing application custom copies...', dependencies);
dependencies.forEach(function (value) {
  fs.copy(value[0], value[1], function (err) {
    if (err) return console.error(err)
    console.log("success!")
  });

});

At this point there is probably a better way to do step 3.


来源: stackexchange

问:
How to do a bidirectional synchronization between GIT and SVN
How can you do a bidirectional synchronization between a GIT repository and a SVN repository? I've seen how you can convert from SVN to GIT, but not much about how you can synchronize smoothly between the two.

The purpose is to save the project in both types of repositories and have them producing/tracking identical content.

As an extra requirement, the SVN repository as the subject does not contain trunk and branches.

答:
This post - Creating a two way sync between a Github repository and Subversion - looks to be a solution:

Create a git repo on a github server or a bitbucket server. Clone the empty repo. Add a readme-git file and commit on master.

Initially create the svn tracking branch:

```
    git branch --no-track svnsync
    git checkout svnsync
    git svn init http://your-svn-server/your-repo
                # here removed  `-s`  if the svn repo is not on a standard layout
                # or use file:///path/to/local/repo
    git svn fetch
                # add if needed  `--authors-file svn-authors.txt`
    git reset --hard remotes/git-svn
                # the post said `remotes/trunk` but it does not look right
```

Sync from svn to git:

```
    git checkout svnsync
    git svn rebase
    git checkout master
    git merge svnsync
                # add  `--allow-unrelated-histories`  to the first merge
    git push origin master
```

Sync from git to svn:

```
    git checkout master
    git pull origin master
    git checkout svnsync
    git svn rebase
    git merge --no-ff master
    git commit
    git svn dcommit
```

A drawback of the above sequence is that a bogus readme-git file was added so that a non-tracking branch could be pulled. Starting with a git repo that is initially cloned from the svn repo may avoid the problem, I guess.

ContentLicense: CC BY-SA 3.0

Body:
This post - Creating a two way sync between a Github repository and Subversion - looks to be a solution:

Create a git repo on a github server or a bitbucket server. Clone the empty repo. Add a readme-git file and commit on master.

Initially create the svn tracking branch:

    git branch --no-track svnsync
    git checkout svnsync
    git svn init http://your-svn-server/your-repo
                # here removed  `-s`  if the svn repo is not on a standard layout
                # or use file:///path/to/local/repo
    git svn fetch
                # add if needed  `--authors-file svn-authors.txt`
    git reset --hard remotes/git-svn
                # the post said `remotes/trunk` but it does not look right

Sync from svn to git:

    git checkout svnsync
    git svn rebase
    git checkout master
    git merge svnsync
                # add  `--allow-unrelated-histories`  to the first merge
    git push origin master

Sync from git to svn:

    git checkout master
    git pull origin master
    git checkout svnsync
    git svn rebase
    git merge --no-ff master
    git commit
    git svn dcommit

A drawback of the above sequence is that a bogus readme-git file was added so that a non-tracking branch could be pulled. Starting with a git repo that is initially cloned from the svn repo may avoid the problem, I guess.


问:
null response usin Retrofit Library in android
Here is my JSONArray Response from Web service:

And Class Java :

```<code>public class Product {

  private int id,price,discount;
  private String name,image,description,discount_type,discount_exp;

  @SerializedName("products")
  private List<Product> products;

  public Product()
  {

  }

}
</code>```

response is null

答:
You have to change like it will work</p>

```<code>public class ProductModel {

    private int current_page;

    private ArrayList<DataModel> data = new ArrayList<>();

    public int getCurrent_page() {
        return current_page;
    }

    public void setCurrent_page(int current_page) {
        this.current_page = current_page;
    }

    public ArrayList<DataModel> getData() {
        return data;
    }

    public void setData(ArrayList<DataModel> data) {
        this.data = data;
    }

    private class DataModel{

        private int id,price,discount,shop_id,vote_id,vedeo_id,status;
        private String name,image,description,discount_type,discount_exp,created_at,updated_at;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public int getPrice() {
            return price;
        }

        public void setPrice(int price) {
            this.price = price;
        }

        public int getDiscount() {
            return discount;
        }

        public void setDiscount(int discount) {
            this.discount = discount;
        }

        public int getShop_id() {
            return shop_id;
        }

        public void setShop_id(int shop_id) {
            this.shop_id = shop_id;
        }

        public int getVote_id() {
            return vote_id;
        }

        public void setVote_id(int vote_id) {
            this.vote_id = vote_id;
        }

        public int getVedeo_id() {
            return vedeo_id;
        }

        public void setVedeo_id(int vedeo_id) {
            this.vedeo_id = vedeo_id;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getImage() {
            return image;
        }

        public void setImage(String image) {
            this.image = image;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getDiscount_type() {
            return discount_type;
        }

        public void setDiscount_type(String discount_type) {
            this.discount_type = discount_type;
        }

        public String getDiscount_exp() {
            return discount_exp;
        }

        public void setDiscount_exp(String discount_exp) {
            this.discount_exp = discount_exp;
        }

        public String getCreated_at() {
            return created_at;
        }

        public void setCreated_at(String created_at) {
            this.created_at = created_at;
        }

        public String getUpdated_at() {
            return updated_at;
        }

        public void setUpdated_at(String updated_at) {
            this.updated_at = updated_at;
        }
    }
}
</code>```

Body:
Here is my JSONArray Response from Web service:

And Class Java :

public class Product {

  private int id,price,discount;
  private String name,image,description,discount_type,discount_exp;

  @SerializedName("products")
  private List<Product> products;

  public Product()
  {

  }

}

response is null

Body:
You have to change like it will work

public class ProductModel {

    private int current_page;

    private ArrayList<DataModel> data = new ArrayList<>();

    public int getCurrent_page() {
        return current_page;
    }

    public void setCurrent_page(int current_page) {
        this.current_page = current_page;
    }

    public ArrayList<DataModel> getData() {
        return data;
    }

    public void setData(ArrayList<DataModel> data) {
        this.data = data;
    }

    private class DataModel{

        private int id,price,discount,shop_id,vote_id,vedeo_id,status;
        private String name,image,description,discount_type,discount_exp,created_at,updated_at;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public int getPrice() {
            return price;
        }

        public void setPrice(int price) {
            this.price = price;
        }

        public int getDiscount() {
            return discount;
        }

        public void setDiscount(int discount) {
            this.discount = discount;
        }

        public int getShop_id() {
            return shop_id;
        }

        public void setShop_id(int shop_id) {
            this.shop_id = shop_id;
        }

        public int getVote_id() {
            return vote_id;
        }

        public void setVote_id(int vote_id) {
            this.vote_id = vote_id;
        }

        public int getVedeo_id() {
            return vedeo_id;
        }

        public void setVedeo_id(int vedeo_id) {
            this.vedeo_id = vedeo_id;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getImage() {
            return image;
        }

        public void setImage(String image) {
            this.image = image;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getDiscount_type() {
            return discount_type;
        }

        public void setDiscount_type(String discount_type) {
            this.discount_type = discount_type;
        }

        public String getDiscount_exp() {
            return discount_exp;
        }

        public void setDiscount_exp(String discount_exp) {
            this.discount_exp = discount_exp;
        }

        public String getCreated_at() {
            return created_at;
        }

        public void setCreated_at(String created_at) {
            this.created_at = created_at;
        }

        public String getUpdated_at() {
            return updated_at;
        }

        public void setUpdated_at(String updated_at) {
            this.updated_at = updated_at;
        }
    }
}


问:
Laptop Keyboard isn't detected by Emulator in Android Studio
My Android Studio Emulator is not getting input from Laptop Keyboard. This was never happened before as i was working for more than 2 months. Now i can't give input from my laptop keyboard to emulator. i m using NEXUS 5X API 26 Emulator. Kindly let me know how to unlock laptop keyboard in android Emulator??..
Thanks in advance</p>

答: Ensure that under your emulator's preferences -> advanced settings, you have a check mark in "Enable keyboard input". I think some update to the tooling recently cleared this checkbox for some (all?) emulators.


问:
PHP: how to parse a huge xml file
I need to parse a huge XML that contains lots of job entries, like this

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<items>
  <item>
    <title><![CDATA[...]]></title>
    <description><![CDATA[...]]></description>
    <link><![CDATA[...]]></link>
    <city><![CDATA[...]]></city>
    <state><![CDATA[...]]></state>
    <position><![CDATA[...]]></position>
    <company><![CDATA[...]]></company>
    <category_id><![CDATA[...]]></category_id>
    <job_id>...</job_id>
    <salary><![CDATA[...]]></salary>
    <term><![CDATA[...]]></term>
  </item>

  ....

</items>
</code>```

The server has enough memory to fully read that file but when if comes to parsing, it fails with "memory exhausted" error. Does PHP provide ways that would allow to split that file nicely or parse it in parts or anything that can be of help here. Thanks for any ideas and suggestions!

答:
Have you tried ramping up the memory?

```<code>ini_set("memory_limit", "128M")
</code>```

place this code at the top of your php file.
you can set the memory as high as you want

ContentLicense: CC BY-SA 2.5

Title: PHP: how to parse a huge xml file

Body:
I need to parse a huge XML that contains lots of job entries, like this

<?xml version="1.0" encoding="ISO-8859-1"?>
<items>
  <item>
    <title><![CDATA[...]]></title>
    <description><![CDATA[...]]></description>
    <link><![CDATA[...]]></link>
    <city><![CDATA[...]]></city>
    <state><![CDATA[...]]></state>
    <position><![CDATA[...]]></position>
    <company><![CDATA[...]]></company>
    <category_id><![CDATA[...]]></category_id>
    <job_id>...</job_id>
    <salary><![CDATA[...]]></salary>
    <term><![CDATA[...]]></term>
  </item>

  ....

</items>

The server has enough memory to fully read that file but when if comes to parsing, it fails with "memory exhausted" error. Does PHP provide ways that would allow to split that file nicely or parse it in parts or anything that can be of help here. Thanks for any ideas and suggestions!

Body:
Have you tried ramping up the memory?

ini_set("memory_limit", "128M")

place this code at the top of your php file.
you can set the memory as high as you want


问:
How to test nginx subdomains on localhost
I want to test nginx subdomains before uploading config to the server. Can i test it on localhost? I try

```<code>server {
    listen       80;
    server_name  localhost;

    location / {
        proxy_pass http://localhost:8080;
    }
}

server {
    listen       80;
    server_name  sub.localhost;

    location / {
        proxy_pass http://localhost:8080/sub;
    }
}
</code>```

And it does not work. Shoulld i change my hosts file in order to make it work? Also, after uploading site to the server should i change DNS records and add sub.mydomain.com?

答:
In Linux based OS just to edit as sudo /etc/hosts file and change 127.0.0.1 localhost to 127.0.0.1 *.localhost.

So at /etc/nginx/sites-enabled/<environment>/<your_project_name> edit server_name key as <subdomain>.localhost.

Reload nginx and networking service.

```<code>$ sudo service nginx reload
$ sudo service networking reload
</code>```

And then try http://<subdomain>.localhost at url bar.

It works for me.

UPDATE

In my opinion, a better solution is creating a virtual server that only responds if subdomain doesn’t exist, at /etc/nginx/sites-enabled/development/default, as default server (remember that you can define only one server as default).

```<code>server {
  listen 80 default_server;
  root /var/www/html/errors/404;
  server_name *.localhost *.<host-name>;

  location / {
    index subdomain.html;
  }

}
</code>```

Make sure that in nginx.conf (generally at /etc/nginx/nginx.conf) contain include /etc/nginx/sites-enabled/**/*; to this virtual server work. If not, put it and then run $ sudo service nginx reload.

In this case isn't necessary put *.localhost in /etc/hosts, but only localhost.

Body:
I want to test nginx subdomains before uploading config to the server. Can i test it on localhost? I try

server {
    listen       80;
    server_name  localhost;

    location / {
        proxy_pass http://localhost:8080;
    }
}

server {
    listen       80;
    server_name  sub.localhost;

    location / {
        proxy_pass http://localhost:8080/sub;
    }
}

And it does not work. Shoulld i change my hosts file in order to make it work? Also, after uploading site to the server should i change DNS records and add sub.mydomain.com?

Body:
In Linux based OS just to edit as sudo /etc/hosts file and change 127.0.0.1 localhost to 127.0.0.1 *.localhost.

So at /etc/nginx/sites-enabled/<environment>/<your_project_name> edit server_name key as <subdomain>.localhost.

Reload nginx and networking service.

$ sudo service nginx reload
$ sudo service networking reload

And then try http://<subdomain>.localhost at url bar.

It works for me.

UPDATE

In my opinion, a better solution is creating a virtual server that only responds if subdomain doesn’t exist, at /etc/nginx/sites-enabled/development/default, as default server (remember that you can define only one server as default).

server {
  listen 80 default_server;
  root /var/www/html/errors/404;
  server_name *.localhost *.<host-name>;

  location / {
    index subdomain.html;
  }

}

Make sure that in nginx.conf (generally at /etc/nginx/nginx.conf) contain include /etc/nginx/sites-enabled/**/*; to this virtual server work. If not, put it and then run $ sudo service nginx reload.

In this case isn't necessary put *.localhost in /etc/hosts, but only localhost.

ContentLicense: CC BY-SA 4.0


问:
ffmpeg FPS information mismatch with the video
I have a bunch of videos with some statistics of what is happening inside a video. One such piece of information is given in terms of time of the video in seconds up to one decimal point.

To get the FPS of a video, I am using ffmpeg -i

But when I manually compute one particular frame's time using given FPS, it does not match.

For example, ffmpeg outputs FPS = 30.

I look at the video statistics, the frame at the 156.8 = 2.368 has to be
4704'th frame. I open the video using 'skvideo', read all the frames, and view the 4704'th frame. It is some frame around time 2.12?. I checked multiple such instances in multiple videos and this is a common behavior.

I do not understand why this is so and how can I get around the problem?

As such I am not bounded by ffmpeg. Skvideo is being used to read the videos. I tried opencv, as of now it does not work with VideoCapture, and reinstalling it is costly for me time wise. But I guess 'opencv/skvideo' should not matter, one can count the frames manually as well.

So, in the solution, I am looking out for -

Given timestamps of inside of a video, how can I find a frame of that particular time location?

In case someone might have already worked on this, this is related to THUMOS dataset. I am on Ubuntu 16.04

EDIT_1

Actually I can be more specific as it is a publicly available data. The time bounds are of an important activity. For example, in a video, when does basketball dunk occurs? It is given in pairs - [start end]. Some videos have multiple activities, some have only one.

Here is a sample video, and following are the activity times.

```<code>[[  16.5, 20.8],
[  26.6, 32.2],
[  34.8, 42.1],
[  47.8, 50.0],
[  58.1, 62.9],
[  65.6, 67.2],
[  68.5, 74.0],
[  76.4, 78.3],
[  78.7, 79.8],
[  80.8, 82.1],
[  85.0, 87.3],
[  90.1, 91.4],
[  98.5, 100.3]]
</code>```

I also tried checking manually, 32.87 FPS "almost" works for few videos but not for all. and almost means it is off by ~ 10 frames. This is a huge difference for my task, and I need exact frame.

Also, there has to be some way, because it can be visually observed with multiple video players that times in the dataset are correct.

答:
If your aim is to extract a frame corresponding to a timestamp, use

```<code>ffmpeg -i in.mp4 -vf select='lt(t,TS)*lt(TS-t,1/FPS)' -vsync 0 frame.png
</code>```

TS should be replaced with your timestamp and FPS with framerate e.g. 'lt(t,78.7)*lt(78.7-t,1/30)'

Frame  indexes are unreliable if the video is variable framerate as yours appear to be.

Body:
I have a bunch of videos with some statistics of what is happening inside a video. One such piece of information is given in terms of time of the video in seconds up to one decimal point.

To get the FPS of a video, I am using ffmpeg -i

But when I manually compute one particular frame's time using given FPS, it does not match.

For example, ffmpeg outputs FPS = 30.

I look at the video statistics, the frame at the 156.8 = 2.368 has to be
4704'th frame. I open the video using 'skvideo', read all the frames, and view the 4704'th frame. It is some frame around time 2.12?. I checked multiple such instances in multiple videos and this is a common behavior.

I do not understand why this is so and how can I get around the problem?

As such I am not bounded by ffmpeg. Skvideo is being used to read the videos. I tried opencv, as of now it does not work with VideoCapture, and reinstalling it is costly for me time wise. But I guess 'opencv/skvideo' should not matter, one can count the frames manually as well.

So, in the solution, I am looking out for -

Given timestamps of inside of a video, how can I find a frame of that particular time location?

In case someone might have already worked on this, this is related to THUMOS dataset. I am on Ubuntu 16.04

EDIT_1

Actually I can be more specific as it is a publicly available data. The time bounds are of an important activity. For example, in a video, when does basketball dunk occurs? It is given in pairs - [start end]. Some videos have multiple activities, some have only one.

Here is a sample video, and following are the activity times.

[[  16.5, 20.8],
[  26.6, 32.2],
[  34.8, 42.1],
[  47.8, 50.0],
[  58.1, 62.9],
[  65.6, 67.2],
[  68.5, 74.0],
[  76.4, 78.3],
[  78.7, 79.8],
[  80.8, 82.1],
[  85.0, 87.3],
[  90.1, 91.4],
[  98.5, 100.3]]

I also tried checking manually, 32.87 FPS "almost" works for few videos but not for all. and almost means it is off by ~ 10 frames. This is a huge difference for my task, and I need exact frame.

Also, there has to be some way, because it can be visually observed with multiple video players that times in the dataset are correct.

Body:
If your aim is to extract a frame corresponding to a timestamp, use

ffmpeg -i in.mp4 -vf select='lt(t,TS)*lt(TS-t,1/FPS)' -vsync 0 frame.png

TS should be replaced with your timestamp and FPS with framerate e.g. 'lt(t,78.7)*lt(78.7-t,1/30)'

Frame  indexes are unreliable if the video is variable framerate as yours appear to be.


问:
Producer-Consumer Error in C
I'm trying to implement the Producer Consumer Algorithm in C so that  producer.c takes in one character from a mydata.txt file and puts it into the shell variable DATA then consumer.c will read it from DATA and print it out. The output must be in the same format. All the while, producer.c and consumer.c gives the TURN to each other during the busy loop.

When I compile the program, I'm getting an error: error: too few arguments to function call, expected 1, have 0 because of both wait() functions. Please let me know if I did something wrong. I'm not sure if you'd need all the code but I hope this isn't too much!

main.c:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "producer.c"
#include "consumer.c"

int main(){
  char turn;
  FILE *mydata = fopen("mydata.txt", "rt");

  // Writing 0 into TURN.txt
  FILE *TURN = fopen("TURN.txt", "wt");
  if(TURN == NULL) exit(1);

  putc('0', TURN);
  fclose(TURN);

  int pid = fork();

  // Program done when turn == 'x'
  while(turn - 'x' != 0){

    TURN = fopen("TURN.txt", "rt");
    turn = getc(TURN);
    fclose(TURN);

    // producer() uses pointer to mydata.txt, to avoid having to reopen in producer.c each time
    if(pid == -1){ exit(1); }
    if(pid == 0){ producer(mydata); wait(); }
    if(pid != -1){ consumer(); wait(); }

  }

  fclose(mydata);

  return 0;
}
</code>```

Producer.c:

```<code>#include <stdio.h>
#include <stdlib.h>

void producer(FILE *mydata){
  FILE *DATA;

  // Writing 1 character from mydata.txt to DATA.txt
  DATA = fopen("DATA.txt", "wt");
  if(DATA == NULL) exit(1);
  fprintf(DATA, "%c", getc(mydata));
  fclose(DATA);

  // Writing '1' into TURN.txt for consumer, or 'x' if done reading mydata.txt
  FILE *TURN = fopen("TURN.txt", "wt");
  if(TURN == NULL) exit(1);
  if(!feof(mydata))
    putc('1', TURN);
  else
    putc('x', TURN);
  fclose(TURN);
}
</code>```

consumer.c:

```<code>#include <stdio.h>
#include <stdlib.h>

void consumer(){

    FILE *DATA;

    DATA = fopen("DATA.txt", "r");
    if(DATA == NULL) exit(1);
    int c;
    if(DATA == NULL) { exit(1); }
    do {
    c = fgetc(DATA);
      if( feof(DATA) ) {
         break ;
      }
      printf("%c", c);
    } while(1);

    fclose(DATA);

    FILE *TURN = fopen("TURN.txt", "wt");
    if(TURN == NULL) exit(1);
    if(!feof(DATA))
      putc('0', TURN);
    else
      putc('x', TURN);
    fclose(TURN);

}
</code>```

答:
The wait function requires an argument, as the error tells you.

An address to an integer, to be precise.

Title: Producer-Consumer Error in C

Body:
I'm trying to implement the Producer Consumer Algorithm in C so that  producer.c takes in one character from a mydata.txt file and puts it into the shell variable DATA then consumer.c will read it from DATA and print it out. The output must be in the same format. All the while, producer.c and consumer.c gives the TURN to each other during the busy loop.

When I compile the program, I'm getting an error: error: too few arguments to function call, expected 1, have 0 because of both wait() functions. Please let me know if I did something wrong. I'm not sure if you'd need all the code but I hope this isn't too much!

main.c:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "producer.c"
#include "consumer.c"

int main(){
  char turn;
  FILE *mydata = fopen("mydata.txt", "rt");

  // Writing 0 into TURN.txt
  FILE *TURN = fopen("TURN.txt", "wt");
  if(TURN == NULL) exit(1);

  putc('0', TURN);
  fclose(TURN);

  int pid = fork();

  // Program done when turn == 'x'
  while(turn - 'x' != 0){

    TURN = fopen("TURN.txt", "rt");
    turn = getc(TURN);
    fclose(TURN);

    // producer() uses pointer to mydata.txt, to avoid having to reopen in producer.c each time
    if(pid == -1){ exit(1); }
    if(pid == 0){ producer(mydata); wait(); }
    if(pid != -1){ consumer(); wait(); }

  }

  fclose(mydata);

  return 0;
}

Producer.c:

#include <stdio.h>
#include <stdlib.h>

void producer(FILE *mydata){
  FILE *DATA;

  // Writing 1 character from mydata.txt to DATA.txt
  DATA = fopen("DATA.txt", "wt");
  if(DATA == NULL) exit(1);
  fprintf(DATA, "%c", getc(mydata));
  fclose(DATA);

  // Writing '1' into TURN.txt for consumer, or 'x' if done reading mydata.txt
  FILE *TURN = fopen("TURN.txt", "wt");
  if(TURN == NULL) exit(1);
  if(!feof(mydata))
    putc('1', TURN);
  else
    putc('x', TURN);
  fclose(TURN);
}

consumer.c:

#include <stdio.h>
#include <stdlib.h>

void consumer(){

    FILE *DATA;

    DATA = fopen("DATA.txt", "r");
    if(DATA == NULL) exit(1);
    int c;
    if(DATA == NULL) { exit(1); }
    do {
    c = fgetc(DATA);
      if( feof(DATA) ) {
         break ;
      }
      printf("%c", c);
    } while(1);

    fclose(DATA);

    FILE *TURN = fopen("TURN.txt", "wt");
    if(TURN == NULL) exit(1);
    if(!feof(DATA))
      putc('0', TURN);
    else
      putc('x', TURN);
    fclose(TURN);

}


问:
blogdown can't find updated version of Hugo
While attempting to build a theme with blogdown and Hugo, I encountered the following error: ERROR 2017/12/01 19:34:06 Current theme does not support Hugo version 0.19. Minimum version required is 0.2.

However, I do have an updated version (0.31.1) of Hugo:

```<code>system("hugo version")

Hugo Static Site Generator v0.31.1 darwin/amd64 BuildDate: 2017-12-01T19:36:01-08:00
</code>```

And blogdown cannot find it:

```<code>> blogdown::hugo_version()
[1] ‘0.19’
</code>```

Is this a path issue I need to fix on my machine?

答:
Met the same problem and Yihui's solution works.
To summarise:

unlink('~/Library/Application Support/Hugo', recursive = TRUE)
blogdown::install_hugo(force=TRUE)

Then restart R.

Body:
While attempting to build a theme with blogdown and Hugo, I encountered the following error: ERROR 2017/12/01 19:34:06 Current theme does not support Hugo version 0.19. Minimum version required is 0.2.

However, I do have an updated version (0.31.1) of Hugo:

system("hugo version")

Hugo Static Site Generator v0.31.1 darwin/amd64 BuildDate: 2017-12-01T19:36:01-08:00

And blogdown cannot find it:

> blogdown::hugo_version()
[1] ‘0.19’

Is this a path issue I need to fix on my machine?


问:
Is it possible to call Sonar ScanSner every time merge request is submitted in Gitlab
Is there any way Gitlab can call Sonar scanner every time merge request is submitted for the particular project.

I know a way Gitlab webhook can call Jenkins job & in Jenkins job can call sonar scanner as a build step, But here I want to bypass Jenkins involvement.

答:
A GitLab webhook won't call anything: it will send to an IP address a JSON payload describing a GitLab event (like a push)

From there, you listener (like kolomiichenko/gitlab-webhooker) can call Sonar itself (or any other command, for that matter).

That command/script executed by the listener would:

go to a local copy of the repo

call git pull to update itself

call Sonar Scanner

No Jenkins required.


问:
code to close a matlab app
I have written a Matlab app with the app designer tool, and have successfully coded everything except the pesky (and most likely simple) exit button. The button itself should do what it says, close the app when clicked, but looking online has just led me to dead ends. Here is what I have written down for the exit function; it doesn't work, but its better than writing no code:</p>

```<code> % Button pushed function: ExitButton
    function ExitButtonPushed(app, event)
        Figurename = app.UIFigure ;
        close Figurename
    end
</code>```

答:
MATLAB interprets close Figurename as close('Figurename'), which is not a valid object to close. See command syntax vs. function syntax

Use close(Figurename), or really just close(app.UIFigure).

Title: code to close a matlab app

Body:
I have written a Matlab app with the app designer tool, and have successfully coded everything except the pesky (and most likely simple) exit button. The button itself should do what it says, close the app when clicked, but looking online has just led me to dead ends. Here is what I have written down for the exit function; it doesn't work, but its better than writing no code:

 % Button pushed function: ExitButton
    function ExitButtonPushed(app, event)
        Figurename = app.UIFigure ;
        close Figurename
    end


问:
Elasticsearch Filebeat
Im new to Elasstic Search and im trying to integrate ES in our infrastructure. I installed one central ES server (6.0) with Elasticsearch, Kibana ....

The first task I wanted to do is sending apache logfiles from other servers into this ES server.

From the description of filebeat it seems this module is doing exactly the things i want (lightweight shipping of logfiles to ES server):

https://www.elastic.co/downloads/beats/filebeat

I installed filebeat from the RPM to our Server. But it seems not to run because of missing Plugins (geoIP, UA). I tried to install these but there is no executable "elasticsearch-plugin" available.

Do i have to install the whole ES package on every server I want to send logfiles to our ES Server?

Or is there another way to send logfiles to the ES Server and process fields like IP and UA on the Server side?

答:
It's not the only approach, but this is generally the best way to get started.

You're nearly there: The elasticsearch-plugin is located in /usr/share/elasticsearch/bin/. You will need to install the GeoIP and UA plugins on every Elasticsearch node. Once that's done you should be able to use the Apache module in Filebeat.

Title: Elasticsearch Filebeat


问:
Select * From table As a table dblink
To select from another database I try to use dblink or fdw extension of Postgres, like this:

```<code>CREATE EXTENSION dblink;

SELECT * FROM
dblink ('dbname = bd_name port = 5432 host = 10.6.6.6 user = username password = password',
'SELECT id, code FROM sch_schema.table')
AS new_table(id INTEGER, code character varying);
</code>```

This works fine when I specify which columns I want to select.

My problem is: How can I select all the columns?

I tried this:

```<code>SELECT * FROM
dblink ('dbname = bd_name port = 5432 host = 10.6.6.6 user = username password = password',
'SELECT * FROM sch_schema.table');
</code>```

But this does not work. How can I solve this problem?

答: DBLink returns a generic data row type. One of the annoying things about this is that in order to use it, you need to specify the output structure. Perhaps in future versions of PostgreSQL, this limitation of lack of introspection of generic row types will be irradicated. The lack of introspection is an issue not only for DbLink, but for other generic row type returning functions such as TableFunc cross tab functions</p>

Title: Select * From table As a table dblink

Body:
To select from another database I try to use dblink or fdw extension of Postgres, like this:

CREATE EXTENSION dblink;

SELECT * FROM
dblink ('dbname = bd_name port = 5432 host = 10.6.6.6 user = username password = password',
'SELECT id, code FROM sch_schema.table')
AS new_table(id INTEGER, code character varying);

This works fine when I specify which columns I want to select.

My problem is: How can I select all the columns?

I tried this:

SELECT * FROM
dblink ('dbname = bd_name port = 5432 host = 10.6.6.6 user = username password = password',
'SELECT * FROM sch_schema.table');

But this does not work. How can I solve this problem?


问:
How to use stanford word tokenizer in NLTK?
I am searching way to use stanford word tokenizer in nltk, I want to use because when I compare results of stanford and nltk word tokenizer, they both are different. I know there might be way to use stanford tokenizer, like we can stanford POS Tagger and NER in NLTK.

Is it possible to do use stanford tokenizer without running server?

Thanks

答:
Note: This solution would only work for:

NLTK v3.2.5 (v3.2.6 would have an even simpler interface)

Stanford CoreNLP (version >= 2016-10-31)

First you have to get Java 8 properly installed first and if Stanford CoreNLP works on command line, the Stanford CoreNLP API in NLTK v3.2.5 is as follows.

Note: You have to start the CoreNLP server in terminal BEFORE using the new CoreNLP API in NLTK.

On the terminal:

```<code>wget http://nlp.stanford.edu/software/stanford-corenlp-full-2016-10-31.zip
unzip stanford-corenlp-full-2016-10-31.zip && cd stanford-corenlp-full-2016-10-31

java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer \
-preload tokenize,ssplit,pos,lemma,parse,depparse \
-status_port 9000 -port 9000 -timeout 15000
</code>```

In Python:

```<code>>>> from nltk.parse.corenlp import CoreNLPParser
>>> st = CoreNLPParser()
>>> tokenized_sent = list(st.tokenize('What is the airspeed of an unladen swallow ?'))
>>> tokenized_sent
['What', 'is', 'the', 'airspeed', 'of', 'an', 'unladen', 'swallow', '?']
</code>```

Body:
Note: This solution would only work for:

NLTK v3.2.5 (v3.2.6 would have an even simpler interface)

Stanford CoreNLP (version >= 2016-10-31)

First you have to get Java 8 properly installed first and if Stanford CoreNLP works on command line, the Stanford CoreNLP API in NLTK v3.2.5 is as follows.

Note: You have to start the CoreNLP server in terminal BEFORE using the new CoreNLP API in NLTK.

On the terminal:

wget http://nlp.stanford.edu/software/stanford-corenlp-full-2016-10-31.zip
unzip stanford-corenlp-full-2016-10-31.zip && cd stanford-corenlp-full-2016-10-31

java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer \
-preload tokenize,ssplit,pos,lemma,parse,depparse \
-status_port 9000 -port 9000 -timeout 15000

In Python:

>>> from nltk.parse.corenlp import CoreNLPParser
>>> st = CoreNLPParser()
>>> tokenized_sent = list(st.tokenize('What is the airspeed of an unladen swallow ?'))
>>> tokenized_sent
['What', 'is', 'the', 'airspeed', 'of', 'an', 'unladen', 'swallow', '?']


问:
Excel VBA "else" statement counting wrongly
I have created an "If ElseIf Else" statement that will count the strings in a strings. It does count the keywords/strings that I want to be counted but it is counting the "others"/ Else items wrongly. As shown below highlighted in red, I should only have 6 strings that should be labelled as "others" but it counted as 8. It is a total of 18 rows but on the total results it counted it as 20.
I am newby in VBA and needing experts advise. Thank you.

```<code>Option Compare Text

Public Sub Keywords()

Dim row_number As Long
Dim count_of_corp_or_windows As Long
Dim count_of_mcafee As Long
Dim count_of_token As Long
Dim count_of_host_or_ipass As Long
Dim count_of_others As Long
Dim count_of_X As Long
Dim count_of_all As Long
Dim items As Variant

row_number = 0
count_of_corp_or_windows = 0
count_of_mcafee = 0
count_of_token = 0
count_of_host_or_ipass = 0
count_of_X = 0
count_of_others = 0
count_of_all = 0
Do

row_number = row_number + 1
items = Sheets("LoginPassword").Range("N" & row_number)
    If InStr(items, "corp") Or InStr(items, "windows") Then
        count_of_corp_or_windows = count_of_corp_or_windows + 1
    ElseIf InStr(items, "mcafee") Then
        count_of_mcafee = count_of_mcafee + 1
    ElseIf InStr(items, "token") Then
        count_of_token = count_of_token + 1
    ElseIf InStr(items, "host") Or InStr(items, "ipass") Then
        count_of_host_or_ipass = count_of_host_or_ipass + 1
    ElseIf InStr(items, "X A") Then
        count_of_X = count_of_X + 1
    Else:
        count_of_others = count_of_others + 1

    End If

Loop Until items = ""

count_of_all = count_of_corp_or_windows + count_of_mcafee + count_of_token + count_of_host_or_ipass + count_of_X + count_of_others

Range("N2").Select

Selection.End(xlDown).Select
lastCell = ActiveCell.Address

ActiveCell.Offset(3, 0).Value = "Count"
ActiveCell.Offset(4, 0).Value = count_of_corp_or_windows
ActiveCell.Offset(5, 0).Value = count_of_mcafee
ActiveCell.Offset(6, 0).Value = count_of_token
ActiveCell.Offset(7, 0).Value = count_of_host_or_ipass
ActiveCell.Offset(8, 0).Value = count_of_X
ActiveCell.Offset(9, 0).Value = count_of_others
ActiveCell.Offset(11, 0).Value = count_of_all
ActiveCell.Offset(3, 1).Value = "Keywords"
ActiveCell.Offset(4, 1).Value = "Corp or Windows"
ActiveCell.Offset(5, 1).Value = "Mcafee"
ActiveCell.Offset(6, 1).Value = "Token"
ActiveCell.Offset(7, 1).Value = "Host or ipass"
ActiveCell.Offset(8, 1).Value = "X accounts"
ActiveCell.Offset(9, 1).Value = "Others"
ActiveCell.Offset(11, 1).Value = "Total"
ActiveCell.Offset(3, -1).Value = "Percent"
ActiveCell.Offset(4, -1).Value = count_of_corp_or_windows / count_of_all
ActiveCell.Offset(5, -1).Value = count_of_mcafee / count_of_all
ActiveCell.Offset(6, -1).Value = count_of_token / count_of_all
ActiveCell.Offset(7, -1).Value = count_of_host_or_ipass / count_of_all
ActiveCell.Offset(8, -1).Value = count_of_X / count_of_all
ActiveCell.Offset(9, -1).Value = count_of_others / count_of_all
End Sub
</code>```

答:
Delete the colon from after your Else and try again.
See this answer for reference.

Body:
I have created an "If ElseIf Else" statement that will count the strings in a strings. It does count the keywords/strings that I want to be counted but it is counting the "others"/ Else items wrongly. As shown below highlighted in red, I should only have 6 strings that should be labelled as "others" but it counted as 8. It is a total of 18 rows but on the total results it counted it as 20.
I am newby in VBA and needing experts advise. Thank you.

Option Compare Text

Public Sub Keywords()

Dim row_number As Long
Dim count_of_corp_or_windows As Long
Dim count_of_mcafee As Long
Dim count_of_token As Long
Dim count_of_host_or_ipass As Long
Dim count_of_others As Long
Dim count_of_X As Long
Dim count_of_all As Long
Dim items As Variant

row_number = 0
count_of_corp_or_windows = 0
count_of_mcafee = 0
count_of_token = 0
count_of_host_or_ipass = 0
count_of_X = 0
count_of_others = 0
count_of_all = 0
Do

row_number = row_number + 1
items = Sheets("LoginPassword").Range("N" & row_number)
    If InStr(items, "corp") Or InStr(items, "windows") Then
        count_of_corp_or_windows = count_of_corp_or_windows + 1
    ElseIf InStr(items, "mcafee") Then
        count_of_mcafee = count_of_mcafee + 1
    ElseIf InStr(items, "token") Then
        count_of_token = count_of_token + 1
    ElseIf InStr(items, "host") Or InStr(items, "ipass") Then
        count_of_host_or_ipass = count_of_host_or_ipass + 1
    ElseIf InStr(items, "X A") Then
        count_of_X = count_of_X + 1
    Else:
        count_of_others = count_of_others + 1

    End If

Loop Until items = ""

count_of_all = count_of_corp_or_windows + count_of_mcafee + count_of_token + count_of_host_or_ipass + count_of_X + count_of_others

Range("N2").Select

Selection.End(xlDown).Select
lastCell = ActiveCell.Address

ActiveCell.Offset(3, 0).Value = "Count"
ActiveCell.Offset(4, 0).Value = count_of_corp_or_windows
ActiveCell.Offset(5, 0).Value = count_of_mcafee
ActiveCell.Offset(6, 0).Value = count_of_token
ActiveCell.Offset(7, 0).Value = count_of_host_or_ipass
ActiveCell.Offset(8, 0).Value = count_of_X
ActiveCell.Offset(9, 0).Value = count_of_others
ActiveCell.Offset(11, 0).Value = count_of_all
ActiveCell.Offset(3, 1).Value = "Keywords"
ActiveCell.Offset(4, 1).Value = "Corp or Windows"
ActiveCell.Offset(5, 1).Value = "Mcafee"
ActiveCell.Offset(6, 1).Value = "Token"
ActiveCell.Offset(7, 1).Value = "Host or ipass"
ActiveCell.Offset(8, 1).Value = "X accounts"
ActiveCell.Offset(9, 1).Value = "Others"
ActiveCell.Offset(11, 1).Value = "Total"
ActiveCell.Offset(3, -1).Value = "Percent"
ActiveCell.Offset(4, -1).Value = count_of_corp_or_windows / count_of_all
ActiveCell.Offset(5, -1).Value = count_of_mcafee / count_of_all
ActiveCell.Offset(6, -1).Value = count_of_token / count_of_all
ActiveCell.Offset(7, -1).Value = count_of_host_or_ipass / count_of_all
ActiveCell.Offset(8, -1).Value = count_of_X / count_of_all
ActiveCell.Offset(9, -1).Value = count_of_others / count_of_all
End Sub


问:
Display user profile url by name instead of ID
I am Newbie. I'm trying to return a view of member profile

At the moment, the user profile is accessible by its ID, like so

profile/7

I would like to access it through the name that I've created

profile/John

this is my route

```<code>Route::get('profile/{id}', 'ProfilController@tampilkanID');
</code>```

this is my controller

```<code>public function tampilkanID($id)
{
    $auth = Auth::user()->id;
    $users=\App\users::all()->whereNotIn('id',$auth);
    $tampilkan = Users::find($id);
    return view('tampilkan', compact('tampilkan', 'users'));
}
</code>```

and this how i call it in my blade

```<code> @foreach($users as $user)
           <tr>
               <td><a id="teamname" href="{{ url('profile',$user->id) }}" target="_blank">{{$user->name}}</a></td>
              </tr>
 @endforeach
</code>```

thank you

答:
try this:

Route:

```<code>Route::any('profile/{name}', 'ProfilController@index')->name('profile.index');
</code>```

Controller:

```<code>public function index(Request $request, $name)
{
    $user = User::where('name', $name)->first();
    if(isset($user))
        return view('tampilkan', ['user' => $user]);
    return "user not found!";
}
</code>```

Blade:

```<code>@foreach($users as $user)
    <tr>
        <td><a id="teamname" href="{{ route('profile.index',['name' => $user->name]) }}" target="_blank">{{$user->name}}</a></td>
    </tr>
 @endforeach
</code>```

Suggestion:

if you're doing this, you should also set "name" column to "unique" in users table in order to get exactly one user each time and not confuse users to each other.

Body:
I am Newbie. I'm trying to return a view of member profile

At the moment, the user profile is accessible by its ID, like so

profile/7

I would like to access it through the name that I've created

profile/John

this is my route

Route::get('profile/{id}', 'ProfilController@tampilkanID');

this is my controller

public function tampilkanID($id)
{
    $auth = Auth::user()->id;
    $users=\App\users::all()->whereNotIn('id',$auth);
    $tampilkan = Users::find($id);
    return view('tampilkan', compact('tampilkan', 'users'));
}

and this how i call it in my blade

 @foreach($users as $user)

               id) }}" target="_blank">{{$user->name}}

 @endforeach

thank you

Body:
try this:

Route:

Route::any('profile/{name}', 'ProfilController@index')->name('profile.index');

Controller:

public function index(Request $request, $name)
{
    $user = User::where('name', $name)->first();
    if(isset($user))
        return view('tampilkan', ['user' => $user]);
    return "user not found!";
}

Blade:

@foreach($users as $user)
    <tr>
        <td><a id="teamname" href="{{ route('profile.index',['name' => $user->name]) }}" target="_blank">{{$user->name}}</a></td>
    </tr>
 @endforeach

Suggestion:

if you're doing this, you should also set "name" column to "unique" in users table in order to get exactly one user each time and not confuse users to each other.


答:
Your POJO class is wrong

Try this

```<code>public class Products_Main
{
  @SerializedName("current_page")
  int current_page;

  @SerializedName("data")
  private List<Product> products;

  public int getCurrent_page() {
    return current_page;
  }

  public void setCurrent_page(int current_page) {
    this.current_page = current_page;
  }

  public List<Product> getProducts() {
    return products;
  }

  public void setProducts(List<Product> products) {
    this.products = products;
  }
}
</code>```

and

```<code>class Product {

    @SerializedName("id")
    private int id;

    @SerializedName("price")
    int price;

    @SerializedName("discount")
    int discount;

    @SerializedName("name")
    private String name;

    @SerializedName("image")
    private String image;

    @SerializedName("description")
    private String description;

    @SerializedName("discount_type")
    private String discount_type;

    @SerializedName("discount_exp")
    private String discount_exp;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getDiscount() {
        return discount;
    }

    public void setDiscount(int discount) {
        this.discount = discount;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDiscount_type() {
        return discount_type;
    }

    public void setDiscount_type(String discount_type) {
        this.discount_type = discount_type;
    }

    public String getDiscount_exp() {
        return discount_exp;
    }

    public void setDiscount_exp(String discount_exp) {
        this.discount_exp = discount_exp;
    }
}
</code>```

Title: null response usin Retrofit Library in android

Body:
Your POJO class is wrong

Try this

public class Products_Main
{
  @SerializedName("current_page")
  int current_page;

  @SerializedName("data")
  private List<Product> products;

  public int getCurrent_page() {
    return current_page;
  }

  public void setCurrent_page(int current_page) {
    this.current_page = current_page;
  }

  public List<Product> getProducts() {
    return products;
  }

  public void setProducts(List<Product> products) {
    this.products = products;
  }
}

and

class Product {

    @SerializedName("id")
    private int id;

    @SerializedName("price")
    int price;

    @SerializedName("discount")
    int discount;

    @SerializedName("name")
    private String name;

    @SerializedName("image")
    private String image;

    @SerializedName("description")
    private String description;

    @SerializedName("discount_type")
    private String discount_type;

    @SerializedName("discount_exp")
    private String discount_exp;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getDiscount() {
        return discount;
    }

    public void setDiscount(int discount) {
        this.discount = discount;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDiscount_type() {
        return discount_type;
    }

    public void setDiscount_type(String discount_type) {
        this.discount_type = discount_type;
    }

    public String getDiscount_exp() {
        return discount_exp;
    }

    public void setDiscount_exp(String discount_exp) {
        this.discount_exp = discount_exp;
    }
}


问:
How can I output a UTF-8 CSV in PHP that Excel will read properly?
I've got this very simple thing that just outputs some stuff in CSV format, but it's got to be UTF-8. I open this file in TextEdit or TextMate or Dreamweaver and it displays UTF-8 characters properly, but if I open it in Excel it's doing this silly íÄ kind of thing instead. Here's what I've got at the head of my document:

```<code>header("content-type:application/csv;charset=UTF-8");
header("Content-Disposition:attachment;filename=\"CHS.csv\"");
</code>```

This all seems to have the desired effect except Excel (Mac, 2008) doesn't want to import it properly. There's no options in Excel for me to "open as UTF-8" or anything, so … I'm getting a little annoyed.

I can't seem to find any clear solutions to this anywhere, despite a lot of people having the same problem. The thing I see the most is to include the BOM, but I can't exactly figure out how to do that. As you can see above I'm just echoing this data, I'm not writing any file. I can do that if I need to, I'm just not because there doesn't seem like a need for it at this point. Any help?

Update: I tried echoing the BOM as echo pack("CCC", 0xef, 0xbb, 0xbf); which I just pulled from a site that was trying to detect the BOM. But Excel just appends those three characters to the very first cell when it imports, and still messes up the special characters.

答:
I just dealt with the same problem, and came up with two solutions.

Use the PHPExcel class  as suggested by bpeterson76.

Using this class generates the most widely compatible file, I was able to generate a file from UTF-8 encoded data that opened fine in Excel 2008 Mac, Excel 2007 Windows, and Google Docs.

The biggest problem with using PHPExcel is that it's slow and uses a lot of memory, which isn't an issue for reasonably sized files, but if your Excel/CSV file has hundreds or thousands of rows, this library becomes unusable.

Here is a PHP method that will take some TSV data and output an Excel file to the browser, note that it uses the Excel5 Writer, which means the file should be compatible with older versions of Excel, but I no longer have access to any, so I cannot test them.

```<code>function excel_export($tsv_data, $filename) {
    $export_data = preg_split("/\n/", $tsv_data);
    foreach($export_data as &$row) {
        $row = preg_split("/\t/", $row);
    }

    include("includes/PHPExcel.php");
    include('includes/PHPExcel/Writer/Excel5.php');

    $objPHPExcel = new PHPExcel();

    $objPHPExcel->setActiveSheetIndex(0);
    $sheet = $objPHPExcel->getActiveSheet();
    $row = '1';
    $col = "A";
    foreach($export_data as $row_cells) {
        if(!is_array($row_cells)) { continue; }
            foreach($row_cells as $cell) {
                $sheet->setCellValue($col.$row, $cell);
                $col++;
            }
        $row += 1;
        $col = "A";
    }

    $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
    header('Cache-Control: max-age=0');
    $objWriter->save('php://output');
    exit;
}
</code>```

Because of the efficiency issues with PHPExcel, I also had to figure out how to generate a UTF-8 & Excel compatible CSV or TSV file.

The best I could come up with was a file that was compatible with Excel 2008 Mac, and Excel 2007 PC, but not Google Docs, which is good enough for my application.

I found the solution here, specifically, this answer, but you should also read the accepted answer as it explains the problem.

Here is the PHP code I used, note that I am using tsv data (tabs as delimiters instead of commas):

```<code>header ( 'HTTP/1.1 200 OK' );
header ( 'Date: ' . date ( 'D M j G:i:s T Y' ) );
header ( 'Last-Modified: ' . date ( 'D M j G:i:s T Y' ) );
header ( 'Content-Type: application/vnd.ms-excel') ;
header ( 'Content-Disposition: attachment;filename=export.csv' );
print chr(255) . chr(254) . mb_convert_encoding($tsv_data, 'UTF-16LE', 'UTF-8');
exit;
</code>```

Body:
I've got this very simple thing that just outputs some stuff in CSV format, but it's got to be UTF-8. I open this file in TextEdit or TextMate or Dreamweaver and it displays UTF-8 characters properly, but if I open it in Excel it's doing this silly íÄ kind of thing instead. Here's what I've got at the head of my document:

header("content-type:application/csv;charset=UTF-8");
header("Content-Disposition:attachment;filename=\"CHS.csv\"");

This all seems to have the desired effect except Excel (Mac, 2008) doesn't want to import it properly. There's no options in Excel for me to "open as UTF-8" or anything, so … I'm getting a little annoyed.

I can't seem to find any clear solutions to this anywhere, despite a lot of people having the same problem. The thing I see the most is to include the BOM, but I can't exactly figure out how to do that. As you can see above I'm just echoing this data, I'm not writing any file. I can do that if I need to, I'm just not because there doesn't seem like a need for it at this point. Any help?

Update: I tried echoing the BOM as echo pack("CCC", 0xef, 0xbb, 0xbf); which I just pulled from a site that was trying to detect the BOM. But Excel just appends those three characters to the very first cell when it imports, and still messes up the special characters.

Body:
I just dealt with the same problem, and came up with two solutions.

Use the PHPExcel class  as suggested by bpeterson76.

Using this class generates the most widely compatible file, I was able to generate a file from UTF-8 encoded data that opened fine in Excel 2008 Mac, Excel 2007 Windows, and Google Docs.

The biggest problem with using PHPExcel is that it's slow and uses a lot of memory, which isn't an issue for reasonably sized files, but if your Excel/CSV file has hundreds or thousands of rows, this library becomes unusable.

Here is a PHP method that will take some TSV data and output an Excel file to the browser, note that it uses the Excel5 Writer, which means the file should be compatible with older versions of Excel, but I no longer have access to any, so I cannot test them.

function excel_export($tsv_data, $filename) {
    $export_data = preg_split("/\n/", $tsv_data);
    foreach($export_data as &$row) {
        $row = preg_split("/\t/", $row);
    }

    include("includes/PHPExcel.php");
    include('includes/PHPExcel/Writer/Excel5.php');

    $objPHPExcel = new PHPExcel();

    $objPHPExcel->setActiveSheetIndex(0);
    $sheet = $objPHPExcel->getActiveSheet();
    $row = '1';
    $col = "A";
    foreach($export_data as $row_cells) {
        if(!is_array($row_cells)) { continue; }
            foreach($row_cells as $cell) {
                $sheet->setCellValue($col.$row, $cell);
                $col++;
            }
        $row += 1;
        $col = "A";
    }

    $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
    header('Cache-Control: max-age=0');
    $objWriter->save('php://output');
    exit;
}

Because of the efficiency issues with PHPExcel, I also had to figure out how to generate a UTF-8 & Excel compatible CSV or TSV file.

The best I could come up with was a file that was compatible with Excel 2008 Mac, and Excel 2007 PC, but not Google Docs, which is good enough for my application.

I found the solution here, specifically, this answer, but you should also read the accepted answer as it explains the problem.

Here is the PHP code I used, note that I am using tsv data (tabs as delimiters instead of commas):

header ( 'HTTP/1.1 200 OK' );
header ( 'Date: ' . date ( 'D M j G:i:s T Y' ) );
header ( 'Last-Modified: ' . date ( 'D M j G:i:s T Y' ) );
header ( 'Content-Type: application/vnd.ms-excel') ;
header ( 'Content-Disposition: attachment;filename=export.csv' );
print chr(255) . chr(254) . mb_convert_encoding($tsv_data, 'UTF-16LE', 'UTF-8');
exit;


答:
Any null data happens when the parsing failed.

This is the Java for the response you've shown

```<code>public class ProductResponse {
    ProductPage products;
}

public class ProductPage {
    int current_page;

    @SerializedName("data")
    private List<Product> products;
}

public class Product {
  private int id,price,discount;
  private String name,image,description,discount_type,discount_exp;

  public Product() { }

}
</code>```

Body:
Here is my JSONArray Response from Web service:

And Class Java :

public class Product {

  private int id,price,discount;
  private String name,image,description,discount_type,discount_exp;

  @SerializedName("products")
  private List<Product> products;

  public Product()
  {

  }

}

response is null

Body:
Any null data happens when the parsing failed.

This is the Java for the response you've shown

public class ProductResponse {
    ProductPage products;
}

public class ProductPage {
    int current_page;

    @SerializedName("data")
    private List<Product> products;
}

public class Product {
  private int id,price,discount;
  private String name,image,description,discount_type,discount_exp;

  public Product() { }

}


答: Open AVD Manager and click on Edit option on that particular emulator. Then click on Enable Keyboard input option. Now you are good to give input through laptop's keyboard

Title: Laptop Keyboard isn't detected by Emulator in Android Studio

Body:
My Android Studio Emulator is not getting input from Laptop Keyboard. This was never happened before as i was working for more than 2 months. Now i can't give input from my laptop keyboard to emulator. i m using NEXUS 5X API 26 Emulator. Kindly let me know how to unlock laptop keyboard in android Emulator??..
Thanks in advance


问:
this.props.xyz is not a function when child calls parent
Currently, I have a small issue, where when using a callback function from one child component, everything renders fine, and on the other, it doesn't work.

Here is the code:

App.js

export default class App extends Component {
  constructor(props) {
    super(props);
    this.loggedInCallback = this.loggedInCallback.bind(this);
    this.renderApplicationContent = this.renderApplicationContent.bind(this);
    this.state = {
      loggedIn: false,
      user: null
    }
  }

  loggedInCallback = (status, user = null) => {
    this.setState({
      loggedIn: status,
      user: user
    })
  }

  renderApplicationContent = () => {
    if (this.state.loggedIn === false) {
      return <LoginForm updateLoginStatus={this.loggedInCallback} />
    } else {
      return <UserData updateLoginStatus-={this.loggedInCallback} user={this.state.user} />;
    }
  }

  render() {
    return (

Welcome to Impact

          {this.renderApplicationContent()}

    );
  }
}```
</div>
</div>
</p>

<p><strong>UserData.js</strong></p>

<p>This is where I get this error: https://screenshot.click/03-31-21ut0-rxzrk.jpg</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { Component } from 'react';
import './UserData.css';

export default class UserData extends Component {
  render() {
    return (
      <div>
        <button onClick={this.props.updateLoginStatus(false)}>
          Logout
        </button>
        <div>
          ID: {this.props.user}
        </div>
      </div>
    )
  }
}</code>```

I'm not 100% sure what's causing this error. I thought it was a binding error, and perhaps it still is, but I can't seem to figure out where the lack of binding is causing the issue. I am running into no errors when using the same thing on the LoginForm component, and that's doing pretty much everything identically.

答:
```<code>return <UserData updateLoginStatus-={this.loggedInCallback} user={this.state.user} />;
                                  ^ remove this dash
</code>```

Also in

```<code><button onClick={this.props.updateLoginStatus(false)}>
</code>```

You probably want to pass a function that runs updateLoginStatus as opposed to running it at render time, so pass in an arrow function:

```<code><button onClick={() => this.props.updateLoginStatus(false)}>
</code>```

Body:
Currently, I have a small issue, where when using a callback function from one child component, everything renders fine, and on the other, it doesn't work.

Here is the code:

App.js

export default class App extends Component {
  constructor(props) {
    super(props);
    this.loggedInCallback = this.loggedInCallback.bind(this);
    this.renderApplicationContent = this.renderApplicationContent.bind(this);
    this.state = {
      loggedIn: false,
      user: null
    }
  }

  loggedInCallback = (status, user = null) => {
    this.setState({
      loggedIn: status,
      user: user
    })
  }

  renderApplicationContent = () => {
    if (this.state.loggedIn === false) {
      return <LoginForm updateLoginStatus={this.loggedInCallback} />
    } else {
      return <UserData updateLoginStatus-={this.loggedInCallback} user={this.state.user} />;
    }
  }

  render() {
    return (

Welcome to Impact

          {this.renderApplicationContent()}

    );
  }
}

UserData.js

This is where I get this error: https://screenshot.click/03-31-21ut0-rxzrk.jpg

import React, { Component } from 'react';
import './UserData.css';

export default class UserData extends Component {
  render() {
    return (

        <button onClick={this.props.updateLoginStatus(false)}>
          Logout
        </button>

          ID: {this.props.user}

    )
  }
}

I'm not 100% sure what's causing this error. I thought it was a binding error, and perhaps it still is, but I can't seem to figure out where the lack of binding is causing the issue. I am running into no errors when using the same thing on the LoginForm component, and that's doing pretty much everything identically.

Body:
return <UserData updateLoginStatus-={this.loggedInCallback} user={this.state.user} />;
                                  ^ remove this dash

Also in

<button onClick={this.props.updateLoginStatus(false)}>

You probably want to pass a function that runs updateLoginStatus as opposed to running it at render time, so pass in an arrow function:

<button onClick={() => this.props.updateLoginStatus(false)}>


问:
DocumentDB JavaScript API: queryDatabases is not a function
I am creating a service for Azure Functions written in JavaScript/Node.js and I am getting the below error when attempting to access the function DocumentClient.queryDatabases. I have the correct references installed in Visual Studio Code and through Intellisense can see the queryDatabases method through the following:

```<code>var client = require('documentdb').DocumentClient;
client.queryDatabases(...);
</code>```

Any ideas why the debugger is blowing up with the error?

```<code>Exception has occurred: TypeError
TypeError: client.queryDatabases is not a function
    at Object.getOrCreateDatabase (/Users/.../Documents/.../UserModel.js:23:16)
    at Object.<anonymous> (/Users/.../Documents/.../Test.js:5:11)
    at Module._compile (module.js:638:14)
    at Object.Module._extensions..js (module.js:652:10)
    at Module.load (module.js:560:32)
    at tryModuleLoad (module.js:503:12)
    at Function.Module._load (module.js:495:3)
    at Function.Module.runMain (module.js:682:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:613:3
</code>```

答:
First, you need to initialize the client with your DocumentDB host and auth key. And then call the function via this client.

Example:

```<code>var DocumentDBClient = require("documentdb").DocumentClient;

var endpoint = '<host>';
var primaryKey = '<authKey>';
var client = new DocumentDBClient(endpoint, { masterKey: primaryKey });

var querySpec = {
    query: 'SELECT * FROM root r WHERE  r.id = @id',
    parameters: [
        {
            name: '@id',
            value: databaseId
        }
    ]
};

client.queryDatabases(querySpec).toArray(function (err, results) {
    if(err) return console.log(err);
    console.log(results);
});
</code>```

Body:
I am creating a service for Azure Functions written in JavaScript/Node.js and I am getting the below error when attempting to access the function DocumentClient.queryDatabases. I have the correct references installed in Visual Studio Code and through Intellisense can see the queryDatabases method through the following:

var client = require('documentdb').DocumentClient;
client.queryDatabases(...);

Any ideas why the debugger is blowing up with the error?

Exception has occurred: TypeError
TypeError: client.queryDatabases is not a function
    at Object.getOrCreateDatabase (/Users/.../Documents/.../UserModel.js:23:16)
    at Object.<anonymous> (/Users/.../Documents/.../Test.js:5:11)
    at Module._compile (module.js:638:14)
    at Object.Module._extensions..js (module.js:652:10)
    at Module.load (module.js:560:32)
    at tryModuleLoad (module.js:503:12)
    at Function.Module._load (module.js:495:3)
    at Function.Module.runMain (module.js:682:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:613:3

Body:
First, you need to initialize the client with your DocumentDB host and auth key. And then call the function via this client.

Example:

var DocumentDBClient = require("documentdb").DocumentClient;

var endpoint = '<host>';
var primaryKey = '<authKey>';
var client = new DocumentDBClient(endpoint, { masterKey: primaryKey });

var querySpec = {
    query: 'SELECT * FROM root r WHERE  r.id = @id',
    parameters: [
        {
            name: '@id',
            value: databaseId
        }
    ]
};

client.queryDatabases(querySpec).toArray(function (err, results) {
    if(err) return console.log(err);
    console.log(results);
});


答:
You have a typo on your code:

```<code>return <UserData updateLoginStatus-={this.loggedInCallback} user={this.state.user} />;
</code>```

Remove the - sign, make it:

```<code>return <UserData updateLoginStatus={this.loggedInCallback} user={this.state.user} />;
</code>```

Title: this.props.xyz is not a function when child calls parent

Body:
You have a typo on your code:

return <UserData updateLoginStatus-={this.loggedInCallback} user={this.state.user} />;

Remove the - sign, make it:

return <UserData updateLoginStatus={this.loggedInCallback} user={this.state.user} />;


问:
Are parentheses around the result significant in a return statement?
Is there a difference between these two statements inside a function?

```<code>bool returnValue = true;
// Code that does something
return(returnValue);
</code>```

and this?

```<code>bool returnValue = true;
// Code
return returnValue;
</code>```

The former has parentheses around returnValue.

答:
The parenthesis on the upper example are superfluous; they are effectively ignored.

It would be the same as something like...

```<code>int x = (5);
</code>```

The parenthesis here are ignored as well.

Body:
Is there a difference between these two statements inside a function?

bool returnValue = true;
// Code that does something
return(returnValue);

and this?

bool returnValue = true;
// Code
return returnValue;

The former has parentheses around returnValue.

Body:
The parenthesis on the upper example are superfluous; they are effectively ignored.

It would be the same as something like...

int x = (5);

The parenthesis here are ignored as well.


问:
Recyclerview not call onCreateViewHolder
My RecyclerView does not call onCreateViewHolder, onBindViewHolder even MenuViewHolder constructor, therefore nothing appears in RecyclerView.
I put logs for debugging, and no log is shown.
What might be the problem?

My adapter:

public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.MenuViewHolder> {
private LayoutInflater inflater;
List<Menu> data = Collections.emptyList();

public MenuAdapter(Context context, List<Menu> data) {
    Log.i("DEBUG", "Constructor");
    inflater = LayoutInflater.from(context);
    Log.i("DEBUG MENU - CONSTRUCTOR", inflater.toString());
    this.data = data;
    for(Menu menu: this.data){
        Log.i("DEBUG MENU - CONSTRUCTOR", menu.menu);
    }
}

@Override
public MenuViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.row_menu, parent, false);
    MenuViewHolder holder = new MenuViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(MenuViewHolder holder, int position) {
    Log.i("DEBUG MENU", "onBindViewHolder");
    Menu current = data.get(position);
    holder.title.setText(current.menu);
}

@Override
public int getItemCount() {
    return 0;
}

class MenuViewHolder extends RecyclerView.ViewHolder {
    TextView title;
    ImageView icon;

    public MenuViewHolder(View itemView) {
        super(itemView);
        title = (TextView) itemView.findViewById(R.id.menuText);
    }
}
```

<p>My custom row XML:</p>

<pre class="lang-xml prettyprint-override"><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/menuText"
    android:text="Dummy Text"
    android:layout_gravity="center_vertical"
    android:textColor="#222"/>
</code>```

and my Fragment:

public NavigationFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
    if (savedInstanceState != null) {
        mFromSavedInstaceState = true;
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View view = inflater.inflate(R.layout.fragment_navigation, container, false);
    RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.drawer_list);
    MenuAdapter adapter = new MenuAdapter(getActivity(), getData());
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setAdapter(adapter);
    return view;
}
```

答:
Please do the following thing   </p>

```<code>@Override
public int getItemCount() {
    return data.size();
}
</code>```

Body:
My RecyclerView does not call onCreateViewHolder, onBindViewHolder even MenuViewHolder constructor, therefore nothing appears in RecyclerView.
I put logs for debugging, and no log is shown.
What might be the problem?

My adapter:

public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.MenuViewHolder> {
private LayoutInflater inflater;
List<Menu> data = Collections.emptyList();

public MenuAdapter(Context context, List<Menu> data) {
    Log.i("DEBUG", "Constructor");
    inflater = LayoutInflater.from(context);
    Log.i("DEBUG MENU - CONSTRUCTOR", inflater.toString());
    this.data = data;
    for(Menu menu: this.data){
        Log.i("DEBUG MENU - CONSTRUCTOR", menu.menu);
    }
}

@Override
public MenuViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.row_menu, parent, false);
    MenuViewHolder holder = new MenuViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(MenuViewHolder holder, int position) {
    Log.i("DEBUG MENU", "onBindViewHolder");
    Menu current = data.get(position);
    holder.title.setText(current.menu);
}

@Override
public int getItemCount() {
    return 0;
}

class MenuViewHolder extends RecyclerView.ViewHolder {
    TextView title;
    ImageView icon;

    public MenuViewHolder(View itemView) {
        super(itemView);
        title = (TextView) itemView.findViewById(R.id.menuText);
    }
}

My custom row XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/menuText"
    android:text="Dummy Text"
    android:layout_gravity="center_vertical"
    android:textColor="#222"/>

and my Fragment:

public NavigationFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
    if (savedInstanceState != null) {
        mFromSavedInstaceState = true;
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View view = inflater.inflate(R.layout.fragment_navigation, container, false);
    RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.drawer_list);
    MenuAdapter adapter = new MenuAdapter(getActivity(), getData());
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setAdapter(adapter);
    return view;
}

Body:
Please do the following thing

@Override
public int getItemCount() {
    return data.size();
}


问:
Cosine similarity with BigQuery SQL?
I have vectors stored in BigQuery (see How can I compute TF/IDF with SQL (BigQuery)), and I want to find the most similar between them. How can I compute the cosine similarity with BigQuery standard SQL?</p>

答:
This query looks at the vector defined for each doc, given its dimensions (by word) and multiplies them with the cosine distance formula:

```<code>#standardSQL
SELECT ANY_VALUE(title2) orig, ANY_VALUE(tf2id) id_orig, a.id id_similar
  , ROUND(SAFE_DIVIDE( SUM(b.tf_idf * IFNULL(c.tf_idf,0)),(SQRT(SUM(b.tf_idf*b.tf_idf))*SQRT(SUM(POW(IFNULL(c.tf_idf,0),2))))),4) distance
  , ANY_VALUE(title1) similar
  , ARRAY_AGG((ROUND(b.tf_idf,4), ROUND(c.tf_idf,4))) weights
  , ARRAY_AGG((b.word, c.word)) words
FROM (
  SELECT id, tfidfs tf1, tf2, tf2id
  , a.title title1
  , b.title title2
  FROM `fh-bigquery.stackoverflow.tf_idf_experiment_3` a
  CROSS JOIN (
    SELECT tfidfs tf2, id tf2id, title
    FROM `fh-bigquery.stackoverflow.tf_idf_experiment_3`
    WHERE id = 11353679
    LIMIT 1
  ) b
) a
, UNNEST(tf1) b LEFT JOIN UNNEST(tf2) c ON b.word=c.word
GROUP BY id
ORDER BY distance DESC
</code>```

First result is the same document, proving that we get distance 1 on itself:

Second result:

Etc:

Caveat: This SQL code does a LEFT JOIN, so we only get nulls for words on the left document not on the right, and not the opposite.

Title: Cosine similarity with BigQuery SQL?

Body:
This query looks at the vector defined for each doc, given its dimensions (by word) and multiplies them with the cosine distance formula:

#standardSQL
SELECT ANY_VALUE(title2) orig, ANY_VALUE(tf2id) id_orig, a.id id_similar
  , ROUND(SAFE_DIVIDE( SUM(b.tf_idf * IFNULL(c.tf_idf,0)),(SQRT(SUM(b.tf_idf*b.tf_idf))*SQRT(SUM(POW(IFNULL(c.tf_idf,0),2))))),4) distance
  , ANY_VALUE(title1) similar
  , ARRAY_AGG((ROUND(b.tf_idf,4), ROUND(c.tf_idf,4))) weights
  , ARRAY_AGG((b.word, c.word)) words
FROM (
  SELECT id, tfidfs tf1, tf2, tf2id
  , a.title title1
  , b.title title2
  FROM `fh-bigquery.stackoverflow.tf_idf_experiment_3` a
  CROSS JOIN (
    SELECT tfidfs tf2, id tf2id, title
    FROM `fh-bigquery.stackoverflow.tf_idf_experiment_3`
    WHERE id = 11353679
    LIMIT 1
  ) b
) a
, UNNEST(tf1) b LEFT JOIN UNNEST(tf2) c ON b.word=c.word
GROUP BY id
ORDER BY distance DESC

First result is the same document, proving that we get distance 1 on itself:

Second result:

Etc:

Caveat: This SQL code does a LEFT JOIN, so we only get nulls for words on the left document not on the right, and not the opposite.


问:
Optimising the ASP.NET Core release bundle
I have published a .net core 2.0 api bundle with

```<code>dotnet publish -c release
</code>```

The release folder includes a bunch of DLL's that I didn't think would be required for running the application, ie, code generation packages etc.

Is there a way to optimise the release package so that these dll's aren't included?

```<code>Microsoft.CodeAnalysis.CSharp.Workspaces.dll
Microsoft.CodeAnalysis.Workspaces.dll
Microsoft.EntityFrameworkCore.Relational.Design.dll
Microsoft.EntityFrameworkCore.SqlServer.Design.dll
Microsoft.VisualStudio.Web.CodeGeneration.Contracts.dll
Microsoft.VisualStudio.Web.CodeGeneration.Core.dll
Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.dll
Microsoft.VisualStudio.Web.CodeGeneration.Templating.dll
Microsoft.VisualStudio.Web.CodeGeneration.Utils.dll
Microsoft.VisualStudio.Web.CodeGeneration.dll
Microsoft.VisualStudio.Web.CodeGenerators.Mvc.dll
NuGet.Frameworks.dll
System.Composition.AttributedModel.dll
System.Composition.Convention.dll
System.Composition.Hosting.dll
System.Composition.Runtime.dll
System.Composition.TypedParts.dll
dotnet-aspnet-codegenerator-design.dll
</code>```

My csproj file:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <Folder Include="Models\" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.3" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.1" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.1" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.1" />
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.1" />
    <DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="2.0.0" />
  </ItemGroup>
</Project>
</code>```

答:
Yes.  Install the Microsoft.Packaging.Tools.Trimming NuGet package.  Then add this to your .csproj file:

```<code><PropertyGroup>
  <TrimUnusedDependencies>true</TrimUnusedDependencies>
</PropertyGroup>
</code>```

Or use the /p:TrimUnusedDependencies=true flag from the command line.

```<code>dotnet build /p:TrimUnusedDependencies=true
dotnet publish /p:TrimUnusedDependencies=true
msbuild /p:TrimUnusedDependencies=true
msbuild /t:Publish /p:TrimUnusedDependencies=true
</code>```

See Dependency Trimming documentation.

Body:
I have published a .net core 2.0 api bundle with

dotnet publish -c release

The release folder includes a bunch of DLL's that I didn't think would be required for running the application, ie, code generation packages etc.

Is there a way to optimise the release package so that these dll's aren't included?

Microsoft.CodeAnalysis.CSharp.Workspaces.dll
Microsoft.CodeAnalysis.Workspaces.dll
Microsoft.EntityFrameworkCore.Relational.Design.dll
Microsoft.EntityFrameworkCore.SqlServer.Design.dll
Microsoft.VisualStudio.Web.CodeGeneration.Contracts.dll
Microsoft.VisualStudio.Web.CodeGeneration.Core.dll
Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.dll
Microsoft.VisualStudio.Web.CodeGeneration.Templating.dll
Microsoft.VisualStudio.Web.CodeGeneration.Utils.dll
Microsoft.VisualStudio.Web.CodeGeneration.dll
Microsoft.VisualStudio.Web.CodeGenerators.Mvc.dll
NuGet.Frameworks.dll
System.Composition.AttributedModel.dll
System.Composition.Convention.dll
System.Composition.Hosting.dll
System.Composition.Runtime.dll
System.Composition.TypedParts.dll
dotnet-aspnet-codegenerator-design.dll

My csproj file:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <Folder Include="Models\" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.3" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.1" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.1" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.1" />
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.1" />
    <DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="2.0.0" />
  </ItemGroup>
</Project>

Body:
Yes.  Install the Microsoft.Packaging.Tools.Trimming NuGet package.  Then add this to your .csproj file:

<PropertyGroup>
  <TrimUnusedDependencies>true</TrimUnusedDependencies>
</PropertyGroup>

Or use the /p:TrimUnusedDependencies=true flag from the command line.

dotnet build /p:TrimUnusedDependencies=true
dotnet publish /p:TrimUnusedDependencies=true
msbuild /p:TrimUnusedDependencies=true
msbuild /t:Publish /p:TrimUnusedDependencies=true

See Dependency Trimming documentation.


问:
How do I set up index.html as top level page for my Github Pages page?
I created a plain static website and deployed it on username.github.io However, whenever I try to access the website, I have to use the direct path to my HTML index.html file to see the site.

Is it possible to set username.github.io to display the index file? Go directly to username.github.io vs username.github.io/index?

thanks in advance

答:
The official documentation is quite clear

```<code>cd username.github.io
echo "My Page" > index.html
git add index.html
git commit -a -m "First pages commit"
git push origin master
</code>```

Note that since Dec. 2016, a README would be enough if you do't have an index.html file.

Body:
The official documentation is quite clear

cd username.github.io
echo "My Page" > index.html
git add index.html
git commit -a -m "First pages commit"
git push origin master

Note that since Dec. 2016, a README would be enough if you do't have an index.html file.


问:
django rest framework nested filter
I want to get all the "Registro_Entrada" and filter them by "Entrante" when "fk_tipo_entrante" is equal to "2".

On VIEWS.py I have:

```<code>class GetPersonalEntranteRegistro_EntradaAPIView(generics.ListAPIView):
    serializer_class = Registro_EntradaNestedSerializer
    def get_queryset(self):
        entrante = Entrante.objects.all().filter(fk_tipo_entrante=2)
        registro = Registro_Entrada.objects.filter(fk_entrante = entrante.pk)
        return registro
</code>```

On SERIALIZERS.py I have:

```<code>class Registro_EntradaNestedSerializer(serializers.ModelSerializer):
    fk_tarifa = TarifaSerializer(many=False)
    fk_entrante = EntranteNestedSerializer(many=False)
    class Meta:
        model = Registro_Entrada
        fields = ('_all_')
</code>```

On MODELS.py I have:

```<code>class Entrante(models.Model):
    fk_credencial = models.ForeignKey(Credencial,related_name='credencial_entrada',on_delete=models.CASCADE)
    fk_placa = models.ForeignKey(Placa, related_name='credencial_placa',on_delete=models.CASCADE)
    fk_tipo_entrante = models.ForeignKey(Tipo_Entrante,related_name='entrante_tipo',on_delete=models.CASCADE)
    fk_persona = models.ForeignKey(Persona,related_name='entrante_persona',on_delete=models.CASCADE)
    estatus = models.IntegerField(default=1)

class Registro_Entrada(models.Model):
    fecha_entrada = models.DateTimeField(auto_now_add=True)
    fecha_salida = models.DateTimeField(null=True)
    fk_tarifa = models.ForeignKey(Tarifa,related_name='registro_tarifa',on_delete=models.CASCADE)
    fk_entrante = models.ForeignKey(Entrante,related_name='regitro_entrante',on_delete=models.CASCADE)
    costo = models.DecimalField(decimal_places=2, max_digits=50)
    saldo = models.DecimalField(decimal_places=2,max_digits=50)
    estatus = models.IntegerField(default=1)
</code>```

It shows the following error:

'QuerySet' object has no attribute 'pk'

答:
You probably have problem here:

```<code>def get_queryset(self):
    entrante = Entrante.objects.all().filter(fk_tipo_entrante=2)
    registro = Registro_Entrada.objects.filter(fk_entrante = entrante.pk) # this line
</code>```

entrante is a queryset. So it does not have pk attribute. So you can try like this:

```<code>def get_queryset(self):
     entrante = Entrante.objects.all().filter(fk_tipo_entrante=2)
     if entrante.exists():
         _entrante = entrante.first() # Or you can use `.get()` method of django queryset
         registro = Registro_Entrada.objects.filter(fk_entrante = _entrante.pk)
     else:
        registro = Registro_Entrada.objects.none() # Or .all() , or any logic you want
</code>```

Title: django rest framework nested filter

Body:
I want to get all the "Registro_Entrada" and filter them by "Entrante" when "fk_tipo_entrante" is equal to "2".

On VIEWS.py I have:

class GetPersonalEntranteRegistro_EntradaAPIView(generics.ListAPIView):
    serializer_class = Registro_EntradaNestedSerializer
    def get_queryset(self):
        entrante = Entrante.objects.all().filter(fk_tipo_entrante=2)
        registro = Registro_Entrada.objects.filter(fk_entrante = entrante.pk)
        return registro

On SERIALIZERS.py I have:

class Registro_EntradaNestedSerializer(serializers.ModelSerializer):
    fk_tarifa = TarifaSerializer(many=False)
    fk_entrante = EntranteNestedSerializer(many=False)
    class Meta:
        model = Registro_Entrada
        fields = ('_all_')

On MODELS.py I have:

class Entrante(models.Model):
    fk_credencial = models.ForeignKey(Credencial,related_name='credencial_entrada',on_delete=models.CASCADE)
    fk_placa = models.ForeignKey(Placa, related_name='credencial_placa',on_delete=models.CASCADE)
    fk_tipo_entrante = models.ForeignKey(Tipo_Entrante,related_name='entrante_tipo',on_delete=models.CASCADE)
    fk_persona = models.ForeignKey(Persona,related_name='entrante_persona',on_delete=models.CASCADE)
    estatus = models.IntegerField(default=1)

class Registro_Entrada(models.Model):
    fecha_entrada = models.DateTimeField(auto_now_add=True)
    fecha_salida = models.DateTimeField(null=True)
    fk_tarifa = models.ForeignKey(Tarifa,related_name='registro_tarifa',on_delete=models.CASCADE)
    fk_entrante = models.ForeignKey(Entrante,related_name='regitro_entrante',on_delete=models.CASCADE)
    costo = models.DecimalField(decimal_places=2, max_digits=50)
    saldo = models.DecimalField(decimal_places=2,max_digits=50)
    estatus = models.IntegerField(default=1)

It shows the following error:

'QuerySet' object has no attribute 'pk'

Body:
You probably have problem here:

def get_queryset(self):
    entrante = Entrante.objects.all().filter(fk_tipo_entrante=2)
    registro = Registro_Entrada.objects.filter(fk_entrante = entrante.pk) # this line

entrante is a queryset. So it does not have pk attribute. So you can try like this:

def get_queryset(self):
     entrante = Entrante.objects.all().filter(fk_tipo_entrante=2)
     if entrante.exists():
         _entrante = entrante.first() # Or you can use `.get()` method of django queryset
         registro = Registro_Entrada.objects.filter(fk_entrante = _entrante.pk)
     else:
        registro = Registro_Entrada.objects.none() # Or .all() , or any logic you want


问:
Access to a single pixel in C#
I'm working on a school project right now. It's meant to be a 3D editing software, (like a very minimized version of Maya). I have to write it in C#, using the 'Windows Application Project'.
I intend to implement all the 3D stuff myself, from projections to shading.
My question is, how can I get direct access to a single pixel in the C# windows application?
I know I'm going to have a main view port in the window. But I haven't decided yet how it will be made. Is there a built in object that I can use, that will let me define the boundaries of the view port, and then paint each pixel individually?
(I'm just shooting in the dark here, I don't know much about C#. I mostly program in C)

Thanks,
Malki.

答: Christian Graus has several good graphic-manipulation articles on www.CodeProject.com.  They should answer your questions.</p>

OwnerDisplayName: Malki

Title: Access to a single pixel in C#

OwnerDisplayName: John Fisher


答:
There are two things that are a problem in your code

First: a typo updateLoginStatus-={this.loggedInCallback} wherein instead of assignment operator you used -=. Correct that to updateLoginStatus={this.loggedInCallback}

Second: calling a function from child

```<code><button onClick={this.props.updateLoginStatus(false)}>
</code>```

it should be

```<code><button onClick={() =>this.props.updateLoginStatus(false)}>
</code>```

since, when you write onClick={this.props.updateLoginStatus(false)}, whenever the component renders onClick handler will be evaluated causing the setState in parent to be called which in turn will lead to an infinite loop. You need to assign a function to the onClick event handler

Body:
There are two things that are a problem in your code

First: a typo updateLoginStatus-={this.loggedInCallback} wherein instead of assignment operator you used -=. Correct that to updateLoginStatus={this.loggedInCallback}

Second: calling a function from child

<button onClick={this.props.updateLoginStatus(false)}>

it should be

<button onClick={() =>this.props.updateLoginStatus(false)}>

since, when you write onClick={this.props.updateLoginStatus(false)}, whenever the component renders onClick handler will be evaluated causing the setState in parent to be called which in turn will lead to an infinite loop. You need to assign a function to the onClick event handler