问:
Linux - moving files from source to destination with overwrite
Firstly I'd like to apologize if I duplicated a questions which already exists but it's too important to screw this.

I have two directories on my linux server:
 - /tmp/tmp as source
 - /var as destination

There are already like 500 txt files in /var directory and I'd like to move all my files from /tmp directory (about 200 files) to /var directory with replacing those ones which already exist with the same name but as well as not touching those ones which are not in /tmp.

Practical example:
/var files: a.txt , b.txt , c.txt , d.txt
/tmp files: a.txt , b.txt
Result: /var files: a.txt(from /tmp) , b.txt(from /tmp) , c.txt , d.txt

Not sure if mv is a proper method to do that, so thank you in advance guys! :)

答:
This can be implemented through rsync

Refer rsync manual for more information.

```<code>Local:  rsync [OPTION...] SRC... [DEST]
Access via remote shell:
  Pull: rsync [OPTION...] [USER@]HOST:SRC... [DEST]
  Push: rsync [OPTION...] SRC... [USER@]HOST:DEST
Access via rsync daemon:
  Pull: rsync [OPTION...] [USER@]HOST::SRC... [DEST]
        rsync [OPTION...] rsync://[USER@]HOST[:PORT]/SRC... [DEST]
  Push: rsync [OPTION...] SRC... [USER@]HOST::DEST
        rsync [OPTION...] SRC... rsync://[USER@]HOST[:PORT]/DEST
</code>```

For your case,

```<code>rsync -avzh /tmp/ /var/
</code>```

If you want to test it

```<code>rsync -avzh --dry-run /tmp/ /var/

-a, --archive               archive mode;
-v, --verbose               increase verbosity
-z, --compress              compress file data during the transfer
-h, --human-readable        output numbers in a human-readable format
</code>```

Detailed commentary

-v, --verbose This option increases the amount of information you are given during the transfer. By default, rsync works silently. A single
  -v will give you information about what files are being transferred and a brief summary at the end. Two -v options will give you
  information on what files are being skipped and slightly more
  information at the end. More than two -v options should only be used
  if you are debugging rsync. Note that the names of the transferred
  files that are output are done using a default --out-format of
  lq%n%Lrq, which tells you just the name of the file and, if the item
  is a link, where it points. At the single -v level of verbosity, this
  does not mention when a file gets its attributes changed. If you ask
  for an itemized list of changed attributes (either --itemize-changes
  or adding lq%irq to the --out-format setting), the output (on the
  client) increases to mention all items that are changed in any way.
  See the --out-format option for more details.

-a, --archive This is equivalent to -rlptgoD. It is a quick way of saying you want recursion and want to preserve almost everything (with
  -H being a notable omission). The only exception to the above equivalence is when --files-from is specified, in which case -r is not
  implied. Note that -a does not preserve hardlinks, because finding
  multiply-linked files is expensive. You must separately specify -H.
  --no-OPTION You may turn off one or more implied options by prefixing the option name with lqno-rq. Not all options may be prefixed with a
  lqno-rq: only options that are implied by other options (e.g. --no-D,
  --no-perms) or have different defaults in various circumstances (e.g. --no-whole-file, --no-blocking-io, --no-dirs). You may specify either the short or the long option name after the lqno-rq prefix (e.g.
  --no-R is the same as --no-relative). For example: if you want to use -a (--archive) but don't want
  -o (--owner), instead of converting -a into -rlptgD, you could specify -a --no-o (or -a --no-owner). The order of the options is important: if you specify --no-r -a, the
  -r option would end up being turned on, the opposite of -a --no-r. Note also that the side-effects of the --files-from option are NOT
  positional, as it affects the default state of several options and
  slightly changes the meaning of -a (see the --files-from option for
  more details).

-z, --compress With this option, rsync compresses the file data as it is sent to the destination machine, which reduces the amount of data
  being transmitted -- something that is useful over a slow connection.
  Note that this option typically achieves better compression ratios
  than can be achieved by using a compressing remote shell or a
  compressing transport because it takes advantage of the implicit
  information in the matching data blocks that are not explicitly sent
  over the connection.

-h, --human-readable Output numbers in a more human-readable format. This makes big numbers output using larger units, with a K, M, or G
  suffix. If this option was specified once, these units are K (1000), M
  (1000*1000), and G (1000*1000*1000); if the option is repeated, the
  units are powers of 1024 instead of 1000.

Body:
This can be implemented through rsync

Refer rsync manual for more information.

Local:  rsync [OPTION...] SRC... [DEST]
Access via remote shell:
  Pull: rsync [OPTION...] [USER@]HOST:SRC... [DEST]
  Push: rsync [OPTION...] SRC... [USER@]HOST:DEST
Access via rsync daemon:
  Pull: rsync [OPTION...] [USER@]HOST::SRC... [DEST]
        rsync [OPTION...] rsync://[USER@]HOST[:PORT]/SRC... [DEST]
  Push: rsync [OPTION...] SRC... [USER@]HOST::DEST
        rsync [OPTION...] SRC... rsync://[USER@]HOST[:PORT]/DEST

For your case,

rsync -avzh /tmp/ /var/

If you want to test it

rsync -avzh --dry-run /tmp/ /var/

-a, --archive               archive mode;
-v, --verbose               increase verbosity
-z, --compress              compress file data during the transfer
-h, --human-readable        output numbers in a human-readable format

Detailed commentary

-v, --verbose This option increases the amount of information you are given during the transfer. By default, rsync works silently. A single
  -v will give you information about what files are being transferred and a brief summary at the end. Two -v options will give you
  information on what files are being skipped and slightly more
  information at the end. More than two -v options should only be used
  if you are debugging rsync. Note that the names of the transferred
  files that are output are done using a default --out-format of
  lq%n%Lrq, which tells you just the name of the file and, if the item
  is a link, where it points. At the single -v level of verbosity, this
  does not mention when a file gets its attributes changed. If you ask
  for an itemized list of changed attributes (either --itemize-changes
  or adding lq%irq to the --out-format setting), the output (on the
  client) increases to mention all items that are changed in any way.
  See the --out-format option for more details.

-a, --archive This is equivalent to -rlptgoD. It is a quick way of saying you want recursion and want to preserve almost everything (with
  -H being a notable omission). The only exception to the above equivalence is when --files-from is specified, in which case -r is not
  implied. Note that -a does not preserve hardlinks, because finding
  multiply-linked files is expensive. You must separately specify -H.
  --no-OPTION You may turn off one or more implied options by prefixing the option name with lqno-rq. Not all options may be prefixed with a
  lqno-rq: only options that are implied by other options (e.g. --no-D,
  --no-perms) or have different defaults in various circumstances (e.g. --no-whole-file, --no-blocking-io, --no-dirs). You may specify either the short or the long option name after the lqno-rq prefix (e.g.
  --no-R is the same as --no-relative). For example: if you want to use -a (--archive) but don't want
  -o (--owner), instead of converting -a into -rlptgD, you could specify -a --no-o (or -a --no-owner). The order of the options is important: if you specify --no-r -a, the
  -r option would end up being turned on, the opposite of -a --no-r. Note also that the side-effects of the --files-from option are NOT
  positional, as it affects the default state of several options and
  slightly changes the meaning of -a (see the --files-from option for
  more details).

-z, --compress With this option, rsync compresses the file data as it is sent to the destination machine, which reduces the amount of data
  being transmitted -- something that is useful over a slow connection.
  Note that this option typically achieves better compression ratios
  than can be achieved by using a compressing remote shell or a
  compressing transport because it takes advantage of the implicit
  information in the matching data blocks that are not explicitly sent
  over the connection.

-h, --human-readable Output numbers in a more human-readable format. This makes big numbers output using larger units, with a K, M, or G
  suffix. If this option was specified once, these units are K (1000), M
  (1000*1000), and G (1000*1000*1000); if the option is repeated, the
  units are powers of 1024 instead of 1000.


来源: stackexchange

问:
Exposing third-party lib (Firepad) methods in a React component
I've been searching for answers to this for a couple of weeks now, and I've read through everything related I could find (on SO, in React's docs, in the source for related libraries like react-codemirror, etc.), and can't find an answer I can understand. I'm kind of weak on React, and that's probably where I'm falling down.

I'm working on a project built in React (called Pharaoh, a browser- and desktop-editor meant for the classroom) that uses Firepad (and so, uses Firebase and CodeMirror, which I love). I've used all of the above technologies a bit, including writing a desktop Markdown editor thing using CodeMirror and a few demo/practice apps using Firebase. My issue here is almost definitely one of just not understanding React all that well.

What I'm trying to do is get the ability to save files out of our Firepad/CodeMirror instance (to the desktop). I know generally how to use FileReader and the HTML5 Filesystem API, and this could even be done potentially with node-fs, since my target here is our desktop app (which runs on NW.js).

CodeMirror has some really useful methods like editorName.codeMirror.doc.getValue() which would work perfectly; Firepad has the even simpler editorName.firepad.getText() (and .setText() which I'd also end up using to load in files from the filesystem). I know how these work, and can see how I'd take what they return and save it out, that's no problem. My problem is that I can't actually access those methods. This is probably some silly thing I should just know about accessing methods from third-party libraries or from components in general, but I'm kind of stumped on it. A tool I frequently use at work, Codeshare.io, which I believe is built in React and uses Firepad, has those methods exposed, so I'm about to dig into their source (yay for cURL) and see if I can find any answers, but anything quicker would be really super helpful.

Thanks muchly!

Note: I guess I need to earn more SO reputation; removed/altered a bunch of links before posting.

答:
Use these npm packages - brace, react-ace, firebase, firepad.

Since firepad needs aceto be present globally, assign brace to global var
like(not the best way, but works) before importing firepad

```<code>import brace from 'brace';
global.ace = brace;
global.ace.require = global.ace.acequire;
import Firepad from 'firepad';
</code>```

Use ref to get instance of ReactAce and initialize it in componentDidMount using:

```<code>new Firepad.fromACE(this.firepadRef, this.aceInstance.editor, options);
</code>```

Similarly for CodeMirror editor.

Hoping, this would be of some help.

ContentLicense: CC BY-SA 3.0

Body:
Use these npm packages - brace, react-ace, firebase, firepad.

Since firepad needs aceto be present globally, assign brace to global var
like(not the best way, but works) before importing firepad

import brace from 'brace';
global.ace = brace;
global.ace.require = global.ace.acequire;
import Firepad from 'firepad';

Use ref to get instance of ReactAce and initialize it in componentDidMount using:

new Firepad.fromACE(this.firepadRef, this.aceInstance.editor, options);

Similarly for CodeMirror editor.

Hoping, this would be of some help.


问:
Add URL before image name in PHP
When i store image name in table, want to store name like URL.

For example, I have ready URL like: http://192.168.137.1/NI/uploads/ that I want to add before image name.

I want this result: http://192.168.137.1/NI/uploads/imagename.png

PHP code:

```<code>//We will upload files to this folder
//So one thing don't forget, also create a folder named uploads inside your
project folder i.e. MyApi folder
 define('UPLOAD_PATH', 'uploads/');

 //connecting to database
 $conn = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die('Unable to
 connect');

  //An array to display the response
  $response = array();

   //if the call is an api call
   if(isset($_GET['apicall'])){

    //switching the api call
    switch($_GET['apicall']){

    //if it is an upload call we will upload the image
    case 'uploadpic':

    //first confirming that we have the image and tags in the request
    parameter
   if(isset($_FILES['pic']['name']) && isset($_POST['tags'])){

  //uploading file and storing it to database as well
 try{
 move_uploaded_file($_FILES['pic']['tmp_name'], UPLOAD_PATH . $_FILES['pic']
['name']);

 $stmt = $conn->prepare("INSERT INTO t_table (image,tags)
VALUES (?,?)");

 $stmt->bind_param("ss", $_FILES['pic']['name'],$_POST['tags']);
 if($stmt->execute()){
 $response['error'] = false;
 $response['message'] = 'File uploaded successfully';
 }else{
 throw new Exception("Could not upload file");
 }
 }catch(Exception $e){
 $response['error'] = true;
 $response['message'] = 'Could not upload file';
}

 }else{
 $response['error'] = true;
 $response['message'] = "Required params not available";
 }
</code>```

答:
Do not store URL, just append the base url of the project while showing it on UI. This won't work once you deploy the app on another IP or change the IP to a domain name.

Store the name and keep appending base url while iterating over the data on front-end.

Title: Add URL before image name in PHP

Body:
When i store image name in table, want to store name like URL.

For example, I have ready URL like: http://192.168.137.1/NI/uploads/ that I want to add before image name.

I want this result: http://192.168.137.1/NI/uploads/imagename.png

PHP code:

//We will upload files to this folder
//So one thing don't forget, also create a folder named uploads inside your
project folder i.e. MyApi folder
 define('UPLOAD_PATH', 'uploads/');

 //connecting to database
 $conn = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die('Unable to
 connect');

  //An array to display the response
  $response = array();

   //if the call is an api call
   if(isset($_GET['apicall'])){

    //switching the api call
    switch($_GET['apicall']){

    //if it is an upload call we will upload the image
    case 'uploadpic':

    //first confirming that we have the image and tags in the request
    parameter
   if(isset($_FILES['pic']['name']) && isset($_POST['tags'])){

  //uploading file and storing it to database as well
 try{
 move_uploaded_file($_FILES['pic']['tmp_name'], UPLOAD_PATH . $_FILES['pic']
['name']);

 $stmt = $conn->prepare("INSERT INTO t_table (image,tags)
VALUES (?,?)");

 $stmt->bind_param("ss", $_FILES['pic']['name'],$_POST['tags']);
 if($stmt->execute()){
 $response['error'] = false;
 $response['message'] = 'File uploaded successfully';
 }else{
 throw new Exception("Could not upload file");
 }
 }catch(Exception $e){
 $response['error'] = true;
 $response['message'] = 'Could not upload file';
}

 }else{
 $response['error'] = true;
 $response['message'] = "Required params not available";
 }


问:
SAS group by first digits
I have a variable in SAS with a lot of numbers, for example 11000, 30129, 11111, 30999. I want to group this by the first two digits so "11000 and 11111" and "30129 and 30999" will be in a own table.</p>

答:
It's quite simple,

You have to create a second column and extract the 2 first digit.

Then sort the dataset by this second columns.

```<code>data test;
 infile datalines dsd ;
   input a : 15. ;
   datalines;
11000,
30129,
11111,
309999,
;
run;

data test_a;
length val_a $2;
set test;
val_a= SUBSTRN(a,1,2);
run;

proc sort data=test_a out=test_b;
by val_a;
run;
</code>```

Result will be :

```<code>val_a     a
11        11000
11        11111
30        30129
30        309999
</code>```

And then you can create 2 dataset with selection on the val_a like this :

```<code>data want data_11 data_30;
set test_b;
if val_a = 11 then output data_11;
if val_a = 30 then output data_30;
run;
</code>```

Regards,

Title: SAS group by first digits

Body:
It's quite simple,

You have to create a second column and extract the 2 first digit.

Then sort the dataset by this second columns.

data test;
 infile datalines dsd ;
   input a : 15. ;
   datalines;
11000,
30129,
11111,
309999,
;
run;

data test_a;
length val_a $2;
set test;
val_a= SUBSTRN(a,1,2);
run;

proc sort data=test_a out=test_b;
by val_a;
run;

Result will be :

val_a     a
11        11000
11        11111
30        30129
30        309999

And then you can create 2 dataset with selection on the val_a like this :

data want data_11 data_30;
set test_b;
if val_a = 11 then output data_11;
if val_a = 30 then output data_30;
run;

Regards,


问:
Anguarjs; Error: [$injector:unpr] trying to do Token authentication with $httpProvider
I'm trying to set up a simple token based authentication and have so far been able to create the tokens and save them to local storage, but when I try to create an interceptor that includes the token to every request sent I get a strange error:

Error: [$injector:unpr] http://errors.angularjs.org/1.6.6/$injector/unpr?p0=%24localStorageProvider%20%3C-%20%24localStorage%20%3C-%20%24http%20%3C-%20%24templateRequest%20%3C-%20%24route

Here is the code that I use for the Interceptor

```<code>var app = angular.module('Jäsentietopalvelu', ["ngRoute"])

.config(['$routeProvider', '$locationProvider', '$httpProvider', function($routeProvider, $locationProvider, $httpProvider){
        $locationProvider.hashPrefix('');
        $routeProvider
                .when('/', {
                templateUrl: 'login.html',
                })
                .when('/testi', {
                templateUrl: 'testi.html',
                })
                .when('/logout', {
                templateUrl: 'logout.html',
                })
                .when('/login', {
                templateUrl: 'login.html',
                })

        $httpProvider.interceptors.push(['$q','$location','$localStorage', function($q,$location, $localStorage){
                return {
                        'request': function (config){
                                config.headers = config.headers || {};
                                if ($localStorage.accessToken) {
                                        config.headers.Authorization = 'bearer ' + $localStorage.accessToken;
                                }
                                return config;
                        },
                        'responseError': function(response){
                                if(response.status === 401 || response.status === 403) {
                                        $location.path('/');
                                }
                                return $q.reject(response);
                        }
                };
        }]);
}])
</code>```

In what way should I create the interceptor so that it works properly? Is it supposed to be in module.config or somewhere else?

EDIT:

Here is my index -page

```<code><html ng-app="Jäsentietopalvelu">
<head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Jäsentietopalvelu</title>
        <script src="https://cdn.jsdelivr.net/ngstorage/0.3.10/ngStorage.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><!-- load jquery -->
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script><!-- load angular -->
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular-route.min.js"></script><!-- load angular routes -->
        <script src="core.js"></script>
</head>
<body ng-controller="mainCtrl">
        <ng-view></ng-view>
</body>
</code>```

答:
This error means that AngularJS could not find one of the required dependency in your project, named $localStorage.

I suspect you are using ngStorage in your code to deal with Local Storage in the browser using AngularJS.

First, you need to ensure that you've installed it as a dependency in the project. Follow these installation methods to get it in your project.

After installation, you need to ensure to declare it as a dependency in your angular module:

```<code>var app = angular.module('Jäsentietopalvelu', ["ngRoute", "ngStorage"]);
</code>```

Then only you can use its components in your project.

Body:
I'm trying to set up a simple token based authentication and have so far been able to create the tokens and save them to local storage, but when I try to create an interceptor that includes the token to every request sent I get a strange error:

Error: [$injector:unpr] http://errors.angularjs.org/1.6.6/$injector/unpr?p0=%24localStorageProvider%20%3C-%20%24localStorage%20%3C-%20%24http%20%3C-%20%24templateRequest%20%3C-%20%24route

Here is the code that I use for the Interceptor

var app = angular.module('Jäsentietopalvelu', ["ngRoute"])

.config(['$routeProvider', '$locationProvider', '$httpProvider', function($routeProvider, $locationProvider, $httpProvider){
        $locationProvider.hashPrefix('');
        $routeProvider
                .when('/', {
                templateUrl: 'login.html',
                })
                .when('/testi', {
                templateUrl: 'testi.html',
                })
                .when('/logout', {
                templateUrl: 'logout.html',
                })
                .when('/login', {
                templateUrl: 'login.html',
                })

        $httpProvider.interceptors.push(['$q','$location','$localStorage', function($q,$location, $localStorage){
                return {
                        'request': function (config){
                                config.headers = config.headers || {};
                                if ($localStorage.accessToken) {
                                        config.headers.Authorization = 'bearer ' + $localStorage.accessToken;
                                }
                                return config;
                        },
                        'responseError': function(response){
                                if(response.status === 401 || response.status === 403) {
                                        $location.path('/');
                                }
                                return $q.reject(response);
                        }
                };
        }]);
}])

In what way should I create the interceptor so that it works properly? Is it supposed to be in module.config or somewhere else?

EDIT:

Here is my index -page

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Jäsentietopalvelu</title>

        <ng-view></ng-view>

Body:
This error means that AngularJS could not find one of the required dependency in your project, named $localStorage.

I suspect you are using ngStorage in your code to deal with Local Storage in the browser using AngularJS.

First, you need to ensure that you've installed it as a dependency in the project. Follow these installation methods to get it in your project.

After installation, you need to ensure to declare it as a dependency in your angular module:

var app = angular.module('Jäsentietopalvelu', ["ngRoute", "ngStorage"]);

Then only you can use its components in your project.


问:
GIT - Pull requests from the same branch bring over history of commits
This is the setup in one of my repositories:

master branch <- this is always in the production server

staging branch (default branch) <- this is in the staging server

Every change we make goes through the following steps.
Let's say I have to make a change to readme.md.

I create a new branch from the default branch (staging), let's call it patch-readme

I make all the changes I need in patch-readme.

When I'm happy with my changes, I create a PR to staging.

I merge (squash and merge) the PR and then I delete patch-readme.

(note: multiple developers could push to the staging branch at this point, following the previous steps)

staging branch is then deployed to the staging server.

If I'm happy with the changes in the staging server, I create a new PR from staging to master.

I then review the changes and I merge (squash and merge) the pull request.

At this point I merge master back into staging. I am doing this because if the next PR to staging has a change to the readme.md file, when I create the new PR from staging to master I am getting a conflict on that file. So to avoid conflicts I am merging back master after every merged PR.

There is a problem with this workflow, basically every pull request from staging to master is bringing in commits from months ago, meaning a mess in the repository (for example if there is a commit that references one issue, that issue will have a very long list of references, one for every new PR created).

Now, something I don't understand is that sometimes (I haven't figured out under what circumstances) that history gets cleaned up. Today it happened to me because a developer forgot to update from master after merging a PR and I had to fix a few conflicts, after fixing the conflicts the new PR had a clean history. I've tried to replicate this scenario but it doesn't seem to do the same.

I've had a look at rebase, so what I've tried after merging the PR from staging to master, instead of merging back master I ran a git rebase master while on the staging branch. This didn't work, the next PR to master still had previous history.

Something that worked is that instead of creating a PR to master, I ran

```<code>git checkout master
git rebase staging
</code>```

In this case I didn't have to do anything and the next PR the history was clean. But this doesn't make a lot of sense because we'll need to discard the PRs. We're using PRs for code review.

What am I doing wrong? How can I have every time a clean history in the PR from staging to master?

Just a note here, our developers usually use only Github Desktop and the Github web interface. And because we're a small team everybody is able to create and merge PRs to both staging and master.

答:
I've found why that was happening. We're using the GitHub web UI to merge PRs.

Basically every PR sent to staging was merged with a "Squash and merge".
The PR from staging to master was merged the same way.

By using a "Merge commit" instead of "Squash and merge" every commit in staging is also appearing in master (instead of a single commit with the squash).

So, now to keep the history clean we're doing a "Squash and merge" from the feature branch to staging, while we're doing a "Merge commit" from staging to master.

Hope this is helpful to somebody else.

Body:
This is the setup in one of my repositories:

master branch <- this is always in the production server

staging branch (default branch) <- this is in the staging server

Every change we make goes through the following steps.
Let's say I have to make a change to readme.md.

I create a new branch from the default branch (staging), let's call it patch-readme

I make all the changes I need in patch-readme.

When I'm happy with my changes, I create a PR to staging.

I merge (squash and merge) the PR and then I delete patch-readme.

(note: multiple developers could push to the staging branch at this point, following the previous steps)

staging branch is then deployed to the staging server.

If I'm happy with the changes in the staging server, I create a new PR from staging to master.

I then review the changes and I merge (squash and merge) the pull request.

At this point I merge master back into staging. I am doing this because if the next PR to staging has a change to the readme.md file, when I create the new PR from staging to master I am getting a conflict on that file. So to avoid conflicts I am merging back master after every merged PR.

There is a problem with this workflow, basically every pull request from staging to master is bringing in commits from months ago, meaning a mess in the repository (for example if there is a commit that references one issue, that issue will have a very long list of references, one for every new PR created).

Now, something I don't understand is that sometimes (I haven't figured out under what circumstances) that history gets cleaned up. Today it happened to me because a developer forgot to update from master after merging a PR and I had to fix a few conflicts, after fixing the conflicts the new PR had a clean history. I've tried to replicate this scenario but it doesn't seem to do the same.

I've had a look at rebase, so what I've tried after merging the PR from staging to master, instead of merging back master I ran a git rebase master while on the staging branch. This didn't work, the next PR to master still had previous history.

Something that worked is that instead of creating a PR to master, I ran

git checkout master
git rebase staging

In this case I didn't have to do anything and the next PR the history was clean. But this doesn't make a lot of sense because we'll need to discard the PRs. We're using PRs for code review.

What am I doing wrong? How can I have every time a clean history in the PR from staging to master?

Just a note here, our developers usually use only Github Desktop and the Github web interface. And because we're a small team everybody is able to create and merge PRs to both staging and master.


问:
Keep uppercase using attr() with jquery (case sensitive)
I am doing this with jQuery :

```<code>@xmlOut = $('<rules />')
@xmlOut.attr('xsi:schemaLocation','test')
</code>```

I get this :

```<code><rules xsi:schemalocation='test'></rules>
</code>```

The "L" is not uppercase anymore...

答:
Kevin's answer is incorrect, .setAttribute() will change the attribute name to lowercase.

Instead, use element.setAttributeNS() with an empty string for the first parameter.

```<code>@xmlOut.get(0).setAttributeNS('', 'xsi:schemaLocation','test')
</code>```

https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttributeNS

Body:
I am doing this with jQuery :

@xmlOut = $('<rules />')
@xmlOut.attr('xsi:schemaLocation','test')

I get this :

<rules xsi:schemalocation='test'></rules>

The "L" is not uppercase anymore...

Body:
Kevin's answer is incorrect, .setAttribute() will change the attribute name to lowercase.

Instead, use element.setAttributeNS() with an empty string for the first parameter.

@xmlOut.get(0).setAttributeNS('', 'xsi:schemaLocation','test')

https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttributeNS


问:
Is it possible to make HttpClient ignore invalid ETag header in response?
I'm working on an application which makes a web service request using the HttpClient API to a third party service over which I have no control. The service seems to respond to requests with an ETag HTTP header containing an invalid value according to the HTTP specification (the value is not enclosed in quotation marks). This causes the HttpClient to fail with a System.FormatException.

In this case I am not interested in the ETag header and would like to be able to ignore the invalid value. Is it possible to do this using HttpClient?

I would prefer to use the HttpClient API over WebClient or WebRequest since this particular use case requires me to use a SOCKS proxy which is a lot simpler when using HttpClient.

答:
Try this:

```<code>class Example
{
    static void Main()
    {
        var client = HttpClientFactory.Create(new Handler());
        client.BaseAddress = new Uri("http://www.example.local");
        var r = client.GetAsync("").Result;
        Console.WriteLine(r.StatusCode);
        Console.WriteLine(r.Headers.ETag);
    }
}

class Handler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var headerName = "ETag";
        var r = await base.SendAsync(request, cancellationToken);
        var header = r.Headers.FirstOrDefault(x => x.Key == headerName);
        var updatedValue = header.Value.Select(x => x.StartsWith("\"") ? x : "\"" + x + "\"").ToList();
        r.Headers.Remove(headerName);
        r.Headers.Add(headerName, updatedValue);
        return r;
    }
}
</code>```

My response headers:

HTTP/1.1 200 OK

Date: Fri, 25 Jan 2013 16:49:29 GMT

FiddlerTemplate: True

Content-Length: 310

Content-Type: image/gif

ETag: rtt123

Body:
Try this:

class Example
{
    static void Main()
    {
        var client = HttpClientFactory.Create(new Handler());
        client.BaseAddress = new Uri("http://www.example.local");
        var r = client.GetAsync("").Result;
        Console.WriteLine(r.StatusCode);
        Console.WriteLine(r.Headers.ETag);
    }
}

class Handler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var headerName = "ETag";
        var r = await base.SendAsync(request, cancellationToken);
        var header = r.Headers.FirstOrDefault(x => x.Key == headerName);
        var updatedValue = header.Value.Select(x => x.StartsWith("\"") ? x : "\"" + x + "\"").ToList();
        r.Headers.Remove(headerName);
        r.Headers.Add(headerName, updatedValue);
        return r;
    }
}

My response headers:

HTTP/1.1 200 OK

Date: Fri, 25 Jan 2013 16:49:29 GMT

FiddlerTemplate: True

Content-Length: 310

Content-Type: image/gif

ETag: rtt123


问:
Vaadin Grid ItemClickListener fails to register clicks on column with ImageRenderer
I have the following code which is supposed to show a clickable icon which opens a popup dialog reading out a lengthy note.

```<code>        this.capacityCommentColumn = this.facilityGrid.addColumn(
                    p -> {
                        if (Strings.isNullOrEmpty(p.getCapacityComment())) {
                            return null;
                        } else {
                            return new ThemeResource("img/note.svg");
                        }
                    },
                    new ImageRenderer<>())
                    .setWidth(80)
                    .setCaption("Note");

        this.facilityGrid.addItemClickListener(new ItemClickListener<MapQueryService.RowResult>() {
            @Override
            public void itemClick(Grid.ItemClick<MapQueryService.RowResult> event) {
                if (event.getColumn() == capacityCommentColumn && !Strings.isNullOrEmpty(event.getItem().getCapacityComment())) {
                    final NoteWindow noteWindow = new NoteWindow();
                    noteWindow.txtDescription.setValue("test");
                    noteWindow.show();
                }
            }
        });
</code>```

The problem is the code does not respond to clicks on the actual image, only on the outside.  You can see this below.  Any idea if its possible to make the image clickable?

答:
You need to add a click listener to the Renderer as well. For example:

```<code>Grid<Integer> grid = new Grid();

private void addIconColumn() {
    ImageRenderer<Integer> renderer = new ImageRenderer<>();
    renderer.addClickListener(e -> iconClicked(e.getItem())); // allow clicks on the image

    Grid.Column<Integer, ThemeResource> iconColumn = grid.addColumn(i -> new ThemeResource("img/icon.svg"), renderer)
            .setCaption("Icon");

    grid.addItemClickListener(e -> { // allow clicks on the cell
        if (iconColumn.equals(e.getColumn())) {
            iconClicked(e.getItem());
        }
    });
}

private void iconClicked(Integer i) {
    ... your UI logic here ...
}
</code>```

You can see a working example here: https://github.com/alejandro-du/community-answers/tree/master/click-image-in-grid

Body:
I have the following code which is supposed to show a clickable icon which opens a popup dialog reading out a lengthy note.

        this.capacityCommentColumn = this.facilityGrid.addColumn(
                    p -> {
                        if (Strings.isNullOrEmpty(p.getCapacityComment())) {
                            return null;
                        } else {
                            return new ThemeResource("img/note.svg");
                        }
                    },
                    new ImageRenderer<>())
                    .setWidth(80)
                    .setCaption("Note");

        this.facilityGrid.addItemClickListener(new ItemClickListener<MapQueryService.RowResult>() {
            @Override
            public void itemClick(Grid.ItemClick<MapQueryService.RowResult> event) {
                if (event.getColumn() == capacityCommentColumn && !Strings.isNullOrEmpty(event.getItem().getCapacityComment())) {
                    final NoteWindow noteWindow = new NoteWindow();
                    noteWindow.txtDescription.setValue("test");
                    noteWindow.show();
                }
            }
        });

The problem is the code does not respond to clicks on the actual image, only on the outside.  You can see this below.  Any idea if its possible to make the image clickable?

Body:
You need to add a click listener to the Renderer as well. For example:

Grid<Integer> grid = new Grid();

private void addIconColumn() {
    ImageRenderer<Integer> renderer = new ImageRenderer<>();
    renderer.addClickListener(e -> iconClicked(e.getItem())); // allow clicks on the image

    Grid.Column<Integer, ThemeResource> iconColumn = grid.addColumn(i -> new ThemeResource("img/icon.svg"), renderer)
            .setCaption("Icon");

    grid.addItemClickListener(e -> { // allow clicks on the cell
        if (iconColumn.equals(e.getColumn())) {
            iconClicked(e.getItem());
        }
    });
}

private void iconClicked(Integer i) {
    ... your UI logic here ...
}

You can see a working example here: https://github.com/alejandro-du/community-answers/tree/master/click-image-in-grid


问:
Display Success Message Box in ASP.NET C#
How can I display messagebox with success logo in ASP.net, I can only display alert message box by using these code.

```<code>ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Please dont leave text boxes blank');",true);
</code>```

Many thanks.

答:
```<code>MessageBox.Show("Successfully saved", " Student Record", MessageBoxButtons.OK, MessageBoxIcon.Information);
</code>```

Body:
How can I display messagebox with success logo in ASP.net, I can only display alert message box by using these code.

ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Please dont leave text boxes blank');",true);

Many thanks.


问:
Custom Webpart Parameters-Sharepoint 2007
My Webpart needs a parameter which will be supplied during the use in a page. The Parameter are supplied in the textbox while its being used in a page as web part.

I have placed a textbox and it should get the parameter as a password in the format of *****.

How can I do that.

I have edited the question The diagram explains in more details

The Password is supplied as an external parameter and supplied during the deployment of the webpart.

Could any body help me.

Luke many thanks for the answer you have provided but I am looking for this kind of input.

Thank You

Hari Gillala

答:
If i have understood what you are wanting to do correctly, you would like to use a TextBoc control in a web part which masks the input like a password input box.. If this is correct you can achieve this as follows:

```<code>public class LukeTestingWebPart : System.Web.UI.WebControls.WebParts.WebPart
{
    TextBox txtBox1; //Declare the TextBox control

    public LukeTestingWebPart()
    {
    }

    protected override void CreateChildControls()
    {
        //Create the child control with th text box mode as Password
        txtBox1 = new TextBox();
        txtBox1.TextMode = TextBoxMode.Password;
        Controls.Add(txtBox1);

        base.CreateChildControls();
    }

    protected override void RenderContents(HtmlTextWriter writer)
    {
        //Render a line of descriptive text and the textbox control
        writer.Write("Here is a text box control that can be used to hold a password:<br />");
        txtBox1.RenderControl(writer);
    }
}
</code>```

This is a ver simple web part that renders a text box where the input is masked...

I hope this helps...

ContentLicense: CC BY-SA 2.5

Body:
If i have understood what you are wanting to do correctly, you would like to use a TextBoc control in a web part which masks the input like a password input box.. If this is correct you can achieve this as follows:

public class LukeTestingWebPart : System.Web.UI.WebControls.WebParts.WebPart
{
    TextBox txtBox1; //Declare the TextBox control

    public LukeTestingWebPart()
    {
    }

    protected override void CreateChildControls()
    {
        //Create the child control with th text box mode as Password
        txtBox1 = new TextBox();
        txtBox1.TextMode = TextBoxMode.Password;
        Controls.Add(txtBox1);

        base.CreateChildControls();
    }

    protected override void RenderContents(HtmlTextWriter writer)
    {
        //Render a line of descriptive text and the textbox control
        writer.Write("Here is a text box control that can be used to hold a password:<br />");
        txtBox1.RenderControl(writer);
    }
}

This is a ver simple web part that renders a text box where the input is masked...

I hope this helps...


问:
How can I check whether a URL is valid using `urlparse`?
I want to check whether a URL is valid, before I open it to read data.

I was using the function urlparse from the urlparse package:

```<code>if not bool(urlparse.urlparse(url).netloc):
 # do something like: open and read using urllin2
</code>```

However, I noticed that some valid URLs are treated as broken, for example:

```<code>url = upload.wikimedia.org/math/8/8/d/88d27d47cea8c88adf93b1881eda318d.png
</code>```

This URL is valid (I can open it using my browser).

Is there a better way to check if the URL is valid?

答:
You can try the function below which checks scheme, netloc and path variables which comes after parsing the url. Supports both Python 2 and 3.

```<code>try:
    # python 3
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse

def url_validator(url):
    try:
        result = urlparse(url)
        components = [result.scheme, result.path]
        if result.netloc != "":
            components.append(result.netloc)
        return all(components)
    except:
        return False
</code>```

Body:
I want to check whether a URL is valid, before I open it to read data.

I was using the function urlparse from the urlparse package:

if not bool(urlparse.urlparse(url).netloc):
 # do something like: open and read using urllin2

However, I noticed that some valid URLs are treated as broken, for example:

url = upload.wikimedia.org/math/8/8/d/88d27d47cea8c88adf93b1881eda318d.png

This URL is valid (I can open it using my browser).

Is there a better way to check if the URL is valid?

Body:
You can try the function below which checks scheme, netloc and path variables which comes after parsing the url. Supports both Python 2 and 3.

try:
    # python 3
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse

def url_validator(url):
    try:
        result = urlparse(url)
        components = [result.scheme, result.path]
        if result.netloc != "":
            components.append(result.netloc)
        return all(components)
    except:
        return False

ContentLicense: CC BY-SA 4.0


问:
Got "else" with no preceding "if" error ruby

links

```<code>- if current_user
= link_to "Edit", edit_job_path(@job), class: "btn btn-sm btn-default"
= link_to "Delete", job_path(@job), method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-sm btn-default"

- else

 = link_to "Back", root_path, class: "btn btn-sm btn-default"
</code>```

This returns:

```<code>Got "else" with no preceding "if" error ruby
</code>```

Why is that?

Body:
links

- if current_user
= link_to "Edit", edit_job_path(@job), class: "btn btn-sm btn-default"
= link_to "Delete", job_path(@job), method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-sm btn-default"

- else

 = link_to "Back", root_path, class: "btn btn-sm btn-default"

This returns:

Got "else" with no preceding "if" error ruby

Why is that?


问:
Foreach syntax issue have used code in different project now broken

So my problem is I do not understand why I am getting this error as I have used this code previously for a different task and it worked. Here is the sample code:

```<code>  <?php

  include('assets/php/sql/con.php');

  if (isset($_GET['age'])) {
    $AGE = $_GET['age'];
    $GENDER = $_GET['gender'];

      $results = DB::query('SELECT * FROM gift_db WHERE age =:age',array(':age' => $_GET['age']))[0]['age'];

      // DB::query('SELECT * FROM gift_db WHERE age=:age', array(':age'=>$_GET['age']));
      $allResults = "";
      foreach ($results as $r) {

        $allResults = $r;

    }
  }
   ?>
</code>```

If anyone would be able to help out that would be amazing. Thanks :)

答:
It seems like $AGE is coming as a string, not an integer, so can you please try like below:-

```<code>$results = DB::query('SELECT * FROM gift_db WHERE age =:age',array(':age' => (int) $AGE));
</code>```

Body:
So my problem is I do not understand why I am getting this error as I have used this code previously for a different task and it worked. Here is the sample code:

  <?php

  include('assets/php/sql/con.php');

  if (isset($_GET['age'])) {
    $AGE = $_GET['age'];
    $GENDER = $_GET['gender'];

      $results = DB::query('SELECT * FROM gift_db WHERE age =:age',array(':age' => $_GET['age']))[0]['age'];

      // DB::query('SELECT * FROM gift_db WHERE age=:age', array(':age'=>$_GET['age']));
      $allResults = "";
      foreach ($results as $r) {

        $allResults = $r;

    }
  }
   ?>

If anyone would be able to help out that would be amazing. Thanks :)

Body:
It seems like $AGE is coming as a string, not an integer, so can you please try like below:-

$results = DB::query('SELECT * FROM gift_db WHERE age =:age',array(':age' => (int) $AGE));


问:
I can't add item to ( std::vector < std::vector <std::string> > )
Why can't I add an item to vector :

```<code>std::vector < std::vector <std::string> > my_list;
my_list[0][0] = "this is text";

std::cout << "text: " << my_list[0][0] << std::endl;
</code>```

What am I doing wrong?

答:
Unlike some containers (such as std::map), a std::vector does not grow on demand.

So before you index an element you need to make sure the std::vector has the appropriate size. You can do that by passing a size on construction.

In your case you could use the flashy syntax

```<code>std::vector < std::vector <std::string> > my_list{{"this is a test"}};
</code>```

to get things going.

Body:
Why can't I add an item to vector :

std::vector < std::vector <std::string> > my_list;
my_list[0][0] = "this is text";

std::cout << "text: " << my_list[0][0] << std::endl;

What am I doing wrong?

Body:
Unlike some containers (such as std::map), a std::vector does not grow on demand.

So before you index an element you need to make sure the std::vector has the appropriate size. You can do that by passing a size on construction.

In your case you could use the flashy syntax

std::vector < std::vector <std::string> > my_list{{"this is a test"}};

to get things going.


问:
How to test for String = Enum.Value?
How do I do a simple compare of an enum value and a string that should match the enums name?

How do I parse the string into it's appropriate enum value.

For example,

```<code>Enum A
     B=0
     C=1
     D=2
End Enum
</code>```

How do I check if String = A.C and how do I convert string into its corresponding A value without comparing it to a string representation?

答:
There are several different methods that are related:

```<code>Enum.GetName(typeof(A), A.C) == "C"
A.C.ToString() == "C"
((A)Enum.Parse(typeof(A), "C")) == A.C
</code>```

The first two convert the value of A.C to a string representation ("C") and then compare it to a string.  The last one converts the string "C" to a type A, and then compares as an actual type A.

Enum to string: enumValue.ToString() or Enum.GetName(typeof(A), A.C)

String to enum: (A)Enum.Parse(typeof(A), "C")

Note that none of those will really work if the enumeration is marked with FlagsAttribute.

OwnerDisplayName: Middletone

Title: How to test for String = Enum.Value?

Body:
How do I do a simple compare of an enum value and a string that should match the enums name?

How do I parse the string into it's appropriate enum value.

For example,

Enum A
     B=0
     C=1
     D=2
End Enum

How do I check if String = A.C and how do I convert string into its corresponding A value without comparing it to a string representation?

Body:
There are several different methods that are related:

Enum.GetName(typeof(A), A.C) == "C"
A.C.ToString() == "C"
((A)Enum.Parse(typeof(A), "C")) == A.C

The first two convert the value of A.C to a string representation ("C") and then compare it to a string.  The last one converts the string "C" to a type A, and then compares as an actual type A.

Enum to string: enumValue.ToString() or Enum.GetName(typeof(A), A.C)

String to enum: (A)Enum.Parse(typeof(A), "C")

Note that none of those will really work if the enumeration is marked with FlagsAttribute.

OwnerDisplayName: earlNameless

LastEditorDisplayName: earlNameless


问:
Automatic type Conversion in C#
I know that you could override an object's ToString() Method, so that everytime you call an object or pass it to a function that requires a String type it will be converted to a String.

I have written several extension methods for object type 'object'

```<code>public static DateTime ToDate(this object date)
{
    return DateTime.Parse(date.ToString());
}

public static int ToInteger(this object num)
{
    return Int32.Parse(num.ToString());
}

public static long ToLong(this object num)
{
    return Int64.Parse(num.ToString());
}
</code>```

so that I could just call them like this:

```<code>eventObject.Cost = row["cost"].ToString();
eventObject.EventId = row["event_id"].ToLong();
</code>```

However, what I want to accomplish is to convert the row objects which is of type 'object' to its correct type based on the property types on my 'eventObject'. So, I could call it like this:

```<code>eventObject.Cost = row["cost"];
eventObject.EventId = row["event_id"];
</code>```

The row is a DataRow if that matters.

答:
C# supports implicit conversion for types and you can use it for your custom types like the following:

```<code> class CustomValue
 {
     public static implicit operator int(CustomValue v)  {  return 4;  }

     public static implicit operator float(CustomValue v) {  return 4.6f;  }
 }

 class Program
 {
     static void Main(string[] args)
     {
         int x = new CustomValue(); // implicit conversion
         float xx = new CustomValue(); // implicit conversion
     }
 }
</code>```

And supports extension methods, but doesn't support implicit conversion as an extension method like the following:

```<code>static class MyExtension
{
    // Not supported
    public static implicit operator bool(this CustomValue v)
    {
        return false;
    }
}
</code>```

Title: Automatic type Conversion in C#

Body:
I know that you could override an object's ToString() Method, so that everytime you call an object or pass it to a function that requires a String type it will be converted to a String.

I have written several extension methods for object type 'object'

public static DateTime ToDate(this object date)
{
    return DateTime.Parse(date.ToString());
}

public static int ToInteger(this object num)
{
    return Int32.Parse(num.ToString());
}

public static long ToLong(this object num)
{
    return Int64.Parse(num.ToString());
}

so that I could just call them like this:

eventObject.Cost = row["cost"].ToString();
eventObject.EventId = row["event_id"].ToLong();

However, what I want to accomplish is to convert the row objects which is of type 'object' to its correct type based on the property types on my 'eventObject'. So, I could call it like this:

eventObject.Cost = row["cost"];
eventObject.EventId = row["event_id"];

The row is a DataRow if that matters.

Body:
C# supports implicit conversion for types and you can use it for your custom types like the following:

 class CustomValue
 {
     public static implicit operator int(CustomValue v)  {  return 4;  }

     public static implicit operator float(CustomValue v) {  return 4.6f;  }
 }

 class Program
 {
     static void Main(string[] args)
     {
         int x = new CustomValue(); // implicit conversion
         float xx = new CustomValue(); // implicit conversion
     }
 }

And supports extension methods, but doesn't support implicit conversion as an extension method like the following:

static class MyExtension
{
    // Not supported
    public static implicit operator bool(this CustomValue v)
    {
        return false;
    }
}


问:
How can I give my right div margin top property here?

Hi,

I want the right div with red background some margin top property but still stay the same in the blue box. How can I achieve this? If I give margin top to the div now, it moves the whole blue div.

    left

    right

```

答:
You can achieve this using

#left {
  background-color: green; height: 50px; width: 50px; float: left;
}
#right {
  background-color: red; height: 50px; width: 50px; margin-top:20px; float:left; margin-left:20px;
}
#wrapper {
width: 100%;height: 100px; background-color: blue; display:inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
  <div id="left">
    left
  </div>
  <div id="right">
    right
  </div>
</div></code>```

Body:
You can achieve this using

#left {
  background-color: green; height: 50px; width: 50px; float: left;
}
#right {
  background-color: red; height: 50px; width: 50px; margin-top:20px; float:left; margin-left:20px;
}
#wrapper {
width: 100%;height: 100px; background-color: blue; display:inline-block;
}

<div id="wrapper">
  <div id="left">
    left
  </div>
  <div id="right">
    right
  </div>
</div>


问:
Fell on the goalline
So I coded something that calculates the minimum and the maximum floating numbers that the user entered.

Now I got a follow up question that asked me to store the min and max numbers in a file.

Storing the min and max werent any problems, just did an outputfile print statement which said this is the biggest number + min (min was the variable). Vice versa for Max variable.

But im struggeling with getting every number the user entered before it calculated which number was the biggest and smallest.

Did outputfile print statement which " (min + max + number); but it only stored min, max, and the last entered number by the user, and not all between.

Do I need to make new variables to track every entered floated number? Or do I need to connect some other variables?

Ive tried using arrays but cant get a hang of it.

Look at this file, its how far ive came yet ; https://imgur.com/a/dE0JB

There might be another way thats more appropriate, dont hesitate to change, w/e just so it works.

I hope you can understand me.

Looking forward your suggestion.

Using Java

`import java.io.*;
import java.io.IOException;
import java.util.Scanner;

public class Output {

```<code>public static void main(String[] args)  throws IOException //Eftersom vi inte lärt oss att hantera exceptions än
{
    PrintWriter outputFile = new PrintWriter("C:\\Users\\Boo\\Desktop\\output.txt");  //Öppnar en ny fil

    // Variabel för att förvara "flyttal"

    float nummer;

    float array[]=null;

    //Deklarera max variabeln för att hålla största numret

    //Initialisera max med minimum värde möjligt

    float max=Float.MIN_VALUE;

    //Deklarera min variabeln för att hålla minsta numret

    //Initialisera min med maximum värde möjligt

    float min=Float.MAX_VALUE;

    //char variabel för att förvara Y/N, med andra ord är du klar?

    char yn;

    //scanner för att läsa input

    Scanner keyboard = new Scanner(System.in);

    System.out.println("Start entering floating point numbers");

    do {

    //läs float input

    nummer = keyboard.nextFloat();

    if(max<nummer) //om max är mindre än nuvarande nummer

    max = nummer; //Då uppdateras max till nuvarande nummer

    if(min>nummer) //om min är större än nuvarande nummer

    min = nummer; //Uppdatera min till nuvarande nummer

    // Fråga användaren om inmatandet är klart?

    System.out.print("Are you done? (Y/N)?");

    yn = keyboard.next().charAt(0);

    // En loop som går tills användaren skriver n/N
    }while(yn=='N' || yn=='n');

    // Printar sen då resultatet, dvs högsta och minsta numret

    System.out.println("Biggest number entered is: "+max);

    System.out.println("Smallest number entered is: " +min);
    outputFile.println("Biggest number entered is:" +  min);
    outputFile.println("Smallest number entered is:" + max);
    outputFile.println("All of the numbers entered is:" +  );
    System.out.println("Data written to the file.");

    outputFile.close();
}
}
</code>```

答:
When using arrays, you need to allocate space for the data. This means you need to know ahead of time the number of items you need:

```<code>float array[] = new float[100];
</code>```

This will create an array with space for 100 floats.

Then, add all the numbers to the array as you read them from the user:

```<code>int currentIndex= 0; // Keep track of where to put the next number
do {
    nummer = keyboard.nextFloat();
    array[currentIndex++] = nummer;
    // .....
} while(currentIndex < 100 && (yn == 'N' || yn == 'n'));
</code>```

Note that I've added a check that ensures you don't add anything once the array is full.

Lastly, use a loop to write all the values in the file.

```<code>outputFile.println("All of the numbers entered:" +  );
for (int i = 0; i < currentIndex; i++) {
    outputFile.println(array[i]);
}
</code>```

Notes: There are other containers, like ArrayList, that do not require you to know how many items you will need ahead of time.

Title: Fell on the goalline

Body:
So I coded something that calculates the minimum and the maximum floating numbers that the user entered.

Now I got a follow up question that asked me to store the min and max numbers in a file.

Storing the min and max werent any problems, just did an outputfile print statement which said this is the biggest number + min (min was the variable). Vice versa for Max variable.

But im struggeling with getting every number the user entered before it calculated which number was the biggest and smallest.

Did outputfile print statement which " (min + max + number); but it only stored min, max, and the last entered number by the user, and not all between.

Do I need to make new variables to track every entered floated number? Or do I need to connect some other variables?

Ive tried using arrays but cant get a hang of it.

Look at this file, its how far ive came yet ; https://imgur.com/a/dE0JB

There might be another way thats more appropriate, dont hesitate to change, w/e just so it works.

I hope you can understand me.

Looking forward your suggestion.

Using Java

`import java.io.*;
import java.io.IOException;
import java.util.Scanner;

public class Output {

public static void main(String[] args)  throws IOException //Eftersom vi inte lärt oss att hantera exceptions än
{
    PrintWriter outputFile = new PrintWriter("C:\\Users\\Boo\\Desktop\\output.txt");  //Öppnar en ny fil

    // Variabel för att förvara "flyttal"

    float nummer;

    float array[]=null;

    //Deklarera max variabeln för att hålla största numret

    //Initialisera max med minimum värde möjligt

    float max=Float.MIN_VALUE;

    //Deklarera min variabeln för att hålla minsta numret

    //Initialisera min med maximum värde möjligt

    float min=Float.MAX_VALUE;

    //char variabel för att förvara Y/N, med andra ord är du klar?

    char yn;

    //scanner för att läsa input

    Scanner keyboard = new Scanner(System.in);

    System.out.println("Start entering floating point numbers");

    do {

    //läs float input

    nummer = keyboard.nextFloat();

    if(max<nummer) //om max är mindre än nuvarande nummer

    max = nummer; //Då uppdateras max till nuvarande nummer

    if(min>nummer) //om min är större än nuvarande nummer

    min = nummer; //Uppdatera min till nuvarande nummer

    // Fråga användaren om inmatandet är klart?

    System.out.print("Are you done? (Y/N)?");

    yn = keyboard.next().charAt(0);

    // En loop som går tills användaren skriver n/N
    }while(yn=='N' || yn=='n');

    // Printar sen då resultatet, dvs högsta och minsta numret

    System.out.println("Biggest number entered is: "+max);

    System.out.println("Smallest number entered is: " +min);
    outputFile.println("Biggest number entered is:" +  min);
    outputFile.println("Smallest number entered is:" + max);
    outputFile.println("All of the numbers entered is:" +  );
    System.out.println("Data written to the file.");

    outputFile.close();
}
}

Body:
When using arrays, you need to allocate space for the data. This means you need to know ahead of time the number of items you need:

float array[] = new float[100];

This will create an array with space for 100 floats.

Then, add all the numbers to the array as you read them from the user:

int currentIndex= 0; // Keep track of where to put the next number
do {
    nummer = keyboard.nextFloat();
    array[currentIndex++] = nummer;
    // .....
} while(currentIndex < 100 && (yn == 'N' || yn == 'n'));

Note that I've added a check that ensures you don't add anything once the array is full.

Lastly, use a loop to write all the values in the file.

outputFile.println("All of the numbers entered:" +  );
for (int i = 0; i < currentIndex; i++) {
    outputFile.println(array[i]);
}

Notes: There are other containers, like ArrayList, that do not require you to know how many items you will need ahead of time.


问:
WordPress: Google-loaded jQuery doesn't work in wp-admin
I'm using jQuery in my theme, loading it from Google's CDN network, and calling it like this in my functions.php file:

```<code>function bb_google_jquery() {
    wp_deregister_script('jquery');
    wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', false, '1.4.4');
    wp_enqueue_script('jquery');
}

if(!is_admin()){
    add_action('init', 'bb_google_jquery');
}
</code>```

The problem is, even if it's wrapped in the conditional tag, it stops wp-admin jQuery stuff, such as the sidebar menu dropdowns, and dashboard dropdowns from working. Removing the is_admin makes it work correctly.

However, I need it to be wrapped in the conditional tag because otherwise I can't move menu items around.

Anything I'm doing wrong with this code?

答:
It sounds like you want this functionality as an admin, but your conditional says to load it only if the session is not an admin session.  Perhaps removing the ! would help?

```<code> if( is_admin() ) {
</code>```

The way it's setup in your code says "load JQuery for all non-admins only."

Body:
I'm using jQuery in my theme, loading it from Google's CDN network, and calling it like this in my functions.php file:

function bb_google_jquery() {
    wp_deregister_script('jquery');
    wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', false, '1.4.4');
    wp_enqueue_script('jquery');
}

if(!is_admin()){
    add_action('init', 'bb_google_jquery');
}

The problem is, even if it's wrapped in the conditional tag, it stops wp-admin jQuery stuff, such as the sidebar menu dropdowns, and dashboard dropdowns from working. Removing the is_admin makes it work correctly.

However, I need it to be wrapped in the conditional tag because otherwise I can't move menu items around.

Anything I'm doing wrong with this code?

Body:
It sounds like you want this functionality as an admin, but your conditional says to load it only if the session is not an admin session.  Perhaps removing the ! would help?

 if( is_admin() ) {

The way it's setup in your code says "load JQuery for all non-admins only."


问:
Is it possible to activate tensorflow anaconda environment inside a python script
What I want to do is to create a GUI for my tensorflow program.
However, I can't seem to run my conda tensorflow environment inside my python script.

I have already tried this code

```<code>subprocess.call("activate tensorflow", shell=True)
</code>```

but it still says that it cant find the tensorflow module.

答:
Not in general. A virtualenv has its own copy of the Python interpreter, possibly with a different version than the system-wide (most problematically, one can be Python 2 and the other Python 3). Once you have already started one Python interpreter you cannot hot-swap it with another.

If you know that both versions of the interpreter are the same, then you could try something like adding the virtualenv lib and site-packages directories at the beginning of sys.path before doing anything else, but that's not really clean and even then some things may not work correctly (besides, I think the default virtualenv and the Anaconda virtualenv directory structures are somewhat different). Also, even if this worked, it would definitely not be possible to dance around from one virtualenv to another after you start importing modules (once you import a module, there is no way to "unimport" it, and every future reference will use the one loaded first, no matter what sys.path says).

It would be better to just have a different process to work in the virtualenv. You can run a second interpreter directly from the first one, or call a batch/shell script to do it for you, or replace the first Python script with a batch/shell script, etc.

Body:
What I want to do is to create a GUI for my tensorflow program.
However, I can't seem to run my conda tensorflow environment inside my python script.

I have already tried this code

subprocess.call("activate tensorflow", shell=True)

but it still says that it cant find the tensorflow module.


问:
Classify a list of value through a list of thresholds
I have a map of <String,Double> considered as thresholds to classify a list of Doubles

```<code>HashMap<String, Double> map = new Hashmap<>();
map.put(A/B,0.7);
map.put(B/C,0.4);
map.put(C/D,0.3);
map.put(D/E,0.1);
</code>```

The Doubles of the hash is used as threshold to classify a list doubles given, so I want to transform this map into a list of classes A, B, C, D

```<code>Class A : from 0.7
Class B : from 0.4 to 0.7
Class C : from 0.3 to 0.4
Class D : from 0.1 to 0.3
Class E : less than 0.1
</code>```

Do you have any idea on how to perform that as a method StringClassifyByValue(HashMap<String, Double> map, Double value){} returning a String of the class correspondent of the value given as parameter?

ِExample :

this.StringClassifyByValue(map,0.5) have to return B.

答:
Some thoughts: first of all, your data structure is not really helping with the problem you want to solve. But that is exactly what data structures exist for: to give you a helpful abstraction that allows you to efficiently solve your "most important" problem.

Coming from there, I would suggest that you start by creating classes that better fit your problem statement. You could start with something like

```<code>public class Interval {

   private final double lowerBoundary;
   private final double upperBoundary;

   public Interval(double lowerBoundary, upperBoundary) {
     this.lowerBoundary = ...
   }

   public boolean contains(double value) {
     return (value >= lowerBoundary) && (value <=upperBoundary);
   }
</code>```

And instead of keeping of using a Map<String, Double> you rather have something like List<Pair<Classification, Interval>> where:

Pair could be a class that simply holds two values that belong together (instead of using a "generic" pair class, you could also create your own custom class that combines a Classification with an Interval).

Classification represents a "class", like A, B, C, in your example. The point is: be careful about using raw String objects for such purposes. Maybe a simple string is fine for now, but maybe you have to further enhance your logic later on - to then find that "hm, now a simple string doesn't do any more, but now I have to update a ton of places to change that".

And of course: ideally, you would sort the above list by "intervals". Then finding the Classification for a specific double value is super simple:

```<code> for (Pair<Classification, Interval> combo : listOfPairs) {
   if (combo.getInterval().contains(value)) {
     return combo.getClassification(); // yeeha found one
   }
 }
 return "nothing found" ... or throw some kind of exception
</code>```

Long story short: I can't tell you how to best transform your existing map into the above list of pair objects - because I don't know the big picture. It might be possible to simply not create that map initially, and directly build such a list of objects.

And for the record: if that map exists as map because there are other, more important requirements ... then you have to carefully balance if you really want to keep using map+list (means "double book-keeping") or if you put all of the above logic into some service that turns your Map into a List, does the lookup and then throws away this "other" representation of your data.

Body:
I have a map of <String,Double> considered as thresholds to classify a list of Doubles

HashMap<String, Double> map = new Hashmap<>();
map.put(A/B,0.7);
map.put(B/C,0.4);
map.put(C/D,0.3);
map.put(D/E,0.1);

The Doubles of the hash is used as threshold to classify a list doubles given, so I want to transform this map into a list of classes A, B, C, D

Class A : from 0.7
Class B : from 0.4 to 0.7
Class C : from 0.3 to 0.4
Class D : from 0.1 to 0.3
Class E : less than 0.1

Do you have any idea on how to perform that as a method StringClassifyByValue(HashMap<String, Double> map, Double value){} returning a String of the class correspondent of the value given as parameter?

ِExample :

this.StringClassifyByValue(map,0.5) have to return B.

Body:
Some thoughts: first of all, your data structure is not really helping with the problem you want to solve. But that is exactly what data structures exist for: to give you a helpful abstraction that allows you to efficiently solve your "most important" problem.

Coming from there, I would suggest that you start by creating classes that better fit your problem statement. You could start with something like

public class Interval {

   private final double lowerBoundary;
   private final double upperBoundary;

   public Interval(double lowerBoundary, upperBoundary) {
     this.lowerBoundary = ...
   }

   public boolean contains(double value) {
     return (value >= lowerBoundary) && (value <=upperBoundary);
   }

And instead of keeping of using a Map<String, Double> you rather have something like List<Pair<Classification, Interval>> where:

Pair could be a class that simply holds two values that belong together (instead of using a "generic" pair class, you could also create your own custom class that combines a Classification with an Interval).

Classification represents a "class", like A, B, C, in your example. The point is: be careful about using raw String objects for such purposes. Maybe a simple string is fine for now, but maybe you have to further enhance your logic later on - to then find that "hm, now a simple string doesn't do any more, but now I have to update a ton of places to change that".

And of course: ideally, you would sort the above list by "intervals". Then finding the Classification for a specific double value is super simple:

 for (Pair<Classification, Interval> combo : listOfPairs) {
   if (combo.getInterval().contains(value)) {
     return combo.getClassification(); // yeeha found one
   }
 }
 return "nothing found" ... or throw some kind of exception

Long story short: I can't tell you how to best transform your existing map into the above list of pair objects - because I don't know the big picture. It might be possible to simply not create that map initially, and directly build such a list of objects.

And for the record: if that map exists as map because there are other, more important requirements ... then you have to carefully balance if you really want to keep using map+list (means "double book-keeping") or if you put all of the above logic into some service that turns your Map into a List, does the lookup and then throws away this "other" representation of your data.


问:
How to reverse a dummy variables from a pandas dataframe
I would like to reverse a dataframe with dummy variables. For example,

from df_input:

```<code>Course_01 Course_02 Course_03
  0           0         1
  1           0         0
  0           1         0
</code>```

To df_output

```<code>   Course
0 03
1 01
2 02
</code>```

I have been looking at the solution provided at Reconstruct a categorical variable from dummies in pandas but it did not work. Please, Any help would be much appreciated.

Many Thanks,
Best Regards,
Carlo

答:
Suppose you have the following dummy DF:

```<code>In [152]: d
Out[152]:
    id  T_30  T_40  T_50
0  id1     0     1     1
1  id2     1     0     1
</code>```

we can prepare the following helper Series:

```<code>    In [153]: v = pd.Series(d.columns.drop('id').str.replace(r'\D','').astype(int), index=d.columns.drop('id'))

In [155]: v
Out[155]:
T_30    30
T_40    40
T_50    50
dtype: int64
</code>```

now we can multiply them, stack and filter:

```<code>In [154]: d.set_index('id').mul(v).stack().reset_index(name='T').drop('level_1',1).query("T > 0")
Out[154]:
    id   T
1  id1  40
2  id1  50
3  id2  30
5  id2  50
</code>```

Body:
I would like to reverse a dataframe with dummy variables. For example,

from df_input:

Course_01 Course_02 Course_03
  0           0         1
  1           0         0
  0           1         0

To df_output

   Course
0 03
1 01
2 02

I have been looking at the solution provided at Reconstruct a categorical variable from dummies in pandas but it did not work. Please, Any help would be much appreciated.

Many Thanks,
Best Regards,
Carlo

Body:
Suppose you have the following dummy DF:

In [152]: d
Out[152]:
    id  T_30  T_40  T_50
0  id1     0     1     1
1  id2     1     0     1

we can prepare the following helper Series:

    In [153]: v = pd.Series(d.columns.drop('id').str.replace(r'\D','').astype(int), index=d.columns.drop('id'))

In [155]: v
Out[155]:
T_30    30
T_40    40
T_50    50
dtype: int64

now we can multiply them, stack and filter:

In [154]: d.set_index('id').mul(v).stack().reset_index(name='T').drop('level_1',1).query("T > 0")
Out[154]:
    id   T
1  id1  40
2  id1  50
3  id2  30
5  id2  50


问:
How to bind a control to an element of a XmlDocument in the ViewModel (MVVM Pattern)?
I'm trying to bind a TextBlock to an element of a XML document, it works fine if the source is a StaticResouce, but I cannot figure out the syntax to bind to the same XML document when exposed through ViewModel.

Here's the XML document:

```<code><Books>
    <Book ID="1" Name="ABC" />
    <Book ID="2" Name="DEF" />
    <Book ID="3" Name="XYZ" />
</Books>
</code>```

Binding to a StaticResource = SUCCESSFUL

The resource file contains a XmlDataProvider with reference to Books.xml:

```<code><XmlDataProvider x:Key="data" Source="Books.xml"/>
</code>```

And here's how I'm binding to the xml file.

```<code><TextBlock Text="{Binding Source={StaticResource data},XPath=/Books/Book/@Name}"/>
<XmlDataProvider x:Key="data" Source="../Views/Data.xml" />
</code>```

As I said before, the binding above works fine and it displays "ABC". However, that XmlDocument is supposed to come from SQL Server and exposed through ViewModel (MVVM Pattern).

Binding to ViewModel = FAILED

The Books property from the ViewModel is populated with the exactly same XML (see above):

```<code>public XmlDocument Books { get; set; }
</code>```

And here's the syntax that I'm using to bind to ViewModel:

```<code><TextBlock Text="{Binding Books,XPath=/Books/Book/@Name}" />
</code>```

It doesn't return anything and I'm getting the following error message:

BindingExpression with XPath cannot bind to non-XML object.

Any help is greatly appreciated.

答:
Incase you binding to a source in code-behind, you don't need to use XPath. Simple Path will do.

Code-behind

```<code>this.DataContext = Books;
</code>```

Xaml

```<code><TextBlock Text="{Binding Path=Name}"
</code>```

Body:
I'm trying to bind a TextBlock to an element of a XML document, it works fine if the source is a StaticResouce, but I cannot figure out the syntax to bind to the same XML document when exposed through ViewModel.

Here's the XML document:

<Books>
    <Book ID="1" Name="ABC" />
    <Book ID="2" Name="DEF" />
    <Book ID="3" Name="XYZ" />
</Books>

Binding to a StaticResource = SUCCESSFUL

The resource file contains a XmlDataProvider with reference to Books.xml:

<XmlDataProvider x:Key="data" Source="Books.xml"/>

And here's how I'm binding to the xml file.

<TextBlock Text="{Binding Source={StaticResource data},XPath=/Books/Book/@Name}"/>
<XmlDataProvider x:Key="data" Source="../Views/Data.xml" />

As I said before, the binding above works fine and it displays "ABC". However, that XmlDocument is supposed to come from SQL Server and exposed through ViewModel (MVVM Pattern).

Binding to ViewModel = FAILED

The Books property from the ViewModel is populated with the exactly same XML (see above):

public XmlDocument Books { get; set; }

And here's the syntax that I'm using to bind to ViewModel:

<TextBlock Text="{Binding Books,XPath=/Books/Book/@Name}" />

It doesn't return anything and I'm getting the following error message:

BindingExpression with XPath cannot bind to non-XML object.

Any help is greatly appreciated.

Body:
Incase you binding to a source in code-behind, you don't need to use XPath. Simple Path will do.

Code-behind

this.DataContext = Books;

Xaml

<TextBlock Text="{Binding Path=Name}"


问:
The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files in weblogic 12c
I can't run web application on Weblogic server 12.1.0.0 which use JDK 8
java.util.Map. Any Ideas?

Here is the stacktrace:

weblogic.servlet.jsp.CompilationException: Failed to compile JSP The
  type
      java.util.Map$Entry cannot be resolved. It is indirectly referenced from
      required .class files

Code :

    <%@page import="java.util.*"%>

     Set section = new TreeSet(sec1);

     SectionComparator sec1 = new SectionComparator();

答:
Thanks Joop Eggen you are correct
once weblogic server has been updated to 12.2.1.0.0 it worked fine.</p>


问:
how to validate url and redirect to some url using flask
I want to validate url before redirect it using Flask.

My abstract code is here...

```<code>@app.before_request
def before():
   if request.before_url == "http://127.0.0.0:8000":
       return redirect("http://127.0.0.1:5000")
</code>```

Do you have any idea?
Thanks in advance.

答:
You can use urlparse from urllib to parse the url. The function below which checks scheme, netloc and path variables which comes after parsing the url. Supports both Python 2 and 3.

```<code>try:
    # python 3
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse

def url_validator(url):
    try:
        result = urlparse(url)
        return all([result.scheme, result.netloc, result.path])
    except:
        return False
</code>```

Body:
I want to validate url before redirect it using Flask.

My abstract code is here...

@app.before_request
def before():
   if request.before_url == "http://127.0.0.0:8000":
       return redirect("http://127.0.0.1:5000")

Do you have any idea?
Thanks in advance.

Body:
You can use urlparse from urllib to parse the url. The function below which checks scheme, netloc and path variables which comes after parsing the url. Supports both Python 2 and 3.

try:
    # python 3
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse

def url_validator(url):
    try:
        result = urlparse(url)
        return all([result.scheme, result.netloc, result.path])
    except:
        return False


问:
How to change the default icon on the SearchView, to be use in the action bar on Android?
I'm having a bit of  trouble customizing the search icon in the SearchView. On my point of view, the icon can be changed in the Item attributes, right? Just check the code bellow..

Can someone tell me what I'm doing wrong?

This is the menu I'm using, with my custom search icon icn_lupa. But when I run the app, I always get the default search icon...

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_search"
      android:title="@string/menu_search"
      android:icon="@drawable/icn_lupa"
      android:showAsAction="always"
      android:actionViewClass="android.widget.SearchView" />
</menu>
</code>```

答:
Desperate solution using Kotlin

```<code>    val s = (searchView.getAllChildren().firstOrNull() as? LinearLayout)?.getAllChildren()?.filter { it is AppCompatImageView }?.firstOrNull() as? AppCompatImageView
    s?.setImageResource(R.drawable.search)
</code>```

getAllChildren:

```<code>fun ViewGroup.getAllChildren() : ArrayList<View> {
val views = ArrayList<View>()
for (i in 0..(childCount-1)) {
    views.add(getChildAt(i))
}
return views
}
</code>```

Hope it helps someone.

Body:
I'm having a bit of  trouble customizing the search icon in the SearchView. On my point of view, the icon can be changed in the Item attributes, right? Just check the code bellow..

Can someone tell me what I'm doing wrong?

This is the menu I'm using, with my custom search icon icn_lupa. But when I run the app, I always get the default search icon...

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_search"
      android:title="@string/menu_search"
      android:icon="@drawable/icn_lupa"
      android:showAsAction="always"
      android:actionViewClass="android.widget.SearchView" />
</menu>

Body:
Desperate solution using Kotlin

    val s = (searchView.getAllChildren().firstOrNull() as? LinearLayout)?.getAllChildren()?.filter { it is AppCompatImageView }?.firstOrNull() as? AppCompatImageView
    s?.setImageResource(R.drawable.search)

getAllChildren:

fun ViewGroup.getAllChildren() : ArrayList<View> {
val views = ArrayList<View>()
for (i in 0..(childCount-1)) {
    views.add(getChildAt(i))
}
return views
}

Hope it helps someone.


问:
determining whether a window is in desktop bounds c++
I wrote some code to determinate whether a certain window is inside the desktop bounds.

Somehow, it doesn't work. For every window, regardless whether it is inside or outside the desktop, false is returned. Something is terribly wrong here, but after staring at this piece of code for 3 hours now, I still don't know where the problem is. If I try to read a RECT struct from the pointer sent in the PMSG's WPARAM, I get a AccessViolationException. Why is this happening?

My code look like this, and always returns false:

```<code>static bool IsInBounds(HWND window)
{
    DEVMODE d;
    d.dmSize = sizeof(DEVMODE);
    BOOL b = EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &d);
    if(b == FALSE)
    {
        PostMessage(FindWindow(NULL, L"Window #1"), RegisterWindowMessage(L"FMSG"), (WPARAM)window, NULL);
    }
    RECT R;
    GetWindowRect(window, &R);
    POINT p = POINT();
    p.x = (LONG)d.dmPelsWidth;
    p.y = (LONG)d.dmPelsHeight;
    PostMessage(FindWindow(NULL, L"Window #1"), RegisterWindowMessage(L"PMSG"), (WPARAM)&R, d.dmPelsWidth);
    if(R.right < 0 || R.bottom < 0 || R.left > (LONG)d.dmPelsWidth || R.top > (LONG)d.dmPelsHeight)
    {
        return false;
    }
    return true;
}
</code>```

EDIT:
after calling IsInBounds, which returned an error number 1400 (Invalid window handle), but before returning from the hook callback, I called IsWindow(window), to see, if my handle is still valid. The truth is: it is in deed a valid handle! How can it be that GetWindowRect says its an invalid handle?

EDIT:
I tried MonitorFromWindow as sujested, but it returned NULL, and calling GetLastError resulted in error no. 1400, which is already familiar to me. Looks like MonitorFromWindow implicitly calls GetWindowRect. I don't care about the size, but is there another way to get window coordinates from a handle?

答:
PostMessage(FindWindow(NULL, L"Window #1"), RegisterWindowMessage(L"PMSG"), (WPARAM)&R, d.dmPelsWidth); will not work if "Window #1" is in another process, you can't just pass a RECT pointer cross process, if you need to pass something larger than a pointer cross process, use WM_COPYDATA. Even if it is not cross process, the fact that you are using PostMessage and not SendMessage means that the RECT is probably out of scope by the time the message is processed!

Using EnumDisplaySettings is a bit overkill, MonitorFromWindow with MONITOR_DEFAULTTONULL should be all you need.

Body:
I wrote some code to determinate whether a certain window is inside the desktop bounds.

Somehow, it doesn't work. For every window, regardless whether it is inside or outside the desktop, false is returned. Something is terribly wrong here, but after staring at this piece of code for 3 hours now, I still don't know where the problem is. If I try to read a RECT struct from the pointer sent in the PMSG's WPARAM, I get a AccessViolationException. Why is this happening?

My code look like this, and always returns false:

static bool IsInBounds(HWND window)
{
    DEVMODE d;
    d.dmSize = sizeof(DEVMODE);
    BOOL b = EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &d);
    if(b == FALSE)
    {
        PostMessage(FindWindow(NULL, L"Window #1"), RegisterWindowMessage(L"FMSG"), (WPARAM)window, NULL);
    }
    RECT R;
    GetWindowRect(window, &R);
    POINT p = POINT();
    p.x = (LONG)d.dmPelsWidth;
    p.y = (LONG)d.dmPelsHeight;
    PostMessage(FindWindow(NULL, L"Window #1"), RegisterWindowMessage(L"PMSG"), (WPARAM)&R, d.dmPelsWidth);
    if(R.right < 0 || R.bottom < 0 || R.left > (LONG)d.dmPelsWidth || R.top > (LONG)d.dmPelsHeight)
    {
        return false;
    }
    return true;
}

EDIT:
after calling IsInBounds, which returned an error number 1400 (Invalid window handle), but before returning from the hook callback, I called IsWindow(window), to see, if my handle is still valid. The truth is: it is in deed a valid handle! How can it be that GetWindowRect says its an invalid handle?

EDIT:
I tried MonitorFromWindow as sujested, but it returned NULL, and calling GetLastError resulted in error no. 1400, which is already familiar to me. Looks like MonitorFromWindow implicitly calls GetWindowRect. I don't care about the size, but is there another way to get window coordinates from a handle?


问:
RabbitMQ asynchronous support
Does the RabbitMQ .NET client have any sort of asynchronous support? I'd like to be able to connect and consume messages asynchronously, but haven't found a way to do either so far.

(For consuming messages I can use the EventingBasicConsumer, but that's not a complete solution.)

Just to give some context, this is an example of how I'm working with RabbitMQ at the moment (code taken from my blog):

```<code>var factory = new ConnectionFactory() { HostName = "localhost" };

using (var connection = factory.CreateConnection())
{
    using (var channel = connection.CreateModel())
    {
        channel.QueueDeclare("testqueue", true, false, false, null);

        var consumer = new EventingBasicConsumer(channel);
        consumer.Received += Consumer_Received;
        channel.BasicConsume("testqueue", true, consumer);

        Console.ReadLine();
    }
}
</code>```

答:
Rabbit supports dispatching to asynchronous message handlers using the AsyncEventingBasicConsumer class. It works similarly to EventingBasicConsumer, but allows you to register a callback which returns a Task. The callback is dispatched to and the returned Task is awaited by the RabbitMQ client.

```<code>var factory = new ConnectionFactory
{
    HostName = "localhost",
    DispatchConsumersAsync = true
};

using(var connection = cf.CreateConnection())
{
    using(var channel = conn.CreateModel())
    {
        channel.QueueDeclare("testqueue", true, false, false, null);

        var consumer = new AsyncEventingBasicConsumer(model);

        consumer.Received += async (o, a) =>
        {
            Console.WriteLine("Message Get" + a.DeliveryTag);
            await Task.Yield();
        };
    }

    Console.ReadLine();
}
</code>```

Title: RabbitMQ asynchronous support

Body:
Does the RabbitMQ .NET client have any sort of asynchronous support? I'd like to be able to connect and consume messages asynchronously, but haven't found a way to do either so far.

(For consuming messages I can use the EventingBasicConsumer, but that's not a complete solution.)

Just to give some context, this is an example of how I'm working with RabbitMQ at the moment (code taken from my blog):

var factory = new ConnectionFactory() { HostName = "localhost" };

using (var connection = factory.CreateConnection())
{
    using (var channel = connection.CreateModel())
    {
        channel.QueueDeclare("testqueue", true, false, false, null);

        var consumer = new EventingBasicConsumer(channel);
        consumer.Received += Consumer_Received;
        channel.BasicConsume("testqueue", true, consumer);

        Console.ReadLine();
    }
}

Body:
Rabbit supports dispatching to asynchronous message handlers using the AsyncEventingBasicConsumer class. It works similarly to EventingBasicConsumer, but allows you to register a callback which returns a Task. The callback is dispatched to and the returned Task is awaited by the RabbitMQ client.

var factory = new ConnectionFactory
{
    HostName = "localhost",
    DispatchConsumersAsync = true
};

using(var connection = cf.CreateConnection())
{
    using(var channel = conn.CreateModel())
    {
        channel.QueueDeclare("testqueue", true, false, false, null);

        var consumer = new AsyncEventingBasicConsumer(model);

        consumer.Received += async (o, a) =>
        {
            Console.WriteLine("Message Get" + a.DeliveryTag);
            await Task.Yield();
        };
    }

    Console.ReadLine();
}


问:
looping through an array backwards from current position
I am quite new to java and android so be patient with me. I have an xml layout containing two buttons. One containing text of "previous" and the other "next". I also have a class containing array of strings which loops in an ascending order in a textView when a "next" button is clicked.

What i want is that i want the array to loop backwards from its current position when the "previous" button is clicked. Any ideas?

Question Class

```<code>// This file contains questions from QuestionBank
class Question{
    // array of questions
    private String mQuestions [] = {
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
    // method returns number of questions
    int getLength(){
        return mQuestions.length;
    }

    // method returns question from array textQuestions[] based on array index
    String getQuestion(int a) {
        return mQuestions[a];
    }
}
</code>```

Main Activity.java

```<code>     public class MainActivityextends AppCompatActivity {
                private QuestionLibraryBeginner mQuestionLibrary = new QuestionLibraryBeginner();
                private int mQuestionNumber = 1; // current question number
            //initialising navigation buttons
                private Button mPrevious;
                private Button mNext;
            private TextView mQuestionText;
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_beginner_review);
                    mPrevious = (Button) findViewById(R.id.previous);
                    mNext = (Button) findViewById(R.id.next);
  mQuestionText = (TextView) findViewById(R.id.txtQuestion);
                    // receive the current question number from last activity by Intent

        Intent intent = getIntent();
             currentQuestionNumber = intent.getIntExtra("quizNumber", 0); // receiving the number of questions the user has attempted from previous activity
                    mNext.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
    // checking against total number of questions the user has attempted instead of total number of questions from Question Class
    if (mQuestionNumber < currentQuestionNumber) {
             updateQuestion();
                        }
                    });
                    mPrevious.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
            // i want it to loop backwards from here
                        }
                    });

            // logic to update question from array
                private void updateQuestion() {
                    if (mQuestionNumber < mQuestionLibrary.getLength()) {
                        mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
                        mQuestionNumber++;
                    }
                }

            }
</code>```

答:
I would suggest to do this:

1) Rename updateQuestion method to nextQuestion

2) Create a method to decrease the mQuestionNumber like this:

```<code>private void prevQuestion(){
    if(mQuestionNumber > 0){
    mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
    mQuestionNumber--;}
}
</code>```

Body:
I am quite new to java and android so be patient with me. I have an xml layout containing two buttons. One containing text of "previous" and the other "next". I also have a class containing array of strings which loops in an ascending order in a textView when a "next" button is clicked.

What i want is that i want the array to loop backwards from its current position when the "previous" button is clicked. Any ideas?

Question Class

// This file contains questions from QuestionBank
class Question{
    // array of questions
    private String mQuestions [] = {
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
    // method returns number of questions
    int getLength(){
        return mQuestions.length;
    }

    // method returns question from array textQuestions[] based on array index
    String getQuestion(int a) {
        return mQuestions[a];
    }
}

Main Activity.java

     public class MainActivityextends AppCompatActivity {
                private QuestionLibraryBeginner mQuestionLibrary = new QuestionLibraryBeginner();
                private int mQuestionNumber = 1; // current question number
            //initialising navigation buttons
                private Button mPrevious;
                private Button mNext;
            private TextView mQuestionText;
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_beginner_review);
                    mPrevious = (Button) findViewById(R.id.previous);
                    mNext = (Button) findViewById(R.id.next);
  mQuestionText = (TextView) findViewById(R.id.txtQuestion);
                    // receive the current question number from last activity by Intent

        Intent intent = getIntent();
             currentQuestionNumber = intent.getIntExtra("quizNumber", 0); // receiving the number of questions the user has attempted from previous activity
                    mNext.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
    // checking against total number of questions the user has attempted instead of total number of questions from Question Class
    if (mQuestionNumber < currentQuestionNumber) {
             updateQuestion();
                        }
                    });
                    mPrevious.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
            // i want it to loop backwards from here
                        }
                    });

            // logic to update question from array
                private void updateQuestion() {
                    if (mQuestionNumber < mQuestionLibrary.getLength()) {
                        mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
                        mQuestionNumber++;
                    }
                }

            }

Body:
I would suggest to do this:

1) Rename updateQuestion method to nextQuestion

2) Create a method to decrease the mQuestionNumber like this:

private void prevQuestion(){
    if(mQuestionNumber > 0){
    mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
    mQuestionNumber--;}
}


问:
Sql avg using query
My question today goes like this:

How many customers are above average?
I replied that way but it's wrong

```<code>select avg(height), count(*) as numofppl
from client
group by height
having height > avg(height)
</code>```

Someone can offer a different solution(who work:))

答:
```<code>select count(*) as numofppl
from client
where height > ( select avg(height) from client )
</code>```

Title: Sql avg using query

Body:
My question today goes like this:

How many customers are above average?
I replied that way but it's wrong

select avg(height), count(*) as numofppl
from client
group by height
having height > avg(height)

Someone can offer a different solution(who work:))