问:
How to unsubscribe from valueChanges in Angular 4 reactive forms?
I am making a reactive form in Angular 4 and looking for valueChanges in the form like below:

```<code>this.searchForm.valueChanges.subscribe((value) => {
   console.log(value);
});
</code>```

The above code works perfectly. But how to unsubscribe from the valueChanges on ngOnDestroy() as this.searchForm.valueChanges.unsubscribe() doesn't seem to work. Please help me solve this.

答:
@Suren has the right answer, I would just like to add some code I use when I have many subscriptions.</p>

```<code>...
this.subscriptions.push(this.searchForm.valueChanges.subscribe((value) => {
   console.log(value);
}));
...

private subscriptions: Subscription[] = [];

ngOnDestroy(): void {
    this.subscriptions.forEach((sub) => {
        sub.unsubscribe();
    })
}
</code>```

Body:
I am making a reactive form in Angular 4 and looking for valueChanges in the form like below:

this.searchForm.valueChanges.subscribe((value) => {
   console.log(value);
});

The above code works perfectly. But how to unsubscribe from the valueChanges on ngOnDestroy() as this.searchForm.valueChanges.unsubscribe() doesn't seem to work. Please help me solve this.

Body:
@Suren has the right answer, I would just like to add some code I use when I have many subscriptions.

...
this.subscriptions.push(this.searchForm.valueChanges.subscribe((value) => {
   console.log(value);
}));
...

private subscriptions: Subscription[] = [];

ngOnDestroy(): void {
    this.subscriptions.forEach((sub) => {
        sub.unsubscribe();
    })
}


来源: stackexchange

问:
Non-trivial geolocation query db caching
I first have to say that I really am a rookie in caching, so please do elaborate on any explanation and bear with me if my question is stupid.

I have a server with pretty limited resources, so I'm really interested in caching db-queries as effectively as I can. My issue is this:

I have a MYSQL DB with a table for geolocations, there are columns (lat and lng) - I only indexed lat since a query will always have both lat and lng, and only 1 index can be effectively used to my understanding (?).

The queries are very alternating in coordinates like

```<code>select lat, lng
where lat BETWEEN 123123123 AND 312412312 AND lng BETWEEN 235124231 AND 34123124
</code>```

where the long numbers that are the boundaries of the BETWEEN query are constantly changing, so IS there a way to cache this the smart way, so that the cache doesn't have to be a complete query match, but the values of previous between queries can be held against a new to save some db resources?

I hope you get my question - if not please ask.

Thank you so much

Update 24/01/2011

Now that I've gotten some response I want to know what the most efficient way of querying would be.

Would the Between query with int values execute faster or

would the radius calculation with point values execute faster

if 1. then how would the optimal index look like?

答:
If your table is MyISAM you can use Point datatype (see this answer for more details)

If you are not willing or are not able to use spatial indexes, you should two separate indexes:

```<code>CREATE INDEX ix_mytable_lat_lon ON mytable (lat, lon)
CREATE INDEX ix_mytable_lon_lat ON mytable (lon, lat)
</code>```

In this case, MySQL can use an index_intersect over these indexes which is sometimes faster than mere filtering with a single index.

Even if it does not, it can pick a more selective index if there are two of those.

As for the caching, all pages read from the indexes are cached and reside in memory until they will be overwritten with hotter data (it not all database fits to the cache).

This will prevent MySQL from the need to read the data from disk.

MySQL is also able to cache the whole resultsets in memory, however, this requires the query to be repeated verbatim, with all parameters exactly the same.

ContentLicense: CC BY-SA 3.0

Body:
I first have to say that I really am a rookie in caching, so please do elaborate on any explanation and bear with me if my question is stupid.

I have a server with pretty limited resources, so I'm really interested in caching db-queries as effectively as I can. My issue is this:

I have a MYSQL DB with a table for geolocations, there are columns (lat and lng) - I only indexed lat since a query will always have both lat and lng, and only 1 index can be effectively used to my understanding (?).

The queries are very alternating in coordinates like

select lat, lng
where lat BETWEEN 123123123 AND 312412312 AND lng BETWEEN 235124231 AND 34123124

where the long numbers that are the boundaries of the BETWEEN query are constantly changing, so IS there a way to cache this the smart way, so that the cache doesn't have to be a complete query match, but the values of previous between queries can be held against a new to save some db resources?

I hope you get my question - if not please ask.

Thank you so much

Update 24/01/2011

Now that I've gotten some response I want to know what the most efficient way of querying would be.

Would the Between query with int values execute faster or

would the radius calculation with point values execute faster

if 1. then how would the optimal index look like?

Body:
If your table is MyISAM you can use Point datatype (see this answer for more details)

If you are not willing or are not able to use spatial indexes, you should two separate indexes:

CREATE INDEX ix_mytable_lat_lon ON mytable (lat, lon)
CREATE INDEX ix_mytable_lon_lat ON mytable (lon, lat)

In this case, MySQL can use an index_intersect over these indexes which is sometimes faster than mere filtering with a single index.

Even if it does not, it can pick a more selective index if there are two of those.

As for the caching, all pages read from the indexes are cached and reside in memory until they will be overwritten with hotter data (it not all database fits to the cache).

This will prevent MySQL from the need to read the data from disk.

MySQL is also able to cache the whole resultsets in memory, however, this requires the query to be repeated verbatim, with all parameters exactly the same.

ContentLicense: CC BY-SA 2.5


问:
How can I make my simple Haskell function recursive?
This is my function:

```<code>rotatebyone :: [Int] -> [Int]
rotatebyone [] = []
rotatebyone (x:xs) = ((tail (x:xs)) ++ (take 1 (x:xs)))

rotatebyn :: Int -> [Int] -> [Int]
rotatebyn n [] = []
rotatebyn 1 (x:xs) = rotatebyone (x:xs)
rotatebyn 2 (x:xs) = (rotatebyone (rotatebyone (x:xs)))
</code>```

I want my function to repeat itself for n-times. I guess you do this with guardians or the "while" operator, but I don't know quite how. The goal is to rotate elements of a integer-list n-times.

This was my failed approach:

```<code>rota :: Int -> [Int] -> [Int]
rota n (x:xs) = rotatebyone (x:xs)
                where
                rota n
                    | n > 1 = rota (n - 1)
                    | otherwise = rotatebyone (x:xs)
</code>```

答:
Let us first clean up the rotatebyone function:

```<code>rotatebyone :: [Int] -> [Int]
rotatebyone [] = []
rotatebyone (x:xs) = ((tail (x:xs)) ++ (take 1 (x:xs)))
</code>```

Here you call tail on (x:xs) but that is quite weird, since we already have a tail: xs. So we can replace tail (x:xs) with xs.

The same holds for take 1 (x:xs). This will construct a list with the head of the list, so [x]. So we can clean up the code to:

```<code>rotatebyone :: [Int] -> [Int]
rotatebyone [] = []
rotatebyone (x:xs) = <b>xs</b> ++ <b>[x]</b></code>```

Furthermore your function only works on lists of type Int (it has signature [Int] -> [Int]). We can however rotate lists by one regardless the type of elements these lists hold, so we can write it as:

```<code>rotatebyone :: [<b>a</b>] -> [<b>a</b>]
rotatebyone [] = []
rotatebyone (x:xs) = xs ++ [x]</code>```

Now we can look for a way to rotate n times with:

```<code>rotatebyn :: <b>Int -></b>[<b>a</b>] -> [<b>a</b>]
rotatebyn ...</code>```

In case we wish to rotate over zero places, then the list remains the same, so as a base case we can write:

```<code>rotatebyn 0 l = l
</code>```

and in case we want to rotate over one or more places, we can rotate over one place by the rotatebyone function, and then rotate this result another n-1 times:

```<code>rotatebyn n l = rotatebyn (n-1) (rotateone n)
</code>```

or these together:

```<code>rotatebyn :: Int ->[a] -> [a]
rotatebyn 0 l = l
rotatebyn n l = rotatebyn (n-1) (rotateone n)
</code>```

But the above is, like @dfeuer says not efficient: it takes O(n) time to rotate a list, if we need to do this k times, the time complexity is thus O(n k).

Note furthermore that the above function only works in case n is greater than or equal to zero.

Body:
This is my function:

rotatebyone :: [Int] -> [Int]
rotatebyone [] = []
rotatebyone (x:xs) = ((tail (x:xs)) ++ (take 1 (x:xs)))

rotatebyn :: Int -> [Int] -> [Int]
rotatebyn n [] = []
rotatebyn 1 (x:xs) = rotatebyone (x:xs)
rotatebyn 2 (x:xs) = (rotatebyone (rotatebyone (x:xs)))

I want my function to repeat itself for n-times. I guess you do this with guardians or the "while" operator, but I don't know quite how. The goal is to rotate elements of a integer-list n-times.

This was my failed approach:

rota :: Int -> [Int] -> [Int]
rota n (x:xs) = rotatebyone (x:xs)
                where
                rota n
                    | n > 1 = rota (n - 1)
                    | otherwise = rotatebyone (x:xs)

Body:
Let us first clean up the rotatebyone function:

rotatebyone :: [Int] -> [Int]
rotatebyone [] = []
rotatebyone (x:xs) = ((tail (x:xs)) ++ (take 1 (x:xs)))

Here you call tail on (x:xs) but that is quite weird, since we already have a tail: xs. So we can replace tail (x:xs) with xs.

The same holds for take 1 (x:xs). This will construct a list with the head of the list, so [x]. So we can clean up the code to:

rotatebyone :: [Int] -> [Int]
rotatebyone [] = []
rotatebyone (x:xs) = xs ++ [x]

Furthermore your function only works on lists of type Int (it has signature [Int] -> [Int]). We can however rotate lists by one regardless the type of elements these lists hold, so we can write it as:

rotatebyone :: [a] -> [a]
rotatebyone [] = []
rotatebyone (x:xs) = xs ++ [x]

Now we can look for a way to rotate n times with:

rotatebyn :: Int ->[a] -> [a]
rotatebyn ...

In case we wish to rotate over zero places, then the list remains the same, so as a base case we can write:

rotatebyn 0 l = l

and in case we want to rotate over one or more places, we can rotate over one place by the rotatebyone function, and then rotate this result another n-1 times:

rotatebyn n l = rotatebyn (n-1) (rotateone n)

or these together:

rotatebyn :: Int ->[a] -> [a]
rotatebyn 0 l = l
rotatebyn n l = rotatebyn (n-1) (rotateone n)

But the above is, like @dfeuer says not efficient: it takes O(n) time to rotate a list, if we need to do this k times, the time complexity is thus O(n k).

Note furthermore that the above function only works in case n is greater than or equal to zero.


问:
How to convert Json to CSV in php
Hi I am trying to convert a json file with differrent array structure than the normal one into csv file. I had been trying to find out a solution to convert it into a csv file but I cant find the solution.

```<code>  <?php
    $jsondata = '[{
        "accession_number_original": "2012.11.45",
        "author_birth_date": [
          "1932"
        ],
        "author_date": [
          "1932"
        ],
        "author_death_date": [
          ""
        ],
        "author_description": [
          "American"
        ],
        "author_display": [
          "Day yon"
        ],
        "author_names_first": [
          "Day"
        ],
        "author_names_last": [
          "yon"
        ],
        "author_names_middle": [
          ""
        ],
        "image_height": "12 1/2",
        "image_width": "18 1/4",
        "jp2_image_url": "",
        "location_physical_location": "Art Gallery",
        "location_shelf_locator": "Unknown",
        "master_image_url": "",
        "note_provenance": "Gift of Gary Ginsberg and Susanna Aaron",
        "object_date": "1963/2010",
        "object_depth": "",
        "object_height": "",
        "object_width": "",
        "origin_datecreated_end": "1963",
        "origin_datecreated_start": "1963",
        "physical_description_extent": [
          "12 1/2 x 18 1/4"
        ],
        "physical_description_material": [
          "Gelatin silver print"
        ],
        "physical_description_technique": [
          "Gelatin silver print"
        ],
        "pid": "bdr:123456",
        "title": "As Demonstrators"
      }]';

    $jsonDecoded = json_decode($jsondata);
    print_r('```');
    print_r($jsonDecoded);
    print_r('```');
    $fh = fopen('fileout.csv', 'w');
    if (is_array($jsonDecoded)){
      print_r('<-------- line variable output-------->');
      foreach($jsonDecoded as $line){
            print_r('```'); print_r($line); print_r('```');
        print_r('<-------- data variable output-------->');
        if (is_array($line)||is_object($line)){
          foreach($line as $data){
            fputcsv($fp,$data);
            }
          }
        }
      }
    }

   fclose($fh);
   print_r('Converted Successfully');
?>
</code>```

I tried looking into most of the similar questions in the stackoverflow but none has a array of my kind so they are not much useful to me.

If I use single foreach I am getting error Array to String Conversion failed and Array is being printed as value instead of actual data into the csv file.

If I use two foreach I am getting error fputcsv() expects parameter 2 to be array string given

var_dump or print_r result of decoded json is as follows

```<code>Array
(
[0] => stdClass Object
    (
        [accession_number_original] => 2012.11.45
        [author_birth_date] => Array
            (
                [0] => 1932
            )

        [author_date] => Array
            (
                [0] => 1932
            )

        [author_death_date] => Array
            (
                [0] =>
            )

        [author_description] => Array
            (
                [0] => American
            )

        [author_display] => Array
            (
                [0] => Day yon
            )

        [author_names_first] => Array
            (
                [0] => Day
            )

        [author_names_last] => Array
            (
                [0] => yon
            )

        [author_names_middle] => Array
            (
                [0] =>
            )

        [image_height] => 12 1/2
        [image_width] => 18 1/4
        [jp2_image_url] =>
        [location_physical_location] => Art Gallery
        [location_shelf_locator] => Unknown
        [master_image_url] =>
        [note_provenance] => Gift of Gary Ginsberg and Susanna Aaron
        [object_date] => 1963/2010
        [object_depth] =>
        [object_height] =>
        [object_width] =>
        [origin_datecreated_end] => 1963
        [origin_datecreated_start] => 1963
        [physical_description_extent] => Array
            (
                [0] => 12 1/2 x 18 1/4
            )

        [physical_description_material] => Array
            (
                [0] => Gelatin silver print
            )

        [physical_description_technique] => Array
            (
                [0] => Gelatin silver print
            )

        [pid] => bdr:123456
        [title] => As Demonstrators
    )
)
</code>```

答:
Used PHPExcel library that's help me to convert my json file into excel sheet.
https://github.com/PHPOffice/PHPExcel</p>

```<code>                $keyName=array();
                $i=0;
                $current_data=file_get_contents($dir.$excelFileLocation,true);
                $excelFile=fopen($dir."ExcelTojson.xls","w+");
                $array_data=json_decode($current_data,true);
                foreach($array_data as $jsonValue)
                {
                    foreach($jsonValue as $key => $value)
                    {
                        if($i==0)
                        {
                            $keyName[$i]=$key;
                            $i++;
                        }
                        else
                        {
                            $check=0;
                            for($j=0;$j<count($keyName);$j++)
                            {
                                if($keyName[$j]==$key)
                                {
                                    $check=1;
                                    break;
                                }
                            }
                            if($check==0)
                            {
                                $keyName[$i]=$key;
                                $i++;
                            }
                        }
                    }
                }
                $excelSheet = PHPExcel_IOFactory::load($dir."ExcelTojson.xls");
                $excelSheet->setActiveSheetIndex(0);
                $ascii=65;
                for($i=0;$i<count($keyName);$i++)
                {
                    $excelSheet->getActiveSheet()->setCellValue(chr($ascii)."1",stripslashes($keyName[$i]));
                    $ascii+=1;
                }
                $cellValue=2;
                foreach($array_data as $jsonValue)
                {
                    $ascii=65;
                    foreach($jsonValue as $key => $value)
                    {
                        $excelSheet->getActiveSheet()->setCellValue(chr($ascii).$cellValue,stripslashes($value));
                        $ascii+=1;
                    }
                    $cellValue+=1;
                }

                $filename="ExcelTojson.xls";
                header('Content-Type: application/vnd.ms-excel');
                header('Content-Disposition: attachment;filename="'.$filename.'"');
                header('Cache-Control: max-age=0');
                $objWriter = PHPExcel_IOFactory::createWriter($excelSheet, 'Excel5');
                $objWriter->save('php://output');
</code>```

Title: How to convert Json to CSV in php

Body:
Hi I am trying to convert a json file with differrent array structure than the normal one into csv file. I had been trying to find out a solution to convert it into a csv file but I cant find the solution.

  <?php
    $jsondata = '[{
        "accession_number_original": "2012.11.45",
        "author_birth_date": [
          "1932"
        ],
        "author_date": [
          "1932"
        ],
        "author_death_date": [
          ""
        ],
        "author_description": [
          "American"
        ],
        "author_display": [
          "Day yon"
        ],
        "author_names_first": [
          "Day"
        ],
        "author_names_last": [
          "yon"
        ],
        "author_names_middle": [
          ""
        ],
        "image_height": "12 1/2",
        "image_width": "18 1/4",
        "jp2_image_url": "",
        "location_physical_location": "Art Gallery",
        "location_shelf_locator": "Unknown",
        "master_image_url": "",
        "note_provenance": "Gift of Gary Ginsberg and Susanna Aaron",
        "object_date": "1963/2010",
        "object_depth": "",
        "object_height": "",
        "object_width": "",
        "origin_datecreated_end": "1963",
        "origin_datecreated_start": "1963",
        "physical_description_extent": [
          "12 1/2 x 18 1/4"
        ],
        "physical_description_material": [
          "Gelatin silver print"
        ],
        "physical_description_technique": [
          "Gelatin silver print"
        ],
        "pid": "bdr:123456",
        "title": "As Demonstrators"
      }]';

    $jsonDecoded = json_decode($jsondata);
    print_r('
');
    print_r($jsonDecoded);
    print_r('
');
    $fh = fopen('fileout.csv', 'w');
    if (is_array($jsonDecoded)){
      print_r('<-------- line variable output-------->');
      foreach($jsonDecoded as $line){
            print_r('
'); print_r($line); print_r('
');
        print_r('<-------- data variable output-------->');
        if (is_array($line)||is_object($line)){
          foreach($line as $data){
            fputcsv($fp,$data);
            }
          }
        }
      }
    }

   fclose($fh);
   print_r('Converted Successfully');
?>

I tried looking into most of the similar questions in the stackoverflow but none has a array of my kind so they are not much useful to me.

If I use single foreach I am getting error Array to String Conversion failed and Array is being printed as value instead of actual data into the csv file.

If I use two foreach I am getting error fputcsv() expects parameter 2 to be array string given

var_dump or print_r result of decoded json is as follows

Array
(
[0] => stdClass Object
    (
        [accession_number_original] => 2012.11.45
        [author_birth_date] => Array
            (
                [0] => 1932
            )

        [author_date] => Array
            (
                [0] => 1932
            )

        [author_death_date] => Array
            (
                [0] =>
            )

        [author_description] => Array
            (
                [0] => American
            )

        [author_display] => Array
            (
                [0] => Day yon
            )

        [author_names_first] => Array
            (
                [0] => Day
            )

        [author_names_last] => Array
            (
                [0] => yon
            )

        [author_names_middle] => Array
            (
                [0] =>
            )

        [image_height] => 12 1/2
        [image_width] => 18 1/4
        [jp2_image_url] =>
        [location_physical_location] => Art Gallery
        [location_shelf_locator] => Unknown
        [master_image_url] =>
        [note_provenance] => Gift of Gary Ginsberg and Susanna Aaron
        [object_date] => 1963/2010
        [object_depth] =>
        [object_height] =>
        [object_width] =>
        [origin_datecreated_end] => 1963
        [origin_datecreated_start] => 1963
        [physical_description_extent] => Array
            (
                [0] => 12 1/2 x 18 1/4
            )

        [physical_description_material] => Array
            (
                [0] => Gelatin silver print
            )

        [physical_description_technique] => Array
            (
                [0] => Gelatin silver print
            )

        [pid] => bdr:123456
        [title] => As Demonstrators
    )
)

Body:
Used PHPExcel library that's help me to convert my json file into excel sheet.
https://github.com/PHPOffice/PHPExcel

                $keyName=array();
                $i=0;
                $current_data=file_get_contents($dir.$excelFileLocation,true);
                $excelFile=fopen($dir."ExcelTojson.xls","w+");
                $array_data=json_decode($current_data,true);
                foreach($array_data as $jsonValue)
                {
                    foreach($jsonValue as $key => $value)
                    {
                        if($i==0)
                        {
                            $keyName[$i]=$key;
                            $i++;
                        }
                        else
                        {
                            $check=0;
                            for($j=0;$j<count($keyName);$j++)
                            {
                                if($keyName[$j]==$key)
                                {
                                    $check=1;
                                    break;
                                }
                            }
                            if($check==0)
                            {
                                $keyName[$i]=$key;
                                $i++;
                            }
                        }
                    }
                }
                $excelSheet = PHPExcel_IOFactory::load($dir."ExcelTojson.xls");
                $excelSheet->setActiveSheetIndex(0);
                $ascii=65;
                for($i=0;$i<count($keyName);$i++)
                {
                    $excelSheet->getActiveSheet()->setCellValue(chr($ascii)."1",stripslashes($keyName[$i]));
                    $ascii+=1;
                }
                $cellValue=2;
                foreach($array_data as $jsonValue)
                {
                    $ascii=65;
                    foreach($jsonValue as $key => $value)
                    {
                        $excelSheet->getActiveSheet()->setCellValue(chr($ascii).$cellValue,stripslashes($value));
                        $ascii+=1;
                    }
                    $cellValue+=1;
                }

                $filename="ExcelTojson.xls";
                header('Content-Type: application/vnd.ms-excel');
                header('Content-Disposition: attachment;filename="'.$filename.'"');
                header('Cache-Control: max-age=0');
                $objWriter = PHPExcel_IOFactory::createWriter($excelSheet, 'Excel5');
                $objWriter->save('php://output');


问:
Jupyter Notebook figure size settings
If I plot a graph or display a table in Jupyter Notebook the figures are really small and unreadable. What is the best way to set the figure size settings globally in Jupyter Notebook? For comparison in Quantopian's Notebook version plots and tables are a lot larger. I know there are separate settings for matplotlib and other libraries but I would like to set global settings. I also tried this setting, but it didn't work.

```<code>%config InlineBackend.figure_format='retina'
</code>```

答:
If "globally" means for all successive outputs in a given notebook, I use

```<code>plt.rcParams['figure.figsize'] = (16,8)
</code>```

after importing matplotlib. This affect all subsequent plots. If you wish a single configuration for all notebooks, the reply by Louise Davies is more appropriate.

Title: Jupyter Notebook figure size settings

Body:
If I plot a graph or display a table in Jupyter Notebook the figures are really small and unreadable. What is the best way to set the figure size settings globally in Jupyter Notebook? For comparison in Quantopian's Notebook version plots and tables are a lot larger. I know there are separate settings for matplotlib and other libraries but I would like to set global settings. I also tried this setting, but it didn't work.

%config InlineBackend.figure_format='retina'

Body:
If "globally" means for all successive outputs in a given notebook, I use

plt.rcParams['figure.figsize'] = (16,8)

after importing matplotlib. This affect all subsequent plots. If you wish a single configuration for all notebooks, the reply by Louise Davies is more appropriate.


问:
Application logging for Read permission users
Authorized users have read/view access to all production data accessed through the application and all of its components due to the application’s design. None of this read activity is logged.

Therefore, people with access to application can access all information within the system and are not restricted to just clients/specific component that apply to them.

How to maintain the Read logging in the system?
Application includes Delphi fro Frond end design, MS sql server for back end.

答:
How to maintain the Read logging in the system?

What you are looking for is called Audit.. you can configure it like below.Take below screens as guidance and modify as per your needs..

Further you can also use Audit as described here:Auditing SELECT statements in SQL Server 2008

I would go with extended events as it is light weight


问:
Beginner JS calculator
I am new into the world of JS, and I'm trying to build a basic calculator.
Everything work fine so long but I have problem displaying different elements on the result screen of the calculator.

When I click 1 then 2, 1 will disappear but I want it to stay for my calculation.

Please help!!

var displayText = document.getElementById('displayText');
var output = document.getElementById('output');
function add(){
  var two, plus, result;
  result = displayText.value;
  output.innerHTML = result;
}
function addOne() {
  var one = document.getElementById('one').value = 1;
      displayText.value = one;
}
function addTwo() {
  var two = document.getElementById('two').value = 2;
      displayText.value = two;
}
function addPlus() {
  var plus = document.getElementById('plus').value = "+";
      displayText.value = plus;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div>
  <div class="display">
    <input type="text" id="displayText" name="" value="">
    <p>The result of your calculation is: <span id="output"></span></p>
  </div>
  <div class="btn_wrap">
    <button id="one" onclick="addOne()">1</button>
    <button id="two" onclick="addTwo()">2</button>
    <button id="plus" onclick="addPlus()">+</button>
    <button id="" onclick="add()">Add</button>
  </div>
</div>
      </code>```

答:
You're resetting the value of the text field everytime you call one of your functions. You don't want to set a new text each time, you want to append the new text to the old text. So replace

```<code>displayText.value = one;
</code>```

with:

```<code>displayText.value += one;
</code>```

for each time you want to append text.

Here is a working fiddle.

Title: Beginner JS calculator

Body:
I am new into the world of JS, and I'm trying to build a basic calculator.
Everything work fine so long but I have problem displaying different elements on the result screen of the calculator.

When I click 1 then 2, 1 will disappear but I want it to stay for my calculation.

Please help!!

var displayText = document.getElementById('displayText');
var output = document.getElementById('output');
function add(){
  var two, plus, result;
  result = displayText.value;
  output.innerHTML = result;
}
function addOne() {
  var one = document.getElementById('one').value = 1;
      displayText.value = one;
}
function addTwo() {
  var two = document.getElementById('two').value = 2;
      displayText.value = two;
}
function addPlus() {
  var plus = document.getElementById('plus').value = "+";
      displayText.value = plus;
}

    <input type="text" id="displayText" name="" value="">

The result of your calculation is:

    <button id="one" onclick="addOne()">1</button>
    <button id="two" onclick="addTwo()">2</button>
    <button id="plus" onclick="addPlus()">+</button>
    <button id="" onclick="add()">Add</button>

Body:
You're resetting the value of the text field everytime you call one of your functions. You don't want to set a new text each time, you want to append the new text to the old text. So replace

displayText.value = one;

with:

displayText.value += one;

for each time you want to append text.

Here is a working fiddle.


问:
Icon fonts not loading in IE11
We're using icomoon for our icon fonts, and they work fine in Chrome and Firefox, but won't display in IE11... Sometimes.  It seems to work on the first page load, but not on subsequent page loads.  Clearing the cache doesn't seem to reset it.  This issue may be present in other IE versions, right now we're just focusing on IE11.

Here's our @font-face:

```<code>@font-face {
font-family: 'icon';
src:url('fonts/icon.eot?-3q3vo5');
src:url('fonts/icon.eot?#iefix-3q3vo5') format('embedded-opentype'),
    url('fonts/icon.woff?-3q3vo5') format('woff'),
    url('fonts/icon.ttf?-3q3vo5') format('truetype'),
    url('fonts/icon.svg?-3q3vo5#rezku') format('svg');
font-weight: normal;
font-style: normal;
}

[class^="icon-"], [class*=" icon-"] {
font-family: 'icon';
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;

/* Better Font Rendering =========== */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-alphabet:before {
content: "\e600";
}
/* etc etc etc */
</code>```

But here's where it gets weird.  Looking at the developer tools, an HTTP request for the fonts is being sent, but only a few hundred bytes are being received (probably just the headers).

But the HTTP response lists the content length correctly as several kilobytes.

The "Response body" tab just says "No data to view."

You can see in the Network Panel screenshot that the Google Fonts aren't behaving like this.

Pasting the URL in the location bar results in the full file being downloaded.

答:
After investigating the very same issue, and going through various solutions posted online, I've created the following troubleshooting list, which covers most potential causes:

Font downloads are disabled in IE, under Internet Options / Security / Custom Level / Font Downloads enable /disable. They might be disabled by your network admin, in which case you would not be able to see nor change this setting.

Your HTTP headers prevent IE from storing the font file locally. To fix, remove any Cache-Control: no-store, no-cache or Pragma: no-cache headers, or any Expires header with a date in the past. Also the Vary header has its tricks in IE, if set to anything other than Accept-Encoding, User-Agent, Host or Accept-Language then IE will not cache anything, unless an ETAG header is also present (see this MSDN blog post).

You don't set the correct MIME types for the font download. For example Jetty 9 will set by default Content-Type: text/plain for the usual font types (eot, woff, woff2). See this answer for the proper content types to use.

Make sure to use display: block or display: inline-block for your icon element.

Finally, make sure to go through the troubleshooting guide over at FontAwesome.

Title: Icon fonts not loading in IE11

Body:
We're using icomoon for our icon fonts, and they work fine in Chrome and Firefox, but won't display in IE11... Sometimes.  It seems to work on the first page load, but not on subsequent page loads.  Clearing the cache doesn't seem to reset it.  This issue may be present in other IE versions, right now we're just focusing on IE11.

Here's our @font-face:

@font-face {
font-family: 'icon';
src:url('fonts/icon.eot?-3q3vo5');
src:url('fonts/icon.eot?#iefix-3q3vo5') format('embedded-opentype'),
    url('fonts/icon.woff?-3q3vo5') format('woff'),
    url('fonts/icon.ttf?-3q3vo5') format('truetype'),
    url('fonts/icon.svg?-3q3vo5#rezku') format('svg');
font-weight: normal;
font-style: normal;
}

[class^="icon-"], [class*=" icon-"] {
font-family: 'icon';
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;

/* Better Font Rendering =========== */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-alphabet:before {
content: "\e600";
}
/* etc etc etc */

But here's where it gets weird.  Looking at the developer tools, an HTTP request for the fonts is being sent, but only a few hundred bytes are being received (probably just the headers).

But the HTTP response lists the content length correctly as several kilobytes.

The "Response body" tab just says "No data to view."

You can see in the Network Panel screenshot that the Google Fonts aren't behaving like this.

Pasting the URL in the location bar results in the full file being downloaded.


问:
codeigniter sends mail in spam
I am using the following code to send mail

but the sent mail are going in spam. How can I mark them to not spam programatically

```<code>$this->load->library('email');

 if($this->config->item('protocol')=="smtp"){
            $config['protocol'] = 'smtp';
            $config['smtp_host'] = $this->config->item('smtp_hostname');
            $config['smtp_user'] = $this->config->item('smtp_username');
            $config['smtp_pass'] = $this->config->item('smtp_password');
            $config['smtp_port'] = $this->config->item('smtp_port');
            $config['smtp_timeout'] = $this->config->item('smtp_timeout');
            $config['mailtype'] = $this->config->item('smtp_mailtype');
            $config['starttls']  = $this->config->item('starttls');
             $config['newline']  = $this->config->item('newline');

            $this->email->initialize($config);
        }
            $fromemail='jodbaki@gmail.com';
            $fromname='Jod Baki';
            $subject=$this->config->item('activation_subject');
            $message=$this->config->item('activation_message');;

            $message=str_replace('[verilink]',$verilink,$message);

            $toemail=$this->input->post('email');

            $this->email->to($toemail);
            $this->email->from($fromemail, $fromname);
            $this->email->subject($subject);
            $this->email->message($message);
            if(!$this->email->send()){
             print_r($this->email->print_debugger());
            exit;
            }
</code>```

I am sending the follwoing message

```<code>Hi,
 Thank you for registering with us. Please click below link to verify your
email address.
 <a href='http://jodbaki.com/exam/?/login/verify/'>Click Here</a>
 or
     Copy below link and visit in browser
 http://jodbaki.com/exam/?/login/verify/

 Thanks
</code>```

答:
Email services are responsible to find out if you are spamming. It has nothing to do with your code or codeigniter.

Try creating email under valid domain and prevent sending message contents that are spam like.

Here is an article to avoid your emails to be spam like:

Avoiding spam filters

Title: codeigniter sends mail in spam

Body:
I am using the following code to send mail

but the sent mail are going in spam. How can I mark them to not spam programatically

$this->load->library('email');

 if($this->config->item('protocol')=="smtp"){
            $config['protocol'] = 'smtp';
            $config['smtp_host'] = $this->config->item('smtp_hostname');
            $config['smtp_user'] = $this->config->item('smtp_username');
            $config['smtp_pass'] = $this->config->item('smtp_password');
            $config['smtp_port'] = $this->config->item('smtp_port');
            $config['smtp_timeout'] = $this->config->item('smtp_timeout');
            $config['mailtype'] = $this->config->item('smtp_mailtype');
            $config['starttls']  = $this->config->item('starttls');
             $config['newline']  = $this->config->item('newline');

            $this->email->initialize($config);
        }
            $fromemail='jodbaki@gmail.com';
            $fromname='Jod Baki';
            $subject=$this->config->item('activation_subject');
            $message=$this->config->item('activation_message');;

            $message=str_replace('[verilink]',$verilink,$message);

            $toemail=$this->input->post('email');

            $this->email->to($toemail);
            $this->email->from($fromemail, $fromname);
            $this->email->subject($subject);
            $this->email->message($message);
            if(!$this->email->send()){
             print_r($this->email->print_debugger());
            exit;
            }

I am sending the follwoing message

Hi,
 Thank you for registering with us. Please click below link to verify your
email address.
 Click Here
 or
     Copy below link and visit in browser
 http://jodbaki.com/exam/?/login/verify/

 Thanks


问:
Writing and closing Notepad++ using speech recognition libraries
I'm trying to write code that will open Notepad++, write to a file, and close it afterward. My code is included below. I'm totally new to C#. Is there any library or way to do this?</p>

```<code>// Button Reference
private void button1_Click(object sender, EventArgs e)
{
    if (button1.Text.Equals("Enable Voice Control"))
    {
        button1.Text = "Stop Voice Control";
        recEngine.RecognizeAsync(RecognizeMode.Multiple);
    }
    else
    {
        button1.Text = "Enable Voice Control";
        recEngine.RecognizeAsyncStop();
    }
}

public void Form1_Load(object sender, EventArgs e)
{
    Choices commands = new Choices();
    commands.Add(myCommands);
    GrammarBuilder gBuilder = new GrammarBuilder();
    gBuilder.Append(commands);
    Grammar grammar = new Grammar(gBuilder);

    recEngine.LoadGrammarAsync(grammar);
    recEngine.SetInputToDefaultAudioDevice();
    recEngine.SpeechRecognized += recEngine_SpeechRecognized;
}

void recEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
    Process cmd = new Process();
    cmd.StartInfo.FileName = @"notepad++.exe" ;
    //cmd.StartInfo.Arguments =@"\Write.txt";
    cmd.Start();
    cmd.CloseMainWindow();
    cmd.WaitForExit();
    cmd.Refresh();

    //if (cmd.StandardError != null)
    //Console.WriteLine(cmd.StandardError.ReadToEnd());

    var result = e.Result;
    var i = 0;
    foreach (var command in myCommands)
    {
        if (command.StartsWith("close"))
        {
            this.Close();
            //cmd.StartInfo.FileName = @"notepad++";
            cmd.Kill();
        }
        if (command.StartsWith("--") || command == string.Empty) continue;  // Skip commentBlocks and skipEmptylines
        var parts = command.Split(new char[] { '|' }); // Split the lines
        i++;
        if (command.Equals(result.Text))
        {
            Console.WriteLine("Command is  {0}: {1}", i, command);
            break;
        }
    }
}

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
</code>```

答:
You need not open notepad and write to file. You can do it programmarically.</p>

```<code>// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);

// Open the file to read from.
string readText = File.ReadAllText(path);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write code that will open Notepad++, write to a file, and close it afterward. My code is included below. I'm totally new to C#. Is there any library or way to do this?

// Button Reference
private void button1_Click(object sender, EventArgs e)
{
    if (button1.Text.Equals("Enable Voice Control"))
    {
        button1.Text = "Stop Voice Control";
        recEngine.RecognizeAsync(RecognizeMode.Multiple);
    }
    else
    {
        button1.Text = "Enable Voice Control";
        recEngine.RecognizeAsyncStop();
    }
}

public void Form1_Load(object sender, EventArgs e)
{
    Choices commands = new Choices();
    commands.Add(myCommands);
    GrammarBuilder gBuilder = new GrammarBuilder();
    gBuilder.Append(commands);
    Grammar grammar = new Grammar(gBuilder);

    recEngine.LoadGrammarAsync(grammar);
    recEngine.SetInputToDefaultAudioDevice();
    recEngine.SpeechRecognized += recEngine_SpeechRecognized;
}

void recEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
    Process cmd = new Process();
    cmd.StartInfo.FileName = @"notepad++.exe" ;
    //cmd.StartInfo.Arguments =@"\Write.txt";
    cmd.Start();
    cmd.CloseMainWindow();
    cmd.WaitForExit();
    cmd.Refresh();

    //if (cmd.StandardError != null)
    //Console.WriteLine(cmd.StandardError.ReadToEnd());

    var result = e.Result;
    var i = 0;
    foreach (var command in myCommands)
    {
        if (command.StartsWith("close"))
        {
            this.Close();
            //cmd.StartInfo.FileName = @"notepad++";
            cmd.Kill();
        }
        if (command.StartsWith("--") || command == string.Empty) continue;  // Skip commentBlocks and skipEmptylines
        var parts = command.Split(new char[] { '|' }); // Split the lines
        i++;
        if (command.Equals(result.Text))
        {
            Console.WriteLine("Command is  {0}: {1}", i, command);
            break;
        }
    }
}

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}

Body:
You need not open notepad and write to file. You can do it programmarically.

// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);

// Open the file to read from.
string readText = File.ReadAllText(path);


问:
rest controller not working in spring boot
I have checked most similar questions, and don't find the answer.So I can only post a new question.

I can successfully run my application without errors, but the rest api I write can't be access correctly.I have compared my launch log to the official tutorials, then I have found out I don't have the similar  log below:

```<code>2017-11-13 17:37:50.921  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2328c243: startup date [Mon Nov 13 17:37:49 CST 2017]; root of context hierarchy
2017-11-13 17:37:51.061  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public hello.Greeting hello.GreetingController.greeting(java.lang.String)
2017-11-13 17:37:51.066  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-13 17:37:51.067  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-11-13 17:37:51.126  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.127  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.188  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
</code>```

Here are some my java files, Hope anyone can find some keypoint to solve my problem

the main application file:

```<code>package com.teachermate;

import com.alibaba.druid.pool.DruidDataSource;
import com.teachermate.entites.TeacherMateSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@SpringBootApplication
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {

    @Autowired
    private Environment env;

    public static void main(String[] args) {
        SpringApplication.run(JobScheduleApplication.class, args);
    }

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        dataSource.setInitialSize(2);
        dataSource.setMaxActive(20);
        dataSource.setMinIdle(0);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setPoolPreparedStatements(false);
        return dataSource;
    }
}
</code>```

the controller file:

```<code>@RestController
@RequestMapping(path = "/test")
public class TestController {
  @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}
</code>```

the pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.teachermate</groupId>
    <artifactId>job-scheduler</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jobSchedule</name>
    <description>job schedule for teachermate</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.39</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.2-jre</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.19</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

BTW, the rest api works fine before I add some code or library(like druid).But I don't know what cause it, can anyone help? Or can anyone show me a way to debug it? Thanks!

If you need any other information, just tell me in the comments.

update

I have modified the controller in official tutorials to

```<code>@RestController
@RequestMapping(path = "/test")
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }

    @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}
</code>```

it works fine!

答:
Try applying the request mapping annotation as described below.

```<code>@RestController
public class TestController {
  @RequestMapping(method = RequestMethod.GET)
  @RequestMapping(path = "/test")
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}
</code>```

Also, check this link below for more examples:
http://www.baeldung.com/spring-requestmapping

Body:
I have checked most similar questions, and don't find the answer.So I can only post a new question.

I can successfully run my application without errors, but the rest api I write can't be access correctly.I have compared my launch log to the official tutorials, then I have found out I don't have the similar  log below:

2017-11-13 17:37:50.921  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2328c243: startup date [Mon Nov 13 17:37:49 CST 2017]; root of context hierarchy
2017-11-13 17:37:51.061  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public hello.Greeting hello.GreetingController.greeting(java.lang.String)
2017-11-13 17:37:51.066  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-13 17:37:51.067  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-11-13 17:37:51.126  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.127  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.188  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

Here are some my java files, Hope anyone can find some keypoint to solve my problem

the main application file:

package com.teachermate;

import com.alibaba.druid.pool.DruidDataSource;
import com.teachermate.entites.TeacherMateSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@SpringBootApplication
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {

    @Autowired
    private Environment env;

    public static void main(String[] args) {
        SpringApplication.run(JobScheduleApplication.class, args);
    }

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        dataSource.setInitialSize(2);
        dataSource.setMaxActive(20);
        dataSource.setMinIdle(0);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setPoolPreparedStatements(false);
        return dataSource;
    }
}

the controller file:

@RestController
@RequestMapping(path = "/test")
public class TestController {
  @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}

the pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.teachermate</groupId>
    <artifactId>job-scheduler</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jobSchedule</name>
    <description>job schedule for teachermate</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.39</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.2-jre</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.19</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

BTW, the rest api works fine before I add some code or library(like druid).But I don't know what cause it, can anyone help? Or can anyone show me a way to debug it? Thanks!

If you need any other information, just tell me in the comments.

update

I have modified the controller in official tutorials to

@RestController
@RequestMapping(path = "/test")
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }

    @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}

it works fine!

Body:
Try applying the request mapping annotation as described below.

@RestController
public class TestController {
  @RequestMapping(method = RequestMethod.GET)
  @RequestMapping(path = "/test")
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}

Also, check this link below for more examples:
http://www.baeldung.com/spring-requestmapping


问:
<select> ajax calls
I am using jQuery on my site and i have a update section on my project and I have three dropdowns:

Completed?

Hours Worked

Who worked on this project?

I am trying to create an ajax call using jQuery to when I select it, call a $.ajax() and send the data to my php page to update my mysql database.

I am guessing I could do this:

Get the data in the select and store in a variable, and send it as data using $.ajax, but I am not sure how I would CAPTURE the value after you select and then run the ajax?

Any suggestions?

答:
As FryGuy said the $.post method is probably your best bet although I'd lay it out like this:

```<code>$("#project select").change(function(){ // use one selector for all 3 selects
    $.post("someurl.php",{
        // data to send
        completed: $("select#completed").val(),
        hours:     $("select#hours").val(),
        who:       $("select#who").val()
    }, function(data) {
        // do callback stuff with the server response 'data' here
    });
});
</code>```

This might not be exactly what you wanted if the three selects occur more than once on the page. I'd recommend reading through the jquery docs to get a handle on events. As for pulling out data you just need to use selectors and methods like .text(), .val(), .html(), .attr() etc... at the point you need them. The information you want is always in the DOM somewhere.

Title: <select> ajax calls

Body:
As FryGuy said the $.post method is probably your best bet although I'd lay it out like this:

$("#project select").change(function(){ // use one selector for all 3 selects
    $.post("someurl.php",{
        // data to send
        completed: $("select#completed").val(),
        hours:     $("select#hours").val(),
        who:       $("select#who").val()
    }, function(data) {
        // do callback stuff with the server response 'data' here
    });
});

This might not be exactly what you wanted if the three selects occur more than once on the page. I'd recommend reading through the jquery docs to get a handle on events. As for pulling out data you just need to use selectors and methods like .text(), .val(), .html(), .attr() etc... at the point you need them. The information you want is always in the DOM somewhere.

OwnerDisplayName: sanchothefat


问:
How to remove VS2010 "File modification detected" dialog?
Every time i switch branch in git, visual studio pisses me off with those popups asking me if I want to reload project or ignore changes.

How to automatically reload solution?

答:
I totally agree. I cannot believe they did not fix it in VS 2010.

But just an FYI:

This one is closed Microsoft Connect.

This one seems to be still active and has a workaround(which is not worth the time for me) : Microsoft Active

I guess this tells you how seriously Microsoft takes this:
Issue is still outstanding from 5 years ago: 283618


问:
Calculate the time in another country based on timezones offset
I bet there must be some plugin out there which might turn this problem into something way easier to solve, like MomentJs but the truth is; I don't know how to use it :) So I want to do it as basic as possible.

I've built an ALMOST-WORKING example of what I want to achieve here:

http://jsfiddle.net/Frondor/5a5wrssn/

The interface and controls are made, but I'm still missing the functions to: 1. Automatically detect user's timezone (like '-1', '0', '+2') and calculate the given time (see input #time) to match the french timezone (which is UTC/GMT +2).

In some kind of order:

Get user current time/timezone (hours only, not minutes or seconds)

Get the time introduced by the user to calculate Calculate

introduced time with other country's time (France in this case).

Return the value as hours like 02:00

This is my script so far, these are controls mostly, I don't know how to build the needed functions for this to work like I described above :)

```<code>$(document).ready(function () {
//Automatically detect user's timezone and store it inside this variable
    //Let's use a temporal example just to see how the whole script works
    var userTimeZone = "-3"; //here goes a function, its just an example of the variable userTimeZone already resolved for some function I don't know how to code hehe

    $("#detected").hide().fadeIn(2000); //just4fancy
    $("#uTZ").text(userTimeZone); //print the detected timezone

    var timeInput = $('#time');
    timeInput.focus();
    timeInput.on('change keyup mouseup', function () {
        var userTZ = $("#uTZ").text();

        var franceTZ = "2"; //predefined timezone of France +2

//Now I try to set the differnce of timezones in order to see how to calculate the final time
        var calculation = userTZ-franceTZ; //here is where the calculation happens. Actually, It is (of course) wrong :)

        var actualValue = $(this).val();

//print the results
        if (timeInput.val() !== '00') {
            $('#actual').text(actualValue + ':00 hours');

            $('#result').text(actualValue - calculation + ':00 hours'); //this calculates
the given time with the difference of timezones to show a converted time

            $('.panel-footer').removeClass('hidden').hide().slideDown();
        }
    }).bind('mousewheel', function (e) {
        return false;
    });
});
</code>```

If its useful for somebody, I've found this Convert timezone offset number of hours to timezone offset in (military?) hours but I didn't know how to implement the same on my script :(

Thanks in advance!

答:
```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" >
    /*finding time for india and usa in both 12hr and 24 hr format*/
function indUsaTime(){
    msg1=document.getElementById("msg1");
    msg2=document.getElementById("msg2");
    msg3=document.getElementById("msg3");
    msg4=document.getElementById("msg4");
    dayFormatIndia=document.getElementById("dayFormatIndia");
    dayFormatUs=document.getElementById("dayFormatUs");
        /*creating date object to collect hours/minutes/seconds*/
        var date=new Date();
        var hrs=date.getHours();
            /*converting into 12hr format*/
            if(hrs>12){
                hrs1=hrs%12;
                dayFormatIndia.innerHTML="PM";
            }
            else if(hrs==12){
               hrs1=hrs;
               dayFormatIndia.innerHTML="PM";
              }else{
                hrs1=hrs;
                dayFormatIndia.innerHTML="AM";
               }
    /*printing both 12hr and 24hr format for India*/
    msg1.innerHTML=hrs1+":"+date.getMinutes()+":"+date.getSeconds();
    msg2.innerHTML=hrs+":"+date.getMinutes()+":"+date.getSeconds();
        var hrsUS=hrs-10;
        var mnsUS=date.getMinutes()+30;
        mnsUS=mnsUS%60;
        /*converting hours of usa east cost using its minutes*/
            if(mnsUS>=0&&mnsUS<30){
                hrsUS=date.getHours()-9;
            }else{
                hrsUS=date.getHours()-10;
            }
        /*converting into proper 24 hr format based upon cases*/
            if(hrsUS<0){
                hrsUS=hrsUS+24;
            }
            if(hrsUS>24){
                hrsUS=hrsUS%24;
            }
            /*converting into proper 12 hr format based upon cases*/
            if(hrsUS<0){
                hrsUS=hrsUS+12;
            }else{
                hrsUS=hrsUS;
            }
            if(hrsUS>=12){
                hrsUS1=hrsUS%12;
                dayFormatUs.innerHTML="PM";
            }if(hrsUS==0){
                hrsUS1=hrsUS+12;
                dayFormatUs.innerHTML="AM";
            }else{
                hrsUS1=hrsUS;
                dayFormatUs.innerHTML="AM";
            }
         /*printing both 12hr format and 24hr format*/
            msg3.innerHTML=hrsUS1+":"+mnsUS+":"+date.getSeconds();
            msg4.innerHTML=hrsUS+":"+mnsUS+":"+date.getSeconds()
        }
 /*calling indUsaTime() in each second sothat it will look dynamic*/
setInterval(indUsaTime,1000);
function bodyload(){
    indUsaTime();
     /*input countries as an array and appending on bodyload*/
    countries=["select","UK(+1 GMT)","Germany(+2 GMT)","Spain(+2 GMT)","Brazil(-3 GMT)","Mexico(-5 GMT)","Japan(+9 GMT)","Canada(-4 GMT)","Aus(+10 GMT)","Qatar(+3 GMT)"];
        country=document.getElementById("country");
        for(i=0;i<countries.length;i++){
            var opt=document.createElement("option");
            opt.text=countries[i];
            opt.values=countries[i];
            country.appendChild(opt);
        }
}
 /*finding time for all the countries in our list*/
function findTime(){
    country=document.getElementById("country");
    showTime=document.getElementById("showTime");
    var date=new Date();
       switch(country.value)
       {
           case "UK(+1 GMT)":
               /*converting minute of UK*/
               ukMns=date.getMinutes()+30;
               ukMns=ukMns%60;
                   /*converting hours of UK*/
                   if(ukMns>=0&&ukMns<30){
                       ukHrs=date.getHours()-4;
                    }else{
                       ukHrs=date.getHours()-5;
                    }
                    if(ukHrs<0){
                       ukHrs=ukHrs+24;
                    }else{
                       ukHrs=ukHrs;
                    }
                /*printing 24hr format*/
                showTime.innerHTML=ukHrs+":"+ukMns+":"+date.getSeconds();
            break;
            case "Germany(+2 GMT)":
                /*converting minute of Germany*/
                germanyMns=date.getMinutes()+30;
                germanyMns=germanyMns%60;
                   /*converting hours of Germany*/
                    if(germanyMns>=0&&germanyMns<30){
                        germanyHrs=date.getHours()-3;
                    }else{
                        germanyHrs=date.getHours()-4;
                    }
                    if(germanyHrs<0){
                        germanyHrs=germanyHrs+24;
                    }else{
                        germanyHrs=germanyHrs;
                    }
                /*printing 24hr format*/
                showTime.innerHTML=germanyHrs+":"+germanyMns+":"+date.getSeconds();
            break;
            case "Spain(+2 GMT)":
                 /*converting minutes of Spain*/
                spainMns=date.getMinutes()+30;
                spainMns=spainMns%60;
                     /*converting hours of Spain*/
                    if(spainMns>=0 && spainMns<30){
                        spainHrs=date.getHours()-3;
                    }else{
                         spainHrs=date.getHours()-4;
                    }
                    if(spainHrs<0){
                        spainHrs=spainHrs+24;
                    }else{
                        spainHrs=spainHrs;
                    }
                /*printing 24hr format*/
                showTime.innerHTML=spainHrs+":"+spainMns+":"+date.getSeconds();
            break;
            case "Mexico(-5 GMT)":
                 /*converting minutes of Mexico*/
                mexicoMns=date.getMinutes()+30;
                mexicoMns=mexicoMns%60;
                     /*converting hours of Spain*/
                    if(mexicoMns>=0 && mexicoMns<30){
                        mexicohrs=date.getHours()-10;
                    }
                    else{
                        mexicohrs=date.getHours()-11;
                    }
                    if(mexicohrs<0){
                        mexicohrs=mexicohrs+24;
                    }
                    else{
                        mexicohrs=mexicohrs;
                    }
                 /*printing 24hr format*/
                showTime.innerHTML=mexicohrs+":"+mexicoMns+":"+date.getSeconds();
            break;
            case "Brazil(-3 GMT)":
                /*converting minutes Brazil*/
                brazilMns=date.getMinutes()+30;
                brazilMns=brazilMns%60;
                    /*converting hours of Mexico*/
                    if(brazilMns>=0 && brazilMns<30){
                        brazilHrs=date.getHours()-8;
                    }else{
                        brazilHrs=date.getHours()-9;
                    }
                    if(brazilHrs<0){
                        brazilHrs=brazilHrs+24;
                    }else{
                        brazilHrs=brazilHrs;
                    }
                /*printing 24hr format*/
                showTime.innerHTML=brazilHrs+":"+brazilMns+":"+date.getSeconds();
            break;
            case "Japan(+9 GMT)":
                 /*converting minutes of Japan*/
                japanMns=date.getMinutes()+30;
                japanMns=japanMns%60;
                    /*converting hours of Japan*/
                    if(japanMns>=0 && japanMns<30){
                        japanHrs=date.getHours()+4;
                    }else{
                        japanHrs=date.getHours()+3;
                    }
                    if(japanHrs<0){
                        japanHrs=japanHrs+24;
                    }
                    else{
                        japanHrs=japanHrs;
                    }
                /*printing 24hr format*/
                showTime.innerHTML=japanHrs+":"+japanMns+":"+date.getSeconds();
            break;
            case "Canada(-4 GMT)":
                /*converting minutes of Canada*/
                canadaMns=date.getMinutes()+30;
                canadaMns=canadaMns%60;
                    /*converting hours of Canada*/
                    if(canadaMns>=0 && canadaMns<30){
                        canadaHrs=date.getHours()-9;
                    }else{
                        canadaHrs=date.getHours()-10;
                    }
                    if(canadaHrs<0){
                        canadaHrs=canadaHrs+24;
                    }else{
                        canadaHrs=canadaHrs;
                    }
                /*printing 24hr format*/
                showTime.innerHTML=canadaHrs+":"+canadaMns+":"+date.getSeconds();
            break;
            case "Aus(+10 GMT)":
                /*converting minutes of Aus*/
                ausMns=date.getMinutes()+30;
                ausMns=ausMns%60;
                    /*converting hours of Canada*/
                    if(ausMns>=0 && ausMns<30){
                        ausHrs=date.getHours()+5;
                    }else{
                        ausHrs=date.getHours()+4;
                    }
                    if(ausHrs<0){
                        ausHrs=ausHrs+24;
                    }else{
                        ausHrs=ausHrs;
                    }
                 /*printing 24hr format*/
                showTime.innerHTML=ausHrs+":"+ausMns+":"+date.getSeconds();
            break;
            case "Qatar(+3 GMT)":
                 /*converting minutes of Qatar*/
                qatarMns=date.getMinutes()+30;
                qatarMns=qatarMns%60;
                     /*converting hours of Qatar*/
                    if(qatarMns>=0 && qatarMns<30){
                        qatarHrs=date.getHours()-2;
                    }else{
                        qatarHrs=date.getHours()-3;
                    }
                    if(qatarHrs<0){
                        qatarHrs=qatarHrs+24;
                    }else{
                        qatarHrs=qatarHrs;
                    }
                 /*printing 24hr format*/
                showTime.innerHTML=qatarHrs+":"+qatarMns+":"+date.getSeconds();
            break;
            default:
                /*clearing div*/
                showTime.innerHTML="";
            break;
        }
}
/*dropdownlist countries time dynamic*/
setInterval(findTime,1000);
    </script>
</head>
<body onload="bodyload()">
    <fieldset>
        <legend style="margin:auto">
            <b>India(+5:30 GMT)</b>
        </legend>
        <table  width="300px" cellspacing="2px" cellpadding="2px">
            <tr>
                <td align="center">
                    <i>12 hr format</i>
                </td>
                <td align="center" style="width:180px">
                    <span align="center" id="msg1"  class="digiClock">
                    </span>
                    <span id="dayFormatIndia" class="digiClock">
                    </span>
                </td>

            </tr>
            <tr>
                <td align="center">
                    <i>24 hr format</i>
                </td>
                <td align="center" style="width:180px">
                    <span id="msg2" class="digiClock">
                    </span>
                </td>
            </tr>

        </table>
    </fieldset>
        <fieldset>
        <legend style="margin:auto">
            <b>USA-EastCost(-4:00 GMT)</b>
        </legend>
        <table  width="300px">
            <tr>
                <td align="center">
                    <i>12 hr format</i>
                </td>
                <td align="center" style="width:180px">
                    <span align="center" id="msg3" class="digiClock" >
                    </span>&nbsp
                    <span id="dayFormatUs" class="digiClock">
                    </span>
                </td>
            </tr>
            <tr>
                <td align="center">
                    <i>24 hr format</i>
                </td>
                <td align="center">
                    <span id="msg4" class="digiClock">
                    </span>
                </td>
            </tr>

        </table>
    </fieldset>
    <fieldset>
        <legend style="margin:auto">
            <b>other countries(24 hr format)</b>
        </legend>
        <table width="300px">
            <tr>
                <td >
                    <select id="country" onclick="findTime()">
                    </select>
                </td>
                <td align="left">
                    <span id="showTime" class="digiClock"></span>
                    <span id="formatTime">

                    </span>
                </td>
            </tr>
        </table>
    </fieldset>
</body>
</html>
</code>```

Body:
I bet there must be some plugin out there which might turn this problem into something way easier to solve, like MomentJs but the truth is; I don't know how to use it :) So I want to do it as basic as possible.

I've built an ALMOST-WORKING example of what I want to achieve here:

http://jsfiddle.net/Frondor/5a5wrssn/

The interface and controls are made, but I'm still missing the functions to: 1. Automatically detect user's timezone (like '-1', '0', '+2') and calculate the given time (see input #time) to match the french timezone (which is UTC/GMT +2).

In some kind of order:

Get user current time/timezone (hours only, not minutes or seconds)

Get the time introduced by the user to calculate Calculate

introduced time with other country's time (France in this case).

Return the value as hours like 02:00

This is my script so far, these are controls mostly, I don't know how to build the needed functions for this to work like I described above :)

$(document).ready(function () {
//Automatically detect user's timezone and store it inside this variable
    //Let's use a temporal example just to see how the whole script works
    var userTimeZone = "-3"; //here goes a function, its just an example of the variable userTimeZone already resolved for some function I don't know how to code hehe

    $("#detected").hide().fadeIn(2000); //just4fancy
    $("#uTZ").text(userTimeZone); //print the detected timezone

    var timeInput = $('#time');
    timeInput.focus();
    timeInput.on('change keyup mouseup', function () {
        var userTZ = $("#uTZ").text();

        var franceTZ = "2"; //predefined timezone of France +2

//Now I try to set the differnce of timezones in order to see how to calculate the final time
        var calculation = userTZ-franceTZ; //here is where the calculation happens. Actually, It is (of course) wrong :)

        var actualValue = $(this).val();

//print the results
        if (timeInput.val() !== '00') {
            $('#actual').text(actualValue + ':00 hours');

            $('#result').text(actualValue - calculation + ':00 hours'); //this calculates
the given time with the difference of timezones to show a converted time

            $('.panel-footer').removeClass('hidden').hide().slideDown();
        }
    }).bind('mousewheel', function (e) {
        return false;
    });
});

If its useful for somebody, I've found this Convert timezone offset number of hours to timezone offset in (military?) hours but I didn't know how to implement the same on my script :(

Thanks in advance!


问:
Matplotlib specify axes value inside an interval
I have a csv with 200 data points. If I plot it, the x-axis will take default values from 0 to 200. However, 4 data points correspond to each event, so I would like to have values from 0 to 50 on the x-axis.

This is what I have now

```<code>import matplotlib.pyplot as plt

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)

ax1.plot(val, color='blue', label='t1')
ax1.plot(val2, color='red', label='t2')
ax1.plot(val3, color='green', label='t3')
ax1.plot(val5, color='magenta', label='t4')

plt.axis([0,200,0,0.8])

plt.xlabel('Values')
plt.ylabel('Events')
ax1.legend(loc='upper right')
</code>```

Any idea how I can modify this to effectively divide the numbers on the x-axis by 4 ?

答:
Well, you're not assigning any x-value to the data points. So it uses their index as default.

Make an array of the required length like x = np.linspace(0, 50, num=200) and use it for the plot as ax1.plot(x, val).

Body:
I have a csv with 200 data points. If I plot it, the x-axis will take default values from 0 to 200. However, 4 data points correspond to each event, so I would like to have values from 0 to 50 on the x-axis.

This is what I have now

import matplotlib.pyplot as plt

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)

ax1.plot(val, color='blue', label='t1')
ax1.plot(val2, color='red', label='t2')
ax1.plot(val3, color='green', label='t3')
ax1.plot(val5, color='magenta', label='t4')

plt.axis([0,200,0,0.8])

plt.xlabel('Values')
plt.ylabel('Events')
ax1.legend(loc='upper right')

Any idea how I can modify this to effectively divide the numbers on the x-axis by 4 ?


问:
Setting a variable to the request's response
I'm working in node.js using the node-rest-client or request libraries to make API calls to a service.  I want to be able to use let and scoping to capture the response however only can get the request...

In the below code when I console log newrequest it logs the request data, when I'm inside the function and logging info.check.id it logs the proper data.

var request = require('request');

```<code>var options = {
  url: 'https://api.pingdom.com/api/2.1/checks/******',
  headers: {
    "App-Key": "******************"
  }
};

  function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
      var info = JSON.parse(body);
     // console.log(info);
     console.log(info.check.id)
     // console.log(response.info);
    }
    else {
  //      console.log(body);
    }
  }

let newrequest = request(options, callback).auth('********', '********');

console.log(newrequest);
</code>```

答:
At this point:

console.log(newrequest);,

The request has no response yet because the call has actually not been made yet. Due to node's async nature, the request will only be made after the line console.log(newrequest);. You will only be able to access the response in the callback, in fact, the whole point of the callback is so that you can handle the response.

Body:
I'm working in node.js using the node-rest-client or request libraries to make API calls to a service.  I want to be able to use let and scoping to capture the response however only can get the request...

In the below code when I console log newrequest it logs the request data, when I'm inside the function and logging info.check.id it logs the proper data.

var request = require('request');

var options = {
  url: 'https://api.pingdom.com/api/2.1/checks/******',
  headers: {
    "App-Key": "******************"
  }
};

  function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
      var info = JSON.parse(body);
     // console.log(info);
     console.log(info.check.id)
     // console.log(response.info);
    }
    else {
  //      console.log(body);
    }
  }

let newrequest = request(options, callback).auth('********', '********');

console.log(newrequest);


问:
Update associative array
How to properly update a JSON associative array with PowerShell?

I have the following set up:

$json = Get-Content $file -Raw | ConvertFrom-Json
$arr = $json.MyJsonObject

foreach ($entry in $arr) {
    ??? = $entry -replace "UpdateMe", "REPLACEMENT"
}
```

<p>What to fill in instead of <code>???</code>?</p>

<p>The JSON looks like this:</p>

<pre class="lang-json prettyprint-override"><code>{
  "MyJsonObject" : {
      "A": "UpdateMe",
      "B": "UpdateMe"
  }
}
</code>```

答:
$arr is not an associative array (or hashtable in PowerShell terms), but a nested object. To change the values of that object's properties without knowing the property names you need to enumerate the properties and assign the modified value back to them:

```<code>$json.MyJsonObject.PSObject.Properties | ForEach-Object {
    $_.Value = $_.Value -replace 'UpdateMe', 'REPLACEMENT'
}
</code>```

Title: Update associative array

Body:
How to properly update a JSON associative array with PowerShell?

I have the following set up:

$json = Get-Content $file -Raw | ConvertFrom-Json
$arr = $json.MyJsonObject

foreach ($entry in $arr) {
    ??? = $entry -replace "UpdateMe", "REPLACEMENT"
}

What to fill in instead of ????

The JSON looks like this:

{
  "MyJsonObject" : {
      "A": "UpdateMe",
      "B": "UpdateMe"
  }
}

Body:
$arr is not an associative array (or hashtable in PowerShell terms), but a nested object. To change the values of that object's properties without knowing the property names you need to enumerate the properties and assign the modified value back to them:

$json.MyJsonObject.PSObject.Properties | ForEach-Object {
    $_.Value = $_.Value -replace 'UpdateMe', 'REPLACEMENT'
}


问:
Bundled file is not found
I am using Golang (Echo) for my backend and React for my frontend. When I bundle my code using webpack, the file is created; however, I am getting an error in my console when I go to localhost:3000 stating the bundle file cannot be found. This is the exact error message: GET http://localhost:3000/build/app.bundle.js net::ERR_ABORTED.

Here is my server:

```<code>func main() {
    env.SetEnvVars()

    e := echo.New()
    e.File("/", "server/static/index.html")

    e.Logger.Fatal(e.Start(os.Getenv("PORT")))
}
</code>```

Here is my webpack.config.js file:

```<code>module.exports = {
  entry: './client/main.jsx',
  output: {
    path: path.resolve(__dirname, 'server/static/build'),
    filename: 'app.bundle.js'
  },
  ...
</code>```

And the script tag in my index.html file is:

```<code><script src="./build/app.bundle.js"></script>
</code>```

The directory path regarding these files is currently:

```<code>/
  server/
    main.go
    static/
      index.html
      build/
        app.bundle.js
</code>```

Any help would be appreciated!

答:
The echo server you've set up only serves one single path, the root path ("/"), by rendering the contents of the index.html file. Because you haven't set up any other handlers for that server, any request to a path other than the root will result in 404, including those requests made from the index page via script and link tags, e.g.; .

To be able to serve a request to a path like "/static/build/app.bundle.js" for example you need to tell the server how to do that by registering a new handler.

With the echo server you can use its Static method to do that.

```<code>e.Static("/static", "static")
</code>```

Please keep in mind that the links you use in html tags, the location of the corresponding files on your machine, and the location from where you launched your app matters if you use relative paths like ./build/app.bundle.js, and because of that the two arguments to e.Static may need to be somewhat different from the example here.

Here's a bit more info.

Title: Bundled file is not found

Body:
I am using Golang (Echo) for my backend and React for my frontend. When I bundle my code using webpack, the file is created; however, I am getting an error in my console when I go to localhost:3000 stating the bundle file cannot be found. This is the exact error message: GET http://localhost:3000/build/app.bundle.js net::ERR_ABORTED.

Here is my server:

func main() {
    env.SetEnvVars()

    e := echo.New()
    e.File("/", "server/static/index.html")

    e.Logger.Fatal(e.Start(os.Getenv("PORT")))
}

Here is my webpack.config.js file:

module.exports = {
  entry: './client/main.jsx',
  output: {
    path: path.resolve(__dirname, 'server/static/build'),
    filename: 'app.bundle.js'
  },
  ...

And the script tag in my index.html file is:

The directory path regarding these files is currently:

/
  server/
    main.go
    static/
      index.html
      build/
        app.bundle.js

Any help would be appreciated!

Body:
The echo server you've set up only serves one single path, the root path ("/"), by rendering the contents of the index.html file. Because you haven't set up any other handlers for that server, any request to a path other than the root will result in 404, including those requests made from the index page via script and link tags, e.g.; <script src="./build/app.bundle.js"></script>.

To be able to serve a request to a path like "/static/build/app.bundle.js" for example you need to tell the server how to do that by registering a new handler.

With the echo server you can use its Static method to do that.

e.Static("/static", "static")

Please keep in mind that the links you use in html tags, the location of the corresponding files on your machine, and the location from where you launched your app matters if you use relative paths like ./build/app.bundle.js, and because of that the two arguments to e.Static may need to be somewhat different from the example here.

Here's a bit more info.


问:
Creating a scatterplot with one x and multiple y values
I have data of the form:

```<code>[x]  [y1] [y2]
1    0.9   1
2    2.0   2
3    3.1   3
</code>```

Where (x,y1) are actual values and y2 is a prediction for y1 based on a linear model estimated on another set of data. (x, y1, y2) are in a dataframe DT. How can I make a scatterplot using xyplot that graphs x on the x-axis and y1 and y2 on the y-axis but with different colors?

I was able to do this in ggplot using the following code, but think it looks much less nice than using the xyplot() command, and am wondering if I can use xyplot / lattice in this case.

```<code>ggplot(DT, aes(x)) + geom_point(aes(y=y1), color="red") + geom_point(aes(y=y2), color = "green")
</code>```

Thank you very much in advance!

答:
Use with(), plot() and points() functions of the base plot package in R:

```<code>with(datatable,plot(X,Y1))
with(datatable,points(X,Y2))
with(datatable,points(X,Y3))
</code>```

Body:
I have data of the form:

[x]  [y1] [y2]
1    0.9   1
2    2.0   2
3    3.1   3

Where (x,y1) are actual values and y2 is a prediction for y1 based on a linear model estimated on another set of data. (x, y1, y2) are in a dataframe DT. How can I make a scatterplot using xyplot that graphs x on the x-axis and y1 and y2 on the y-axis but with different colors?

I was able to do this in ggplot using the following code, but think it looks much less nice than using the xyplot() command, and am wondering if I can use xyplot / lattice in this case.

ggplot(DT, aes(x)) + geom_point(aes(y=y1), color="red") + geom_point(aes(y=y2), color = "green")

Thank you very much in advance!

Body:
Use with(), plot() and points() functions of the base plot package in R:

with(datatable,plot(X,Y1))
with(datatable,points(X,Y2))
with(datatable,points(X,Y3))


问:
Editing the file "config.inc.php"
I put my password into he config.inc.php file because I couldn’t access phpmyadmin in xampp server. But after editing the file, I can' save it.

Error

"You do not have the permissions necessary to save the file. Please
  check that you typed the location correctly and try again."

how can i get rid of this?

答:
```<code>$ cd /opt/lampp/htdocs/myapp

$ chown bitnami.root config/myapp.php
</code>```

Title: Editing the file "config.inc.php"


问:
Error: While creating partitions in SSAS Cube
While creating Partitions in SSAS Cubes, I am getting an error stating "Errors related to feature availability and configuration: Exceeded the maximum number of partitions in a measure group.

Because of requirement, I need to create minimum 5 partitions. Please Help me with this.

答:
This could be related to two similar problems I have found:

You use a AnalysisServer-Version that does not feature multiple partitions (Standard)

Check your SQLServer Version if it fits the required features or install the Enterprise one / Developer Core. If you use Visualstudio - BI Tools, check the BuildTab if the Server Version is correctly inserted there as well or change it.

You find more Information here

You use more than 1 writeback-Partition in a measuregroup

I could not find why there is this limit, but I guess it is not in the intention to split a measuregroup into multiple Partitions, instead use multiple measuregroups to partition them fully, as they all share same dependencies.

You need to make sure you only have one writeback partition in a measuregroup, as stated here

If those two possible solutions did not help you, you should consider posting in Microsofts SSAS Forum, as there are many experts luring around helping you further with this quite special topic here


问:
iphone app on windows or android mobile
Can iphone apps run on windows or android phones?

Is there any tool or framework available?

答:
Native iPhone apps wont run on other devices. However, if you were to create an application using a framwork such as JQueryMobile which is a library which formats web applications to look similar to an application for the device.

Jquery mobile is written to support many mobile devices so depending on your requirements and whether you need access to the phone hardware (eg camera etc) then jqmobile might be for you.

Title: iphone app on windows or android mobile