问:
bash one liner to combine text files line by line except for the first line in every file except for the first file
I am currently doing it using this script:

```<code>head -1 file001.txt > all.txt; tail -n +2 -q *.txt >> all.txt
</code>```

it is doing alright, gettting the header from first file and then concatenating the others.

Problem is:

the other lines are all in one line, rather than each being in separate line. Please help to correct this problem.

if you have any other one liner that does the job, perfect, it is welcome.

the desired answer will be:

get the header from any of the files with that extension, I don't want to give any specific file name like file001.txt, i'd prefer it to take it from any file, because anyway they have the same headers. But it is possible that my file names don't be the pattern file001.txt, that is why I say any file with that extension.

答:
Use awk:

```<code>awk 'FNR==1&&!ctr++;FNR!=1' *.txt
</code>```

Explanation:

FNR is the line number of the current input file

ctr is a variable that starts at 0 and is incremented
 every time we see the first line of a file

ctr is only zero for the first input file, so !ctr is only true
 for the first file.

Without an explicit action, the current input line is printed.

The first condition prints line 1 of each file if ctr is false.

The second condition prints a line if it is not the first line of a file.

Demonstration:

```<code>$ printf '%s\n' hdr f1 f2 > f1.txt
$ printf '%s\n' hdr g1 g2 > f2.txt
$ printf '%s\n' hdr h1 h2 > f3.txt
$ awk 'FNR==1&&!ctr++;FNR!=1' *.txt
hdr
f1
f2
g1
g2
h1
h2
</code>```

A slightly simpler command:

```<code>awk '!ctr++ || FNR!=1' *.txt
</code>```

which prints a line if either ctr is zero (which is only true for the first line of the first file) or the line is not the first line of a file.

Body:
I am currently doing it using this script:

head -1 file001.txt > all.txt; tail -n +2 -q *.txt >> all.txt

it is doing alright, gettting the header from first file and then concatenating the others.

Problem is:

the other lines are all in one line, rather than each being in separate line. Please help to correct this problem.

if you have any other one liner that does the job, perfect, it is welcome.

the desired answer will be:

get the header from any of the files with that extension, I don't want to give any specific file name like file001.txt, i'd prefer it to take it from any file, because anyway they have the same headers. But it is possible that my file names don't be the pattern file001.txt, that is why I say any file with that extension.

Body:
Use awk:

awk 'FNR==1&&!ctr++;FNR!=1' *.txt

Explanation:

FNR is the line number of the current input file

ctr is a variable that starts at 0 and is incremented
 every time we see the first line of a file

ctr is only zero for the first input file, so !ctr is only true
 for the first file.

Without an explicit action, the current input line is printed.

The first condition prints line 1 of each file if ctr is false.

The second condition prints a line if it is not the first line of a file.

Demonstration:

$ printf '%s\n' hdr f1 f2 > f1.txt
$ printf '%s\n' hdr g1 g2 > f2.txt
$ printf '%s\n' hdr h1 h2 > f3.txt
$ awk 'FNR==1&&!ctr++;FNR!=1' *.txt
hdr
f1
f2
g1
g2
h1
h2

A slightly simpler command:

awk '!ctr++ || FNR!=1' *.txt

which prints a line if either ctr is zero (which is only true for the first line of the first file) or the line is not the first line of a file.


来源: stackexchange

问:
How to select the date in the window phone 7 application?
I am new to the window phone 7 application development. I am developing an application in which I want to select the date dynamically as we do with calenderextender control in asp.net, datetimepicker control in windows mobile application. In the above cases we simply click on the control & can select the date. I want to how to perform this task in window phone 7 application ? Is there any control in window phone 7 through which we can perform the above task or is there any class through which we can achieve the above purpose. Can you please provide me any code or link through which we can solve the above issue ?</p>

答:
Date Picker was released as part of the Windows Phone Toolkit.

Some details offered in these posts.

Pining for Windows Phone 7 controls? We got ya covered! [Announcing the first release of the Silverlight for Windows Phone Toolkit!] - Delay's Blog

There are lots of ways to ask for a date [Creating custom DatePicker/TimePicker experiences is easy with the Windows Phone Toolkit] - Delay's Blog

ContentLicense: CC BY-SA 2.5


问:
Python - Regex cyrillic mixed with latin
I'm trying to extract the cyrillic letters from a mixed input but can't get it to split the way I want. No numbers or special characters involved.

```<code>input = "я я я я я w w w w w w\nф ф ф ф ф v v v v v v"
output = re.split("![а-я]\s*", input)
print(output)
</code>```

I want to get rid of the w and v letters and just print the Russian ones. With my code, input and output are the same except that they're in a list now.

答:
If you need to get all the Russian letters from your string, you need to use (?i)[А-ЯЁ] regex (do not forget about Ё as [А-Я] range does not include it) and use it with re.findall.

Tested in Python 3:

```<code>>>> import re
>>> input = "я я я я я w w w w w w\nф ф ф ф ф v v v v v v"
>>> output = re.findall(r'(?i)[А-ЯЁ]', input)
>>> print(output)
['я', 'я', 'я', 'я', 'я', 'ф', 'ф', 'ф', 'ф', 'ф']
</code>```

To also extract Ukranian letters, you need to add ЇІЄҐ to the character class:

```<code> output = re.findall(r"(?i)[А-ЯЁЇІЄҐ]", input)
</code>```

An apostrophe is also considered a Ukrainan letter, no idea if you want to include it into the pattern.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to extract the cyrillic letters from a mixed input but can't get it to split the way I want. No numbers or special characters involved.

input = "я я я я я w w w w w w\nф ф ф ф ф v v v v v v"
output = re.split("![а-я]\s*", input)
print(output)

I want to get rid of the w and v letters and just print the Russian ones. With my code, input and output are the same except that they're in a list now.

Body:
If you need to get all the Russian letters from your string, you need to use (?i)[А-ЯЁ] regex (do not forget about Ё as [А-Я] range does not include it) and use it with re.findall.

Tested in Python 3:

>>> import re
>>> input = "я я я я я w w w w w w\nф ф ф ф ф v v v v v v"
>>> output = re.findall(r'(?i)[А-ЯЁ]', input)
>>> print(output)
['я', 'я', 'я', 'я', 'я', 'ф', 'ф', 'ф', 'ф', 'ф']

To also extract Ukranian letters, you need to add ЇІЄҐ to the character class:

 output = re.findall(r"(?i)[А-ЯЁЇІЄҐ]", input)

An apostrophe is also considered a Ukrainan letter, no idea if you want to include it into the pattern.


问:
Python Selenium how to locate element
How can I click via selenium and python on such element:

```<code>      <a href="#create" class="btn toolbarBtn">
          <i class="fa fa-plus-circle"></i> Create
        </a>
</code>```

When I Copy Xpath this element from Chrome i got this:

//*[@id="page"]/div/div/div/div[1]/div[1]/a/i

But when I use it in my code:

driver.find_element_by_xpath('//*[@id="page"]/div/div/div/div[1]/div[1]/a/i').click()

I got error that:

```<code>Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="page"]/div/div/div/div[1]/div[1]/a/i').click()"}
</code>```

When I tried to use find_element_by_link_text and partial_link_text I got same error that selenium was unable to find such element.

答:
please try below code</p>

```<code>driver.find_element_by_partial_link_text("Create").click()
</code>```

Title: Python Selenium how to locate element

Body:
How can I click via selenium and python on such element:

           Create

When I Copy Xpath this element from Chrome i got this:

//*[@id="page"]/div/div/div/div[1]/div[1]/a/i

But when I use it in my code:

driver.find_element_by_xpath('//*[@id="page"]/div/div/div/div[1]/div[1]/a/i').click()

I got error that:

Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="page"]/div/div/div/div[1]/div[1]/a/i').click()"}

When I tried to use find_element_by_link_text and partial_link_text I got same error that selenium was unable to find such element.

Body:
please try below code

driver.find_element_by_partial_link_text("Create").click()


问:
how to append HTML content in angular 2 using innerHTML
I use innerHTML to render HTML Content in my component. But innerHTML remove all the attributes (eg: removes style attributes) in the HTML content and renders it. But need to render as it is, and doesn't want to extract any attribute from the HTML content. Is there any equivalent to innerHTML or do we can accomplish the desired result with innerHTML. Thanks in Advance.

my template file

```<code><div id="more-info-box" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title">Title</h4>
            </div>
            <div class="modal-body">
                <div class="clearfix">
                    <div [innerHTML]="htmlContent" class="long-desc-wrap">
                    </div>
                </div>
            </div>
         </div>
    </div>
</div><!-- End Info box -->
</code>```

my component file

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

@Component({
  selector: 'cr-template-content',
  templateUrl: './app/channel.component.html'
})
export class TemplateComponent {
  constructor() {

  }

  htmlContent = '<p>This is my <strong style="color:red">Paragraph</strong></p>'

}
</code>```

My current output is the content rendered without style attribute.
But the desired result should be with style attribute.

答:
Using ViewChild.

```<code>import {ViewChild,ElementRef,Component} from '@angular/core'
</code>```

create a local variable in the template

```<code><div #div ></div>
</code>```

query the local variable inside component class

```<code>@Component({...}) class MyComponent {
@ViewChild('div') div:ElementRef;
}
</code>```

access native element inside any function

```<code>this.div.nativeElement.innerHTML ="something";
</code>```

that's it. ☺

Body:
I use innerHTML to render HTML Content in my component. But innerHTML remove all the attributes (eg: removes style attributes) in the HTML content and renders it. But need to render as it is, and doesn't want to extract any attribute from the HTML content. Is there any equivalent to innerHTML or do we can accomplish the desired result with innerHTML. Thanks in Advance.

my template file

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

Title

my component file

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

@Component({
  selector: 'cr-template-content',
  templateUrl: './app/channel.component.html'
})
export class TemplateComponent {
  constructor() {

  }

  htmlContent = '
This is my Paragraph
'

}

My current output is the content rendered without style attribute.
But the desired result should be with style attribute.

Body:
Using ViewChild.

import {ViewChild,ElementRef,Component} from '@angular/core'

create a local variable in the template

<div #div ></div>

query the local variable inside component class

@Component({...}) class MyComponent {
@ViewChild('div') div:ElementRef;
}

access native element inside any function

this.div.nativeElement.innerHTML ="something";

that's it. ☺


问:
Stale element exception still persist in spite of 20 retries
I saw one os the posts before regarding stale element exception and used the retry code for handling it. But inspite of keeping the count at 20 , stale element exception still persists. I can see that the element2 is loaded in the webpage being tested .But its still id'd as stale element. The code works in case of element1 sometimes. but never for element2
code:</p>

```<code>for (i = 1; i < 7; i++)
        {
            sServiceID = ExcelUtils.getCellData(i,Constant.Col_ServiceID);
            System.out.println("sServiceID:"+sServiceID);

            ServiceID_Filter().clear();//function returns element
            ServiceID_Filter().sendKeys(sServiceID);
            BaseClass.driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

            Thread.sleep(3000);
            ApplyFilters_element().click();
            Thread.sleep(3000);

      boolean result = false;
                        int attempts = 0;
                        while(attempts < 20) {
                            System.out.println("inside stale check loop");
                            BaseClass.driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
                            try {
                                if(element1.isDisplayed()||element2.isDisplayed())  //either one of the elements will be loaded
                                {
                                System.out.println("not stale "+Table_widget.ExportButton().isDisplayed());
                                result = true;
                                break;
                                }
                            } catch(StaleElementReferenceException e) {
                                System.out.println("stale at attempt "+attempts);
                            }
                            attempts++;
                        }
    if(result==true)
                  {
                      if(element1.isDisplayed())
                      {
                          element3.click();
                          System.out.println(" button clicked");
                          Thread.sleep(1000);
                      }
                      else
                          if(element2.isDisplayed())
                          {  element3.click();
                             System.out.println("No records found");
                             Thread.sleep(1000);
                          }
                  }
        }
</code>```

答:
In my humble opinion the problem is here:

```<code> BaseClass.driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

            Thread.sleep(3000);
            ApplyFilters_element().click();
            Thread.sleep(3000);
</code>```

First of all you are using implicit wait plus thread sleep which is a recipe for disaster. This is what is causing your stale elements exceptions, try something like this below:

```<code>public boolean waitForElement(String elementXpath, int timeOut) {

    try{
    WebDriverWait wait = new WebDriverWait(driver, timeOut);
    boolean elementPresent=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(elementXpath)).isDisplayed());

    System.out.printf("%nElement is present [T/F]..? ")+elementPresent;
    }
    catch(TimeoutException e1){e1.printStackTrace();elementPresent=false;}

    return elementPresent;
 }
</code>```

Best of luck!

Body:
I saw one os the posts before regarding stale element exception and used the retry code for handling it. But inspite of keeping the count at 20 , stale element exception still persists. I can see that the element2 is loaded in the webpage being tested .But its still id'd as stale element. The code works in case of element1 sometimes. but never for element2
code:

for (i = 1; i < 7; i++)
        {
            sServiceID = ExcelUtils.getCellData(i,Constant.Col_ServiceID);
            System.out.println("sServiceID:"+sServiceID);

            ServiceID_Filter().clear();//function returns element
            ServiceID_Filter().sendKeys(sServiceID);
            BaseClass.driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

            Thread.sleep(3000);
            ApplyFilters_element().click();
            Thread.sleep(3000);

      boolean result = false;
                        int attempts = 0;
                        while(attempts < 20) {
                            System.out.println("inside stale check loop");
                            BaseClass.driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
                            try {
                                if(element1.isDisplayed()||element2.isDisplayed())  //either one of the elements will be loaded
                                {
                                System.out.println("not stale "+Table_widget.ExportButton().isDisplayed());
                                result = true;
                                break;
                                }
                            } catch(StaleElementReferenceException e) {
                                System.out.println("stale at attempt "+attempts);
                            }
                            attempts++;
                        }
    if(result==true)
                  {
                      if(element1.isDisplayed())
                      {
                          element3.click();
                          System.out.println(" button clicked");
                          Thread.sleep(1000);
                      }
                      else
                          if(element2.isDisplayed())
                          {  element3.click();
                             System.out.println("No records found");
                             Thread.sleep(1000);
                          }
                  }
        }

Body:
In my humble opinion the problem is here:

 BaseClass.driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

            Thread.sleep(3000);
            ApplyFilters_element().click();
            Thread.sleep(3000);

First of all you are using implicit wait plus thread sleep which is a recipe for disaster. This is what is causing your stale elements exceptions, try something like this below:

public boolean waitForElement(String elementXpath, int timeOut) {

    try{
    WebDriverWait wait = new WebDriverWait(driver, timeOut);
    boolean elementPresent=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(elementXpath)).isDisplayed());

    System.out.printf("%nElement is present [T/F]..? ")+elementPresent;
    }
    catch(TimeoutException e1){e1.printStackTrace();elementPresent=false;}

    return elementPresent;
 }

Best of luck!


问:
Seeking Opinion:Denormalising Fact and Dim tables to improve performance of SSRS Reports
We seem to have bit of a debate on a discussion point in our team.
We are working on a Data Warehouse in the Microsoft SQL Server 2012 platform. We have followed the Kimball Architecture to build this Data Warehouse.

Issue:

A reporting solution (built on SSRS), which sources data from this Warehouse, has significant performance issues when sourcing data from fact and dim tables. Some of our team members suggest that we extract data from facts and dims into a new set of tables using SSIS packages. This would mean we denormalise these tables into ‘Snapshot’ tables.  In this way the we would not need to join these tables to create data sets within the reports. Data could be read out of these tables directly.

I do have my own worries about this; inconsistencies, maintenance of different data structures, duplication of data etc to name a few.

Question:

Would you consider creating snapshot tables (by denormalising facts and dim tables) for reporting tables a right approach?

Would like to hear your thoughts on this.

Cheers
Nithin

答:
for raw cube performance my advice would be to always try to denormalize your tables and have one fact table and one table for each dimension (star schema).
If you are unsure if it will actually help you could start creating materialized views. These are kind of the best of both worlds, on the long run you should alter your etl.
In my previous job we only had flattened tables which worked quite well. Currenly we have a normalized schema but flatten it in the last step.</p>


问:
Javascript RegExp for matching different values with $ (dollar sign) as part of the string
I'm looking for a way to construct a RegExp object from a user input value that will match against some values which contains a dollar character $ (currency).

As I know this character must be escaped I have issues getting it to work correctly, especially in combination with other operators and characters.

I'm looking for to construct a RegExp that will work based on user input and hence it needs to be dynamic. Trying try to explain the scenario, something in this fashion:

User input: "$50" or "50"

```<code>"$50" // match
"$50 + $5" // match as it matches on "$50"
"$500 + $50" // match as it matches on "$50"
"$500" // should not match
"$5000" // should not match
"$5.50" // should not match
</code>```

user input: "$5000" or "5000"

```<code>"$5000" // match
"$5,000" // match as it resembles the same value
"$5000 + $500" // match
"$5.000" // should not match
"$5000.50" // should not match
</code>```

So basically it should only match the exact user input, with the exception of the dollar character ($), if there's a value that follows it but they are separated by a plus symbol (but still the same string), or if the value has a comma which is commonly used when writing larger numbers (for example 5,000).

Is this possible with a RegExp object?

答:
 var regExp = /^\$(50*)|(\+50*)/igm ;
    console.log(regExp.test("$50")); //true
    console.log(regExp.test("$50000")); //true
    console.log(regExp.test("$50+50")); //true
    console.log(regExp.test("$50+500000")); //true
    console.log(regExp.test("$50.00")); //false
    console.log(regExp.test("$50.00+50")); //false```

Body:
I'm looking for a way to construct a RegExp object from a user input value that will match against some values which contains a dollar character $ (currency).

As I know this character must be escaped I have issues getting it to work correctly, especially in combination with other operators and characters.

I'm looking for to construct a RegExp that will work based on user input and hence it needs to be dynamic. Trying try to explain the scenario, something in this fashion:

User input: "$50" or "50"

"$50" // match
"$50 + $5" // match as it matches on "$50"
"$500 + $50" // match as it matches on "$50"
"$500" // should not match
"$5000" // should not match
"$5.50" // should not match

user input: "$5000" or "5000"

"$5000" // match
"$5,000" // match as it resembles the same value
"$5000 + $500" // match
"$5.000" // should not match
"$5000.50" // should not match

So basically it should only match the exact user input, with the exception of the dollar character ($), if there's a value that follows it but they are separated by a plus symbol (but still the same string), or if the value has a comma which is commonly used when writing larger numbers (for example 5,000).

Is this possible with a RegExp object?


问:
CakePHP: Undefined variable, but it is defined
I am using CakePHP 2.4.4. In the Controller I am setting an array :

```<code>$bla = array();
$bla[] = 'phone';
$bla[] = 'id';
$this->set(compact('bla'));
</code>```

In the view when I try to debug this $bla array it debugs well. But when I  try to check if one string is in this array it gives me the Undefined variable: bla error. The whole view's code:

```<code>     array_walk_recursive($data, function(&$val, $key) {
        if (is_numeric($val) AND in_array($key, $bla)) { //this line gives me error: Undefined variable $bla, but it is actually defined
            if (ctype_digit($val)) {
                $val= (int) $val;
            } else {
                $val = (float) $val;
            }
        }
    });
</code>```

答:
Anonymous function you've created in array_walk_recursive has no access to $bla and any other outer variables. You should explicitly pass this variable to this function with use:

```<code>array_walk_recursive($data, function(&$val, $key) use ($bla) {
    if (is_numeric($val) AND in_array($key, $bla)) {
        if (ctype_digit($val)) {
            $val= (int) $val;
        } else {
            $val = (float) $val;
        }
    }
});
</code>```

Body:
I am using CakePHP 2.4.4. In the Controller I am setting an array :

$bla = array();
$bla[] = 'phone';
$bla[] = 'id';
$this->set(compact('bla'));

In the view when I try to debug this $bla array it debugs well. But when I  try to check if one string is in this array it gives me the Undefined variable: bla error. The whole view's code:

     array_walk_recursive($data, function(&$val, $key) {
        if (is_numeric($val) AND in_array($key, $bla)) { //this line gives me error: Undefined variable $bla, but it is actually defined
            if (ctype_digit($val)) {
                $val= (int) $val;
            } else {
                $val = (float) $val;
            }
        }
    });

Body:
Anonymous function you've created in array_walk_recursive has no access to $bla and any other outer variables. You should explicitly pass this variable to this function with use:

array_walk_recursive($data, function(&$val, $key) use ($bla) {
    if (is_numeric($val) AND in_array($key, $bla)) {
        if (ctype_digit($val)) {
            $val= (int) $val;
        } else {
            $val = (float) $val;
        }
    }
});


问:
Example of code which incorrectly tries to re-seat a reference
As per my understanding, C++ does not allow you to re-seat a reference.  In other words, you cannot change the object that a reference "refers" to.  It's like a constant pointer in that regard (e.g. int* const a = 3;).

In some code I looked at today, I saw the following:

```<code>CMyObject& object = ObjectA().myObject();
// ...
object = ObjectB().myObject();
</code>```

Immediately my alarm bells went off on the last line of code above.  Wasn't the code trying to re-seat a reference?  Yet the code compiled.

Then I realised that what the code was doing was simply invoking the assignment operator (i.e. operator=) to reassign ObjectA's internal object to ObjectB's internal object.  The object reference still referred to ObjectA, it's just that the contents of ObjectA now matched that of ObjectB.

My understanding is that the compiler will always generate a default assignment operator if you don't provide one, which does a shallow copy (similar to the default copy constructor).

Since a reference is typed (just like the underlying object that it refers to), doesn't that mean that we will always invoke the assignment operator when attempting to re-seat a reference, thus preventing the compiler from complaining about this?

I've been racking my brains out trying to come up with an illegal line of code which will incorrectly try to re-seat a reference, to get the compiler to complain.

Can anyone point me to an example of such code?

答:
I've been racking my brains out trying to come up with an illegal line of code which will incorrectly try to re-seat a reference, to get the compiler to complain.

```<code>const int i = 42;
const int j = 1337;

const int& r = i;
r = j;
</code>```

The uninitiated might expect the last line to re-seat r to j, but instead, the assignment to i fails.

Body:
As per my understanding, C++ does not allow you to re-seat a reference.  In other words, you cannot change the object that a reference "refers" to.  It's like a constant pointer in that regard (e.g. int* const a = 3;).

In some code I looked at today, I saw the following:

CMyObject& object = ObjectA().myObject();
// ...
object = ObjectB().myObject();

Immediately my alarm bells went off on the last line of code above.  Wasn't the code trying to re-seat a reference?  Yet the code compiled.

Then I realised that what the code was doing was simply invoking the assignment operator (i.e. operator=) to reassign ObjectA's internal object to ObjectB's internal object.  The object reference still referred to ObjectA, it's just that the contents of ObjectA now matched that of ObjectB.

My understanding is that the compiler will always generate a default assignment operator if you don't provide one, which does a shallow copy (similar to the default copy constructor).

Since a reference is typed (just like the underlying object that it refers to), doesn't that mean that we will always invoke the assignment operator when attempting to re-seat a reference, thus preventing the compiler from complaining about this?

I've been racking my brains out trying to come up with an illegal line of code which will incorrectly try to re-seat a reference, to get the compiler to complain.

Can anyone point me to an example of such code?

Body:
I've been racking my brains out trying to come up with an illegal line of code which will incorrectly try to re-seat a reference, to get the compiler to complain.

const int i = 42;
const int j = 1337;

const int& r = i;
r = j;

The uninitiated might expect the last line to re-seat r to j, but instead, the assignment to i fails.


问:
How can i take screenshot of rotated TextView with emoji?
I'm trying to make a screenshot of the rotated TextView which contain emoji icons. But on resulting bitmap i see that emoji are not rotated! Why is this happening? How can i make a screenshot with rotated emoji ?

What i expect:

And this is what i get:

I'm using this method to get screenshot of view:

```<code>layout.setDrawingCacheEnabled(true);
layout.buildDrawingCache();
Bitmap bitmap = null;
if (layout.getDrawingCache() != null)
    bitmap = layout.getDrawingCache().copy(Bitmap.Config.ARGB_8888, false);
layout.setDrawingCacheEnabled(false);
layout.destroyDrawingCache();
</code>```

Update:
as i figured, if I set textView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); then emoji will not be rotated even in the TextView (if you rotate TextView - they will not be rotated, they will be just moving around like a carousel), but still I don't really understand why is this happening, or rotation of emoji (on first picture) is only because of hardware acceleration?

答:
ok, i couldnt find a way to solve this really annoying issue, so i had to hack it a bit.
imageviews works perfectly with rotation.
so i basically do all the manipulations with image view - and setting it's image out of the emoji text i want using this method:

```<code>private Bitmap generateBitmapFromText(int size, String res) {
    TextView tv = new TextView(getContext());
    tv.setText(res);
    tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, 150f);
    tv.setTextColor(0xffffffff);
    tv.measure(size, size);
    int questionWidth = tv.getMeasuredWidth();
    int questionHeight = tv.getMeasuredHeight();
    Bitmap bitmap = Bitmap.createBitmap(questionWidth, questionHeight, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(bitmap);
    tv.layout(0, 0, questionWidth, questionHeight);
    tv.draw(c);
    return bitmap;
}
</code>```

and then i call

```<code>    Bitmap bitmap = generateBitmapFromText(stickersStartingSize, res);
    imageview.setImageBitmap(bitmap);
</code>```

Body:
I'm trying to make a screenshot of the rotated TextView which contain emoji icons. But on resulting bitmap i see that emoji are not rotated! Why is this happening? How can i make a screenshot with rotated emoji ?

What i expect:

And this is what i get:

I'm using this method to get screenshot of view:

layout.setDrawingCacheEnabled(true);
layout.buildDrawingCache();
Bitmap bitmap = null;
if (layout.getDrawingCache() != null)
    bitmap = layout.getDrawingCache().copy(Bitmap.Config.ARGB_8888, false);
layout.setDrawingCacheEnabled(false);
layout.destroyDrawingCache();

Update:
as i figured, if I set textView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); then emoji will not be rotated even in the TextView (if you rotate TextView - they will not be rotated, they will be just moving around like a carousel), but still I don't really understand why is this happening, or rotation of emoji (on first picture) is only because of hardware acceleration?

Body:
ok, i couldnt find a way to solve this really annoying issue, so i had to hack it a bit.
imageviews works perfectly with rotation.
so i basically do all the manipulations with image view - and setting it's image out of the emoji text i want using this method:

private Bitmap generateBitmapFromText(int size, String res) {
    TextView tv = new TextView(getContext());
    tv.setText(res);
    tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, 150f);
    tv.setTextColor(0xffffffff);
    tv.measure(size, size);
    int questionWidth = tv.getMeasuredWidth();
    int questionHeight = tv.getMeasuredHeight();
    Bitmap bitmap = Bitmap.createBitmap(questionWidth, questionHeight, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(bitmap);
    tv.layout(0, 0, questionWidth, questionHeight);
    tv.draw(c);
    return bitmap;
}

and then i call

    Bitmap bitmap = generateBitmapFromText(stickersStartingSize, res);
    imageview.setImageBitmap(bitmap);


问:
Access Microsoft sql database from Folder
I have MS sql database in folder on my computer and i am trying to connect to that database from asp.net(c#) application but it is throwing errors. Any help please.

My Web.config

```<code><connectionStrings>
<add
<add name="con" connectionString="Server=kuldeep;Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\jambtjh.mdf;
Initial Catalog=jambtjh;Integrated Security=True; ID=sa;Password=123;" providerName="System.Data.SqlClient" />
<connectionStrings>
</code>```

c# Code-

```<code>public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["con2"].ConnectionString);
    SqlCommand cmd,cmd1;
    SqlDataReader dr,dr1;
    con.Open();
    string str = "select * from testtable";
    cmd = new SqlCommand(str, con);
}
</code>```

答:
If you're using the *.mdf file in the App_Data folder of an ASP.NET app you can use this.

```<code>Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;Integrated Security=True;MultipleActiveResultSets=True;
</code>```

No authentication is required.

Body:
I have MS sql database in folder on my computer and i am trying to connect to that database from asp.net(c#) application but it is throwing errors. Any help please.

My Web.config

<connectionStrings>
<add
<add name="con" connectionString="Server=kuldeep;Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\jambtjh.mdf;
Initial Catalog=jambtjh;Integrated Security=True; ID=sa;Password=123;" providerName="System.Data.SqlClient" />
<connectionStrings>

c# Code-

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["con2"].ConnectionString);
    SqlCommand cmd,cmd1;
    SqlDataReader dr,dr1;
    con.Open();
    string str = "select * from testtable";
    cmd = new SqlCommand(str, con);
}

Body:
If you're using the *.mdf file in the App_Data folder of an ASP.NET app you can use this.

Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;Integrated Security=True;MultipleActiveResultSets=True;

No authentication is required.


问:
Swfit: Firebase DB / Dictionary look for highest Int
I have a Firebase database which looks like in the image

When I get these values in my code via a NSDictionary, I want to check what is the highest integer, so in this case 4.

This is how the NSdictionary looks (I can't do dictionaryName[ 1 ] like when I have an array  to get the value so...):

```<code>  {
   1 =     {
      driverName = chauffeur1;
      latitude = "37.33022769";
      longitude = "-122.03439793";
  };
  4 =     {
      driverName = kees;
  };
}
</code>```

Is there any option in Firebase or in Dictionary's which could help me to get this functional?
I've already looked up some solutions but all of them were not what I was looking for. Maybe someone knows how to?

I'll be glad to know

Edit 1:
The problem is that I get my Dictionary from firebase like this:

```<code>DBProvider.Instance.dbRef.child("driverLocations").observeSingleEvent(of: .value, with: { (snapshot) in
        if let data = snapshot.value as? NSDictionary {
            print(data)
            let keys = data.allKeys
            let sortedKeys = Array(keys).sorted(by: { $0 > $1 }) // highest will be the first
            let highestKey = sortedKeys[0]
        }
    })
</code>```

I can't typ it like:

```<code> if let data = snapshot.value as? NSDictionary[Int: Any]
</code>```

Maybe I'm just a little bit stupid doing it wrong.. Do you know how I can fix it?

Edit 2 (snapshot.value data)

```<code>Optional({
1 =     {
    driverName = chauffeur1;
    latitude = "37.33193453";
    longitude = "-122.03777128";
};
4 =     {
    driverName = kees;
};
})
</code>```

答:
Try something like this:

```<code>let yourDictionary = [Int: Any]() // or [String: Any]()
let keys = yourDictionary.keys
let sortedKeys = Array(keys).sorted(by: { $0 > $1 }) // highest will be the first
let highestKey = sortedKeys[0]
</code>```

Hope it helps

Body:
I have a Firebase database which looks like in the image

When I get these values in my code via a NSDictionary, I want to check what is the highest integer, so in this case 4.

This is how the NSdictionary looks (I can't do dictionaryName[ 1 ] like when I have an array  to get the value so...):

  {
   1 =     {
      driverName = chauffeur1;
      latitude = "37.33022769";
      longitude = "-122.03439793";
  };
  4 =     {
      driverName = kees;
  };
}

Is there any option in Firebase or in Dictionary's which could help me to get this functional?
I've already looked up some solutions but all of them were not what I was looking for. Maybe someone knows how to?

I'll be glad to know

Edit 1:
The problem is that I get my Dictionary from firebase like this:

DBProvider.Instance.dbRef.child("driverLocations").observeSingleEvent(of: .value, with: { (snapshot) in
        if let data = snapshot.value as? NSDictionary {
            print(data)
            let keys = data.allKeys
            let sortedKeys = Array(keys).sorted(by: { $0 > $1 }) // highest will be the first
            let highestKey = sortedKeys[0]
        }
    })

I can't typ it like:

 if let data = snapshot.value as? NSDictionary[Int: Any]

Maybe I'm just a little bit stupid doing it wrong.. Do you know how I can fix it?

Edit 2 (snapshot.value data)

Optional({
1 =     {
    driverName = chauffeur1;
    latitude = "37.33193453";
    longitude = "-122.03777128";
};
4 =     {
    driverName = kees;
};
})

Body:
Try something like this:

let yourDictionary = [Int: Any]() // or [String: Any]()
let keys = yourDictionary.keys
let sortedKeys = Array(keys).sorted(by: { $0 > $1 }) // highest will be the first
let highestKey = sortedKeys[0]

Hope it helps


问:
Cordova iOS: xcrun can't find "PackageApplication" after xcode update
This morning, xcode got updated to version 8.3 on my osx building device.

Since then, when I try to build my iOs app with Cordova, I get the following error at the end of the building process:

```<code> [exec]
 [exec] ** BUILD SUCCEEDED **
 [exec]
 [exec] xcrun: error: unable to find utility "PackageApplication", not a developer tool or in PATH
 [exec] Error: Error code 72 for command: xcrun with args: -sdk,iphoneos,PackageApplication,-v,[source.app]-o,[destination.ipa]
 [exec] Result 1
</code>```

I can't seem to get this fixed in my Cordova or Xcode setup. Wouldn't know where to start ;)

Did anyone experience the same issue? Do you have some advise for a solution.

Thank you!

(I'll be happy to buy a beer if you could help me out)

答:
We only solution we had is:

Copied from xcode Contents\Developer\Platforms\IPhoneOS.platform\DeviceSupport\10.3 folder

rolled back to xcode 8.2 but put 10.3 back in Contents\Developer\Platforms\IPhoneOS.platform\DeviceSupport\

Packaging start working.

Body:
This morning, xcode got updated to version 8.3 on my osx building device.

Since then, when I try to build my iOs app with Cordova, I get the following error at the end of the building process:

 [exec]
 [exec] ** BUILD SUCCEEDED **
 [exec]
 [exec] xcrun: error: unable to find utility "PackageApplication", not a developer tool or in PATH
 [exec] Error: Error code 72 for command: xcrun with args: -sdk,iphoneos,PackageApplication,-v,[source.app]-o,[destination.ipa]
 [exec] Result 1

I can't seem to get this fixed in my Cordova or Xcode setup. Wouldn't know where to start ;)

Did anyone experience the same issue? Do you have some advise for a solution.

Thank you!

(I'll be happy to buy a beer if you could help me out)


问:
Appending the contents of an iframe
I have an iFrame loaded from a url: The url points to a well formed piece of html; This loads ok.

[edit] There are no X domain issues etc.

```<code> $("#targetIframe").attr("src", url);
</code>```

How do I append say the  of the content just loaded into the iFrame ?
The line I'm using below doesn't seem to work

```<code>$("#targetIframe").find("head").append('<link rel="stylesheet" type="text/css" href="http://localhost:9090/html/flows/header.css">');
</code>```

Do I have to wait in a timer before calling the append ?

答:
Yes,  wait on a timer</p>

```<code>$("#targetIframe").attr("src", url);

 setTimeout(function(){
        $("#targetIframe").find("head").append('<link rel="stylesheet" type="text/css" href="http://localhost:9090/html/flows/header.css">');
 }, 100);
</code>```

Title: Appending the contents of an iframe

Body:
I have an iFrame loaded from a url: The url points to a well formed piece of html; This loads ok.

[edit] There are no X domain issues etc.

 $("#targetIframe").attr("src", url);

How do I append say the  of the content just loaded into the iFrame ?
The line I'm using below doesn't seem to work

$("#targetIframe").find("head").append('<link rel="stylesheet" type="text/css" href="http://localhost:9090/html/flows/header.css">');

Do I have to wait in a timer before calling the append ?

Body:
Yes,  wait on a timer

$("#targetIframe").attr("src", url);

 setTimeout(function(){
        $("#targetIframe").find("head").append('<link rel="stylesheet" type="text/css" href="http://localhost:9090/html/flows/header.css">');
 }, 100);


问:
What's the fastest barcode reader from PDF in c#
for an application i'm developing, I need a barcode reader. I currently use inlite barcode reader (http://how-to.inliteresearch.com/barcode-reading-howto/) but I would like to know if there is not a faster SDK. because this sdk scan the whole pdf page to find the codes (39 and 128 in my case) and it takes up to 4 hours for a 17238 pdf page.

I know IText7 has a barcode reader too but which one is faster? or if there is another sdk faster, I would like to know.

Thanks in advance :-)

答:
Why not simply run an objective speed-test?
Generate a large number of documents (you can test different codes, different sizes, damage, etc).

Once generated, pull the entire pdf through iText and then through whatever other software suite you have. Time it.

That way you'll get an objective measure of what works best in your usecase.


问:
Workaround instead of using websockets / ajax-long-pulling
My site checks the database for overdue reminders by making an AJAX request every 5 seconds. I've been told this is not ideal because of too many AJAX calls, one person said it's almost like DDOSing your own site if there are many people on with several tabs open etc.

The alternatives are using websockets or ajax-long-pulling. I can't use websockets because my shared hosting doesn't have that capability. Ajax-long-pulling is not ideal because of limited connections.

So a workaround I thought of would be to have a file on the server which simply stores a token. The browser reads this file via a hidden i-frame every 5 seconds, and if something relevant changes in the database the token is changed and this signals the browser to send an AJAX request to get the new reminders.

Would that be a feasible workaround to significantly reduce the load on the server since it's not making so many AJAX calls every 5 seconds since it's just reading the file instead?

答:
"one person said it's almost like ..." - was that person the system administrator of the host where your site runs?

"because my shared hosting doesn't have that capability" - if writing lots of code is cheaper than switching web providers then you really need to look at your at the way you manage your hosting.

"Ajax-long-pulling is not ideal because of limited connections" - and you think the same problem would not apply to websockets?

You seem to be trying to fix a problem you don't know exists. And you don't seem to be in a position to evaluate whether any changes you make will have the desired effect.

After discounting comet and websockets, your only option for reducing the impact on the server is to reduce the frequency of polling. But your next step should be to get establish a capability to assess what impact the facility currently has on the server and how that changes if you change the behaviour. This can be rather tricky on a shared host - at best you're going to see a lot of noise generated by other tenants, but if you really were consuming a lot of resources, I'm quite confident that a competent hosting provider would be alerting you to this.


问:
Stop listening to scroll event until data loads
I am developing a react component which is basically scroll to bottom feed.

I have an issue while loading more data and props are updating, scroll event queues up and executes after the loading is done. I have tried to disable and enable scroll while data is loading as mentioned here

```<code>this.keys = {37: 1, 38: 1, 39: 1, 40: 1};
preventDefault(e) {
  e = e || window.event;
  if (e.preventDefault)
    e.preventDefault();
  e.returnValue = false;
}

preventDefaultForScrollKeys(e) {
  if (this.keys[e.keyCode]) {
    this.preventDefault(e);
    return false;
  }
}

disableScroll() {
  if (window.addEventListener) // older FF
    window.addEventListener('DOMMouseScroll', this.preventDefault, false);
  window.onwheel = this.preventDefault; // modern standard
  window.onmousewheel = document.onmousewheel = this.preventDefault; // older browsers, IE
  window.ontouchmove = this.preventDefault; // mobile
  document.onkeydown = this.preventDefaultForScrollKeys;
}

enableScroll() {
  if (window.removeEventListener)
    window.removeEventListener('DOMMouseScroll', this.preventDefault, false);
  window.onmousewheel = document.onmousewheel = null;
  window.onwheel = null;
  window.ontouchmove = null;
  document.onkeydown = null;
}

ComponentDidRecieveProps(){
  this.enableScroll();
}

handleScroll(event){
  if((event.target.scrollTop + event.target.clientHeight) >= (event.target.scrollHeight) && event.target.scrollTop > this.lastScrollTop) {
     //when hits bottom
     this.disableScroll();
     this.getMoreData();
   }
   this.lastScrollTop = event.target.scrollTop
}

render(){
  return <div onScroll = {(e) => this.handleScroll(e)}> DATA </div>
}
</code>```

How to disable scrolling temporarily?

Event though scroll disables but once I enable the scroll back it executes the events queued up, hence scroll even with out user scrolling.

I am using onScroll event of a div, to load more data when it hits bottom.

答:
How about this. dataLoaded = true when fetch is done and set it to false before fetching a new set. I haven't tested it.

```<code>import React, { PropTypes } from 'react';

class ScrollingComponent extends React.Component {

  constructor(props) {
    super(props);
  }

  removeScrollListener() {
    // if running on client side
    document.removeEventListener('scroll', this.handleScroll, false);
  }

  addScrollListener() {
    // if running on client side
    document.addEventListener('scroll', this.handleScroll, false);
  }

  ComponentDidRecieveProps({ dataLoaded }){
    if(dataLoaded){
        this.addScrollListener();
    } else{
        this.removeScrollListener()
    }
  }

  handleScroll() {
    // your logic
  }

  render() {
    const { data, dataLoaded } = this.props;
    const loading = dataLoaded ? null : <p>Loading ...</p>;
    return (
        <div>
          <loading />
          <Table>
            <tbody >
             // loop through your data
            </tbody>
          </Table>
        </div>
    );
  }
};

const { arrayOf, bool, object } = PropTypes;

ScrollingComponent.propTypes = {
  data: arrayOf(object),
  dataLoaded: bool
};
</code>```

Body:
I am developing a react component which is basically scroll to bottom feed.

I have an issue while loading more data and props are updating, scroll event queues up and executes after the loading is done. I have tried to disable and enable scroll while data is loading as mentioned here

this.keys = {37: 1, 38: 1, 39: 1, 40: 1};
preventDefault(e) {
  e = e || window.event;
  if (e.preventDefault)
    e.preventDefault();
  e.returnValue = false;
}

preventDefaultForScrollKeys(e) {
  if (this.keys[e.keyCode]) {
    this.preventDefault(e);
    return false;
  }
}

disableScroll() {
  if (window.addEventListener) // older FF
    window.addEventListener('DOMMouseScroll', this.preventDefault, false);
  window.onwheel = this.preventDefault; // modern standard
  window.onmousewheel = document.onmousewheel = this.preventDefault; // older browsers, IE
  window.ontouchmove = this.preventDefault; // mobile
  document.onkeydown = this.preventDefaultForScrollKeys;
}

enableScroll() {
  if (window.removeEventListener)
    window.removeEventListener('DOMMouseScroll', this.preventDefault, false);
  window.onmousewheel = document.onmousewheel = null;
  window.onwheel = null;
  window.ontouchmove = null;
  document.onkeydown = null;
}

ComponentDidRecieveProps(){
  this.enableScroll();
}

handleScroll(event){
  if((event.target.scrollTop + event.target.clientHeight) >= (event.target.scrollHeight) && event.target.scrollTop > this.lastScrollTop) {
     //when hits bottom
     this.disableScroll();
     this.getMoreData();
   }
   this.lastScrollTop = event.target.scrollTop
}

render(){
  return
 this.handleScroll(e)}> DATA

}

How to disable scrolling temporarily?

Event though scroll disables but once I enable the scroll back it executes the events queued up, hence scroll even with out user scrolling.

I am using onScroll event of a div, to load more data when it hits bottom.

Body:
How about this. dataLoaded = true when fetch is done and set it to false before fetching a new set. I haven't tested it.

import React, { PropTypes } from 'react';

class ScrollingComponent extends React.Component {

  constructor(props) {
    super(props);
  }

  removeScrollListener() {
    // if running on client side
    document.removeEventListener('scroll', this.handleScroll, false);
  }

  addScrollListener() {
    // if running on client side
    document.addEventListener('scroll', this.handleScroll, false);
  }

  ComponentDidRecieveProps({ dataLoaded }){
    if(dataLoaded){
        this.addScrollListener();
    } else{
        this.removeScrollListener()
    }
  }

  handleScroll() {
    // your logic
  }

  render() {
    const { data, dataLoaded } = this.props;
    const loading = dataLoaded ? null : <p>Loading ...</p>;
    return (
        <div>
          <loading />
          <Table>
            <tbody >
             // loop through your data
            </tbody>
          </Table>
        </div>
    );
  }
};

const { arrayOf, bool, object } = PropTypes;

ScrollingComponent.propTypes = {
  data: arrayOf(object),
  dataLoaded: bool
};


问:
How to allow only one edit at time using Angular js inline editing
Hello I am using Angular js and creating one application with table inline editing using this demo jsfiddle.

Here if you see you can edit multiple row at a time but I just want to allow one row edit at a time.

How I can stop the user to edit other row if any one row is already in edit mode?

答:
Add One more property called CanEdit to your $scope.appkeys to false,And make it true when you try to click any Edit Button.rest all CanEdit property should be false.disable the button according to CanEdit property.You can do this by checkbox
When you click edit.Checkbox(CanEdit)will true.</p>


问:
Handling 403 error in generic way in aurelia (typeScript)
Is there any way of handling 403 responses  sending from server in generic way  without handling each of them separately inside catch block?`</p>
```<code>  searchCustomer(customerName: string): any {
            if (customerName != "") {
                let url = '{url}';
                let headers = new Headers();
                headers.append('accept', 'application/vnd.vetserve.customerlookup.v1.hal+json');
                return this.http.fetch(url, { method: 'GET', headers: headers })
                    .then(response => response.json())
                    .catch(error => {
                        if(error.status==403){
                           this._messageService.showMessage('No permission', MessageService.type.error, error);
                     }
                        console.log(error);
                    }
                        );
            }
        }`
</code>```

答:
Thanks @thebluefox for suggesting the interseptions, This is the best method and what i needed,  api-client.ts file got class ApiClient we can modify that like below
response(response) condition in .withInterceptor catchs the error</p>

```<code>  export class ApiClient {
      http:HttpClient = null;

      constructor(aurelia:Aurelia, auth:AuthenticationService) {
        let httpClient = new HttpClient();
        httpClient.configure(httpConfig => {
          httpConfig
            .withDefaults({
              headers: {
                'Accept': 'application/json'
              }
            })
            .withInterceptor({
                request(request) {
                    if (!auth.isAuthenticated()) {
                        aurelia.setRoot('authentication');
                    };
                request.headers.append('Authorization', 'bearer ' + auth.accessToken);

                 return request;
               }
                response(response) {
                console.log(`Received ${response.status} ${response.url}`);
                return response; // you can return a modified Response

                }
            })
          .useStandardConfiguration()
          .withBaseUrl(config.api_endpoint);
        });
        this.http = httpClient;
      }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is there any way of handling 403 responses  sending from server in generic way  without handling each of them separately inside catch block?`

  searchCustomer(customerName: string): any {
            if (customerName != "") {
                let url = '{url}';
                let headers = new Headers();
                headers.append('accept', 'application/vnd.vetserve.customerlookup.v1.hal+json');
                return this.http.fetch(url, { method: 'GET', headers: headers })
                    .then(response => response.json())
                    .catch(error => {
                        if(error.status==403){
                           this._messageService.showMessage('No permission', MessageService.type.error, error);
                     }
                        console.log(error);
                    }
                        );
            }
        }`

Body:
Thanks @thebluefox for suggesting the interseptions, This is the best method and what i needed,  api-client.ts file got class ApiClient we can modify that like below
response(response) condition in .withInterceptor catchs the error

  export class ApiClient {
      http:HttpClient = null;

      constructor(aurelia:Aurelia, auth:AuthenticationService) {
        let httpClient = new HttpClient();
        httpClient.configure(httpConfig => {
          httpConfig
            .withDefaults({
              headers: {
                'Accept': 'application/json'
              }
            })
            .withInterceptor({
                request(request) {
                    if (!auth.isAuthenticated()) {
                        aurelia.setRoot('authentication');
                    };
                request.headers.append('Authorization', 'bearer ' + auth.accessToken);

                 return request;
               }
                response(response) {
                console.log(`Received ${response.status} ${response.url}`);
                return response; // you can return a modified Response

                }
            })
          .useStandardConfiguration()
          .withBaseUrl(config.api_endpoint);
        });
        this.http = httpClient;
      }
    }


问:
How to user sum (column) over order by (column desc)
```<code>SELECT SUM(E.column1) over (order by E.SrNo)
as Total from (select row_number over (order by column3)
as SrNo from table) E;
</code>```

I have a query for question. I am getting this data from Temporary table.

I am using this query with sub query. I got perfect answer when tried on my local database. But I am not able to execute this query on live database.

Can any one help me out?

答:
SUM(E.column1) is giving the error. You are calculating this SUM based on a subquery -

```<code>from (select row_number over (order by column3) as SrNo from table) E
</code>```

So, in the newly created table from subquery, you don't have any column named "Column1". But in the aggregation, you are using it. Add this column at the subquery first and then use it at aggregation.

Body:
SELECT SUM(E.column1) over (order by E.SrNo)
as Total from (select row_number over (order by column3)
as SrNo from table) E;

I have a query for question. I am getting this data from Temporary table.

I am using this query with sub query. I got perfect answer when tried on my local database. But I am not able to execute this query on live database.

Can any one help me out?

Body:
SUM(E.column1) is giving the error. You are calculating this SUM based on a subquery -

from (select row_number over (order by column3) as SrNo from table) E

So, in the newly created table from subquery, you don't have any column named "Column1". But in the aggregation, you are using it. Add this column at the subquery first and then use it at aggregation.


问:
Need help resolving and understanding a few errors in mongodb using Pycharm
I am learning python 3.0 and using it with mongodb to try and make a blog, as being instructed by an udemy tutorial. However, even though I did exactly as shown in the video, I'm not getting the correct result. My python code is:

```<code>import pymongo

uri="mongodb://127.0.0.1:56752"

client=pymongo.MongoClient(uri)

database=client["fullstack"]

collections=database["student"]

student=collections.find({})

for i in student:

    print(i)
</code>```

I have checked the current port number, which is matching with the mongod terminal:

```<code>2017-03-30T04:57:31.250+0530 I NETWORK  [thread1] connection accepted from 127.0.0.1:56752 #1 (1 connection now open)
2017-03-30T04:57:31.251+0530 I NETWORK  [conn1] received client metadata from 127.0.0.1:56752 conn1: { application: { name: "MongoDB Shell" }, driver: { name: "MongoDB Internal Client", version: "3.4.2" }, os: { type: "Darwin", name: "Mac OS X", architecture: "x86_64", version: "16.4.0" } }
</code>```

However, on running the code, its showing a few errors as in:

```<code>/Users/suprateem/Documents/Pycharm/venv/bin/python /Users/suprateem/PycharmProjects/terminal_blog/app.py
Traceback (most recent call last):
  File "/Users/suprateem/PycharmProjects/terminal_blog/app.py", line 9, in <module>
    for i in student:
  File "/Users/suprateem/Documents/Pycharm/venv/lib/python3.6/site-packages/pymongo/cursor.py", line 1114, in next
    if len(self.__data) or self._refresh():
  File "/Users/suprateem/Documents/Pycharm/venv/lib/python3.6/site-packages/pymongo/cursor.py", line 1036, in _refresh
    self.__collation))
  File "/Users/suprateem/Documents/Pycharm/venv/lib/python3.6/site-packages/pymongo/cursor.py", line 873, in __send_message
    **kwargs)
  File "/Users/suprateem/Documents/Pycharm/venv/lib/python3.6/site-packages/pymongo/mongo_client.py", line 888, in _send_message_with_response
    server = topology.select_server(selector)
  File "/Users/suprateem/Documents/Pycharm/venv/lib/python3.6/site-packages/pymongo/topology.py", line 214, in select_server
    address))
  File "/Users/suprateem/Documents/Pycharm/venv/lib/python3.6/site-packages/pymongo/topology.py", line 189, in select_servers
    self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: 127.0.0.1:56752: [Errno 61] Connection refused

Process finished with exit code 1
</code>```

In the tutorial, the local database we had created earlier is being shown, ie the json type structures.
So far, the differences I've faced from the tutorial is:

I had to use sudo mongod to run it properly, while they used mongod

I had to use sudo killall -15 to kill the mongod processes when launching a new terminal after closing my last mongod tab

I'm using a updated version of pymongo than the one in the video

Any help would be highly appreciated.Thank you.

答: Just connect to mongodb://127.0.0.1 with no port number - MongoDB is listening on the default port, 27017. The port you see in the log, 56752, is the client temporary port you connected from, ignore it. </p>

Body:
I am learning python 3.0 and using it with mongodb to try and make a blog, as being instructed by an udemy tutorial. However, even though I did exactly as shown in the video, I'm not getting the correct result. My python code is:

import pymongo

uri="mongodb://127.0.0.1:56752"

client=pymongo.MongoClient(uri)

database=client["fullstack"]

collections=database["student"]

student=collections.find({})

for i in student:

    print(i)

I have checked the current port number, which is matching with the mongod terminal:

2017-03-30T04:57:31.250+0530 I NETWORK  [thread1] connection accepted from 127.0.0.1:56752 #1 (1 connection now open)
2017-03-30T04:57:31.251+0530 I NETWORK  [conn1] received client metadata from 127.0.0.1:56752 conn1: { application: { name: "MongoDB Shell" }, driver: { name: "MongoDB Internal Client", version: "3.4.2" }, os: { type: "Darwin", name: "Mac OS X", architecture: "x86_64", version: "16.4.0" } }

However, on running the code, its showing a few errors as in:

/Users/suprateem/Documents/Pycharm/venv/bin/python /Users/suprateem/PycharmProjects/terminal_blog/app.py
Traceback (most recent call last):
  File "/Users/suprateem/PycharmProjects/terminal_blog/app.py", line 9, in <module>
    for i in student:
  File "/Users/suprateem/Documents/Pycharm/venv/lib/python3.6/site-packages/pymongo/cursor.py", line 1114, in next
    if len(self.__data) or self._refresh():
  File "/Users/suprateem/Documents/Pycharm/venv/lib/python3.6/site-packages/pymongo/cursor.py", line 1036, in _refresh
    self.__collation))
  File "/Users/suprateem/Documents/Pycharm/venv/lib/python3.6/site-packages/pymongo/cursor.py", line 873, in __send_message
    **kwargs)
  File "/Users/suprateem/Documents/Pycharm/venv/lib/python3.6/site-packages/pymongo/mongo_client.py", line 888, in _send_message_with_response
    server = topology.select_server(selector)
  File "/Users/suprateem/Documents/Pycharm/venv/lib/python3.6/site-packages/pymongo/topology.py", line 214, in select_server
    address))
  File "/Users/suprateem/Documents/Pycharm/venv/lib/python3.6/site-packages/pymongo/topology.py", line 189, in select_servers
    self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: 127.0.0.1:56752: [Errno 61] Connection refused

Process finished with exit code 1

In the tutorial, the local database we had created earlier is being shown, ie the json type structures.
So far, the differences I've faced from the tutorial is:

I had to use sudo mongod to run it properly, while they used mongod

I had to use sudo killall -15 to kill the mongod processes when launching a new terminal after closing my last mongod tab

I'm using a updated version of pymongo than the one in the video

Any help would be highly appreciated.Thank you.


问:
Multiple Threads to process files in python
I am trying to process some files using python, however as file number is huge it's taking too much time. I am trying to create multiple threads and wants to execute this thing in parallel to cut down some time. However not sure exactly how to do it.

I have write the following code which is suppose to execute 10 files in parallel, but it seems like rather than creating 10 threads it's creating 100 threads, one for each file.

```<code>    def setup_logging():
    log_formatter = logging.Formatter('%(asctime)s [%(threadName)s] [%(levelname)s] %(message)s')
    root_logger = logging.getLogger()

    file_handler = logging.FileHandler("./logs.log")
    file_handler.setFormatter(log_formatter)
    root_logger.addHandler(file_handler)

    console_handler = logging.StreamHandler()
    console_handler.setFormatter(log_formatter)
    root_logger.addHandler(console_handler)
    root_logger.level = logging.DEBUG

def print_file_name(name):
    logging.info(name)

if __name__ == '__main__':
    setup_logging()
    logging.info("hi")

    dir_name = "/home/egnyte/demo/100"
    file_list = os.listdir(dir_name)
    threads = []
    import threading
    for i in range(0, len(file_list), 10):
        for index in range(0, 10, 1):
            t = threading.Thread(target=print_file_name, args=(file_list[i+index],))
            threads.append(t)
            t.start()

        for t in threads:
            t.join()
</code>```

Now the problem is, in logs I am able to see following lines, which makes me think it's creating more than 10 thread, actually 1 for every file. And that's not what I want.

```<code>2017-03-30 13:16:46,120 [Thread-9] [INFO] demo_69.txt
2017-03-30 13:16:46,120 [Thread-10] [INFO] demo_45.txt
2017-03-30 13:16:46,121 [Thread-11] [INFO] demo_72.txt
2017-03-30 13:16:46,121 [Thread-12] [INFO] demo_10.txt
...
...
2017-03-30 13:16:46,149 [Thread-98] [INFO] demo_29.txt
2017-03-30 13:16:46,150 [Thread-99] [INFO] demo_27.txt
2017-03-30 13:16:46,150 [Thread-100] [INFO] demo_39.txt
</code>```

I tried using multi process as well, however seems like it's not creating any thread, all the file name are being printed using main thread only.

pool = multiprocessing.Pool(processes=10)
result_list = pool.map(print_file_name, (file for file in os.listdir(dir_name)))

答:
You are creating a thread for each file:

```<code>for i in range(0, len(file_list), 10):
    for index in range(0, 10, 1):
        t = threading.Thread(target=print_file_name, args=(file_list[i+index],))
        threads.append(t)
        t.start()
</code>```

(Note: you should use for file in file_list to loop through the file list)

Would using a thread pool as in the following Answer be a better solution:

parallel file parsing, multiple CPU cores

Body:
I am trying to process some files using python, however as file number is huge it's taking too much time. I am trying to create multiple threads and wants to execute this thing in parallel to cut down some time. However not sure exactly how to do it.

I have write the following code which is suppose to execute 10 files in parallel, but it seems like rather than creating 10 threads it's creating 100 threads, one for each file.

    def setup_logging():
    log_formatter = logging.Formatter('%(asctime)s [%(threadName)s] [%(levelname)s] %(message)s')
    root_logger = logging.getLogger()

    file_handler = logging.FileHandler("./logs.log")
    file_handler.setFormatter(log_formatter)
    root_logger.addHandler(file_handler)

    console_handler = logging.StreamHandler()
    console_handler.setFormatter(log_formatter)
    root_logger.addHandler(console_handler)
    root_logger.level = logging.DEBUG

def print_file_name(name):
    logging.info(name)

if __name__ == '__main__':
    setup_logging()
    logging.info("hi")

    dir_name = "/home/egnyte/demo/100"
    file_list = os.listdir(dir_name)
    threads = []
    import threading
    for i in range(0, len(file_list), 10):
        for index in range(0, 10, 1):
            t = threading.Thread(target=print_file_name, args=(file_list[i+index],))
            threads.append(t)
            t.start()

        for t in threads:
            t.join()

Now the problem is, in logs I am able to see following lines, which makes me think it's creating more than 10 thread, actually 1 for every file. And that's not what I want.

2017-03-30 13:16:46,120 [Thread-9] [INFO] demo_69.txt
2017-03-30 13:16:46,120 [Thread-10] [INFO] demo_45.txt
2017-03-30 13:16:46,121 [Thread-11] [INFO] demo_72.txt
2017-03-30 13:16:46,121 [Thread-12] [INFO] demo_10.txt
...
...
2017-03-30 13:16:46,149 [Thread-98] [INFO] demo_29.txt
2017-03-30 13:16:46,150 [Thread-99] [INFO] demo_27.txt
2017-03-30 13:16:46,150 [Thread-100] [INFO] demo_39.txt

I tried using multi process as well, however seems like it's not creating any thread, all the file name are being printed using main thread only.

pool = multiprocessing.Pool(processes=10)
result_list = pool.map(print_file_name, (file for file in os.listdir(dir_name)))

Body:
You are creating a thread for each file:

for i in range(0, len(file_list), 10):
    for index in range(0, 10, 1):
        t = threading.Thread(target=print_file_name, args=(file_list[i+index],))
        threads.append(t)
        t.start()

(Note: you should use for file in file_list to loop through the file list)

Would using a thread pool as in the following Answer be a better solution:

parallel file parsing, multiple CPU cores


问:
conda install matplotlib's natgrid python toolkit on windows 64
Trying to install the natgrid matplotlib toolkit (https://github.com/matplotlib/natgrid) on Windows 64 through Anaconda.

I can only find one package which is supported on Windows and that's here https://anaconda.org/rios/natgrid

When I run conda install -c rios natgrid=0.2
it returns PackageNotFoundError: Package not found: Conda could not find '

Does anybody know what causes the error, is there another package or a workaround I can use to be able to use the natgrid toolkit within the Anaconda python distribution on Windows?

答:
you can try to update conda : conda update conda

also you can directly download file from  :

https://anaconda.org/rios/natgrid/files

you can use as alternative pip install :

python -m pip install .\natgrid-0.2.1-cp27-none-win_amd64.whl

or this alternative from this post :

conda install -c jochym natgrid=0.2


问:
How configure the HTTP Headers in Weblogic Response
Using Weblogic 11g and want to be able to add headers to all files served up by weblogic. There is no seperate web server sitting in front of weblogic. Cannot find a way to configure weblogic to add header to the HTTP response. In IIS you can easily do this by choosing the server and clicking to add headers. Looking for the equivalent way to do this in weblogic. </p>

答:
I dont think this is configurable. You would have to write a  Filter to manipulate the headers as you need.

As a hint, you could try something along the lines of this package http://flavio.tordini.org/http-headers-filter. I have not tried this myself


答:
You need something like this.

```<code>if let dictionary = snapshot.value as? [Int:[String:Any]] {
    if let max = Array(dictionary.keys).max() {
        print(dictionary[max])
    }
}
</code>```

If your dictionary have key as String with number try like this.

```<code>if let dictionary = snapshot.value as? [String:[String:Any]] {
    if let max = Array(dictionary.keys).flatMap({ Int($0) }).max() {
        print(dictionary["\(max)"])
    }
}
</code>```

Title: Swfit: Firebase DB / Dictionary look for highest Int

Body:
You need something like this.

if let dictionary = snapshot.value as? [Int:[String:Any]] {
    if let max = Array(dictionary.keys).max() {
        print(dictionary[max])
    }
}

If your dictionary have key as String with number try like this.

if let dictionary = snapshot.value as? [String:[String:Any]] {
    if let max = Array(dictionary.keys).flatMap({ Int($0) }).max() {
        print(dictionary["\(max)"])
    }
}


问:
CSS rotate div 10deg full width
I have found the following Website.
Special the Section: Social News on the half of the side.

I wonder how to get the rotated divs (i think about 10 deg) over the full width.
Is there any possibility to do that responsive? So i can use the rotated div on a mobile phone?
I`m not as fit to rotate the div. How can i do this using css?

I`ve tried this:

```<code><div class="container"></div>
</code>```

Ans using following css:

```<code>.container {
   transform: rotate(10deg);
   width: 100%;
   height: 200px;
   background: red;
}
</code>```

But the Container is not full width.

答:
HTML

```<code><div class="rotated"></div>
</code>```

CSS

```<code>.rotated {
    transform: rotate(10deg)
}
</code>```

If this is what you are talking about, it's not a rotated div. That whole slideshow part is just an image.

UPDATE:
It's is supported in IE9. Reference: http://caniuse.com/#search=transform%3A%20rotate

Title: CSS rotate div 10deg full width

Body:
I have found the following Website.
Special the Section: Social News on the half of the side.

I wonder how to get the rotated divs (i think about 10 deg) over the full width.
Is there any possibility to do that responsive? So i can use the rotated div on a mobile phone?
I`m not as fit to rotate the div. How can i do this using css?

I`ve tried this:

Ans using following css:

.container {
   transform: rotate(10deg);
   width: 100%;
   height: 200px;
   background: red;
}

But the Container is not full width.

Body:
HTML

<div class="rotated"></div>

CSS

.rotated {
    transform: rotate(10deg)
}

If this is what you are talking about, it's not a rotated div. That whole slideshow part is just an image.

UPDATE:
It's is supported in IE9. Reference: http://caniuse.com/#search=transform%3A%20rotate


问:
Why body match string in postman is passed even string iss not Exits in response?
Following I put in my test to check if ABC string exists or not.

```<code>tests["Body matches string"] = responseBody.has("ABC");
</code>```

so, test pass as ABC was in response now I wanted to test fail so I check

```<code>tests["Body matches string"] = responseBody.has("ABC");
tests["Body matches string"] = responseBody.has("XYZ");
</code>```

but still test pass, how?
and if I only check

```<code>tests["Body matches string"] = responseBody.has("XYZ");
</code>```

then it fails.Strange.
Is there any way I can check or assert?

Thanks

答:
```<code>tests["check ABC"] = responseBody.has("ABC");
tests["check XYZ"] = responseBody.has("XYZ");
</code>```

This worked!!!

Body:
Following I put in my test to check if ABC string exists or not.

tests["Body matches string"] = responseBody.has("ABC");

so, test pass as ABC was in response now I wanted to test fail so I check

tests["Body matches string"] = responseBody.has("ABC");
tests["Body matches string"] = responseBody.has("XYZ");

but still test pass, how?
and if I only check

tests["Body matches string"] = responseBody.has("XYZ");

then it fails.Strange.
Is there any way I can check or assert?

Thanks

Body:
tests["check ABC"] = responseBody.has("ABC");
tests["check XYZ"] = responseBody.has("XYZ");

This worked!!!


问:
MySQL shows incorrect autoincrement value after bulk insertion
I have run a MySQL query to insert records to a table (A) from table B in another DB using INSERT .....SELECT.

There are 18997 records inserted successfully. But then what I am seeing is the next new record takes value 32768  where as the expected one is 18997+1 = 18998.

I repeated the insertion many times after truncating the content. Everytime the autoinc value is 1 before the bulk insertion but after the insertion , teh last record has id 18997 and table shows next counter 32768.

Table is InnoDB, MySQL is 5.5

Anybody has an idea why this is happening?

答:
Check out the explanation here:

https://dev.mysql.com/doc/refman/5.5/en/innodb-auto-increment-handling.html#innodb-auto-increment-lock-modes


问:
Which tool has this database file been exported from?
I have got a text file which I know has been created by a database application which I thought was Filemaker but I can't find any export format in Filemaker which looks like this :

records end with a line containing 60 times the character "*"

each line contains field_name: value

Any idea which tool should have been used to produce this file?

答: I have been able to gather more information regarding this file, and my guess was wrong, it was not originating from filemaker but rather from a museum management software called micromusée, leaving this information there in case someone finds this thread in the future.</p>


问:
Run local python script on remote server
I'm debugging some python script that must run on my virtual machine. And, I prefer to edit the scripts locally(outside of virtual machines). So I find it's tedious to scp modified scripts to virtual machines every time. Can anyone suggests some effective way?

Particularly, I'm wondering if it's possible to execute python scripts on remote PVM. Something like that:

```<code>python --remote user@192.168.1.101 hello.py //**FAKED**, served to explain ONLY
</code>```

答:
```<code>ssh user@machine python < script.py - arg1 arg2
</code>```

Because cat | is usually not necessary

Body:
I'm debugging some python script that must run on my virtual machine. And, I prefer to edit the scripts locally(outside of virtual machines). So I find it's tedious to scp modified scripts to virtual machines every time. Can anyone suggests some effective way?

Particularly, I'm wondering if it's possible to execute python scripts on remote PVM. Something like that:

python --remote user@192.168.1.101 hello.py //**FAKED**, served to explain ONLY

Body:
ssh user@machine python < script.py - arg1 arg2

Because cat | is usually not necessary


问:
Returning an empty string in C++ using getcwd()
I've a question on how to properly return an empty string in C++, see the codeenter code here below:

```<code>string Options::getCwd()
{
    const char *buffer = getcwd(NULL, 0);
    if (buffer == NULL)
    {
        buffer = "";
    }
    string base(buffer);
    base += '/';

    return base;
}
</code>```

The problem is that if getcwd() fails the returned buffer pointer is NULL, and setting buffer to the empty string solves that. However, I would like to return the empty string in base itself. The current code returns base="/" due to the concatenation of base with the empty string in buffer. Additionally attempting to free() buffer makes the compiler complain since strings in C++ has to be declared const.

Any other ideas on how to solve this in a better way?

答:
You can simply do that:

```<code>if (buffer == NULL)
{
    return "";
}
</code>```

The empty string literal will get implicitly converted into an empty std::string which will then get returned.

However you also have other problems, e.g. that getcwd expects a valid buffer as an input and not NULL (edited: clarification at the bottom).

The following total code should should work:

```<code>string Options::getCwd()
{
    char buffer[1024]; // Or optionally PATH_MAX
    char *result = getcwd(buffer, 1024);
    if (result == NULL)
    {
        // Optionally do something with errno here
        return "";
    }

    string base(buffer);
    base += '/';
    return base;
}
</code>```

EDIT:

Ok, it seems that is indeed possibly to pass NULL to getcwd and let it allocate the buffer. In that case call free(result) after base has been constructed.  I wouldn't recommend the approach since the dynamic allocation is not needed here.

Body:
I've a question on how to properly return an empty string in C++, see the codeenter code here below:

string Options::getCwd()
{
    const char *buffer = getcwd(NULL, 0);
    if (buffer == NULL)
    {
        buffer = "";
    }
    string base(buffer);
    base += '/';

    return base;
}

The problem is that if getcwd() fails the returned buffer pointer is NULL, and setting buffer to the empty string solves that. However, I would like to return the empty string in base itself. The current code returns base="/" due to the concatenation of base with the empty string in buffer. Additionally attempting to free() buffer makes the compiler complain since strings in C++ has to be declared const.

Any other ideas on how to solve this in a better way?

Body:
You can simply do that:

if (buffer == NULL)
{
    return "";
}

The empty string literal will get implicitly converted into an empty std::string which will then get returned.

However you also have other problems, e.g. that getcwd expects a valid buffer as an input and not NULL (edited: clarification at the bottom).

The following total code should should work:

string Options::getCwd()
{
    char buffer[1024]; // Or optionally PATH_MAX
    char *result = getcwd(buffer, 1024);
    if (result == NULL)
    {
        // Optionally do something with errno here
        return "";
    }

    string base(buffer);
    base += '/';
    return base;
}

EDIT:

Ok, it seems that is indeed possibly to pass NULL to getcwd and let it allocate the buffer. In that case call free(result) after base has been constructed.  I wouldn't recommend the approach since the dynamic allocation is not needed here.


问:
how to use c++ libraries(.lib) in c# WPF project
I have a library(.lib) which as been implemented in VC++. I want to include or use this library in c# wpf project how can i achieve it.</p>

答:
You can use marshalling to access C++ code in your C# code.

Have a look at MSDN, too.

An example

```<code>[DllImport("example.dll")]
static public extern void DoSomething(int value);
</code>```

and you can use your method in your C# code like usual

```<code>DoSomething(42);
</code>```

Can be a bit confusing because you have to "map" the C++ types to C# and reverse.

Body:
You can use marshalling to access C++ code in your C# code.

Have a look at MSDN, too.

An example

[DllImport("example.dll")]
static public extern void DoSomething(int value);

and you can use your method in your C# code like usual

DoSomething(42);

Can be a bit confusing because you have to "map" the C++ types to C# and reverse.


问:
MySQL Get Different services for each IP
I have the following table:

```<code>|    **IP**   | **PORT** | **SERVICE** | **VERSION** |
|:-------:|:----:|:-------:|:-------:|
| 1.2.3.4 |  80  |   HTTP  |   1.1   |
| 1.2.3.4 |  443 |   HTTP  |   1.2   |
| 1.2.3.4 |  25  |   SMTP  |   a     |
| 2.3.4.5 |  80  |   HTTP  |   1.2   |
| 2.3.4.5 |  443 |   HTTP  |   1.2   |
| 2.3.4.5 |  25  |   SMTP  |   a     |
| 3.4.5.6 |  25  |   SMTP  |   b     |
| 3.4.5.6 |  443 |   HTTP  |   1.2   |
| 0.0.0.1 |  25  |   SMTP  |   b     |
| 0.0.0.2 |  443 |   HTTP  |   1.2   |
</code>```

And I want to get a list of the different services by port, service and version between some of the IPs, for example the result for the IPs 1.2.3.4, 2.3.4.5 and 3.4.5.6 should be similar to the following: As the rest of the services on those IPs are the same port, service and version.

Different services for IPs 1.2.3.4, 2.3.4.5 and 3.4.5.6:

```<code>|    IP   | PORT | SERVICE | VERSION |
|:-------:|:----:|:-------:|:-------:|
| 1.2.3.4 |  80  |   HTTP  |   1.1   |
| 1.2.3.4 |  25  |   SMTP  |   a     |
| 2.3.4.5 |  80  |   HTTP  |   1.2   |
| 2.3.4.5 |  25  |   SMTP  |   a     |
| 3.4.5.6 |  25  |   SMTP  |   b     |
</code>```

Not sure how to get them on a Query.

Thanks in advance

答:
Hmmm.  If I understand correctly, you care more about ports than services.  If so:

```<code>select t.*
from t
where t.ip in ('1.2.3.4', '2.3.4.5', '3.4.5.6') and
      t.port in (select t2.port from t t2 where t2.ip in ('1.2.3.4', '2.3.4.5', '3.4.5.6'));
</code>```

Body:
I have the following table:

|    **IP**   | **PORT** | **SERVICE** | **VERSION** |
|:-------:|:----:|:-------:|:-------:|
| 1.2.3.4 |  80  |   HTTP  |   1.1   |
| 1.2.3.4 |  443 |   HTTP  |   1.2   |
| 1.2.3.4 |  25  |   SMTP  |   a     |
| 2.3.4.5 |  80  |   HTTP  |   1.2   |
| 2.3.4.5 |  443 |   HTTP  |   1.2   |
| 2.3.4.5 |  25  |   SMTP  |   a     |
| 3.4.5.6 |  25  |   SMTP  |   b     |
| 3.4.5.6 |  443 |   HTTP  |   1.2   |
| 0.0.0.1 |  25  |   SMTP  |   b     |
| 0.0.0.2 |  443 |   HTTP  |   1.2   |

And I want to get a list of the different services by port, service and version between some of the IPs, for example the result for the IPs 1.2.3.4, 2.3.4.5 and 3.4.5.6 should be similar to the following: As the rest of the services on those IPs are the same port, service and version.

Different services for IPs 1.2.3.4, 2.3.4.5 and 3.4.5.6:

|    IP   | PORT | SERVICE | VERSION |
|:-------:|:----:|:-------:|:-------:|
| 1.2.3.4 |  80  |   HTTP  |   1.1   |
| 1.2.3.4 |  25  |   SMTP  |   a     |
| 2.3.4.5 |  80  |   HTTP  |   1.2   |
| 2.3.4.5 |  25  |   SMTP  |   a     |
| 3.4.5.6 |  25  |   SMTP  |   b     |

Not sure how to get them on a Query.

Thanks in advance

Body:
Hmmm.  If I understand correctly, you care more about ports than services.  If so:

select t.*
from t
where t.ip in ('1.2.3.4', '2.3.4.5', '3.4.5.6') and
      t.port in (select t2.port from t t2 where t2.ip in ('1.2.3.4', '2.3.4.5', '3.4.5.6'));


问:
toggle passed in variable boolean value in javascript function
I would like to create a re-usable function that changes the boolean value of the variable that is passed in.

My example is below however this doesn't work as the first part of the statement 'item' is not assigned to the variable passed in.

```<code>let editable = true;

     function toggleEditMode (item){
            item = !item;
        }

toggleEditMode(editable);
</code>```

Any help?

答:
You have to learn how js passes function arguments. It is passing by value here. Read this by value vs reference

Basically you can't pass by reference like you are trying to. You can make an object and then change a property on that object inside your function and it will work how you are expecting.

```<code>var i = { a:true }

function c(o){
  o.a = !o.a
}

c(i)
console.log(i);
</code>```

Body:
I would like to create a re-usable function that changes the boolean value of the variable that is passed in.

My example is below however this doesn't work as the first part of the statement 'item' is not assigned to the variable passed in.

let editable = true;

     function toggleEditMode (item){
            item = !item;
        }

toggleEditMode(editable);

Any help?

Body:
You have to learn how js passes function arguments. It is passing by value here. Read this by value vs reference

Basically you can't pass by reference like you are trying to. You can make an object and then change a property on that object inside your function and it will work how you are expecting.

var i = { a:true }

function c(o){
  o.a = !o.a
}

c(i)
console.log(i);


问:
Derby/Intellij java.sql.SQLSyntaxErrorException: Table/View 'ALCOHOL' does not exist
Tried setting up a simple embedded Derby Database via IntelliJ. When trying to access the tables from jdbc I get errors saying the tables do not exist. When I type in the terminal for the database the same query I get data unlike jdbc.

Method

```<code>Scanner input = new Scanner(System.in);
        int wob = 0;
        ResultSet rset;
        Statement stmt;

        String qry = "SELECT * FROM ALCOHOL WHERE ALCOHOL.ALCOHOL_TYPE = ";

        do{
            System.out.println("");
            System.out.println("1: For Malt Beverages");
            System.out.println("2: For Wine");
            System.out.println("");
            wob = input.nextInt();
        }while(wob != 1 && wob != 2);

        stmt = conn.createStatement();
        rset = stmt.executeQuery(qry + wob);

        System.out.println(" ID|                     Name|               BrandName |APPELLATION |      Type");
        System.out.println("---|-------------------------|-------------------------|------------|----------");

        while(rset.next()){
            String ID = String.format("%1$"+3+ "s", rset.getString("AID"));
            String name = String.format("%1$"+25+ "s", rset.getString("NAME"));
            String brandname = String.format("%1$"+25+ "s", rset.getString("BRAND_NAME"));
            String app = String.format("%1$"+22+ "s", rset.getString("APPELLATION"));
            String type = String.format("%1$"+10+ "s", rset.getString("ALCOHOL_TYPE"));
            System.out.println(ID + "|" + name + "|" + brandname + "|" + app + "|" + type);
        }
        System.out.println("---|-------------------------|-------------------------|------------|----------");

        rset.close();
        stmt.close();
        input.close();
</code>```

Trace:

```<code>java.sql.SQLSyntaxErrorException: Table/View 'ALCOHOL' does not exist.
    at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
    at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
    at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source)
    at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
    at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source)
    at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source)
    at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
    at org.apache.derby.impl.jdbc.EmbedStatement.executeQuery(Unknown Source)
    at Main.search(Main.java:89)
    at Main.main(Main.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: ERROR 42X05: Table/View 'ALCOHOL' does not exist.
    at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
    at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
    at org.apache.derby.impl.sql.compile.FromBaseTable.bindTableDescriptor(Unknown Source)
    at org.apache.derby.impl.sql.compile.FromBaseTable.bindNonVTITables(Unknown Source)
    at org.apache.derby.impl.sql.compile.FromList.bindTables(Unknown Source)
    at org.apache.derby.impl.sql.compile.SelectNode.bindNonVTITables(Unknown Source)
    at org.apache.derby.impl.sql.compile.DMLStatementNode.bindTables(Unknown Source)
    at org.apache.derby.impl.sql.compile.DMLStatementNode.bind(Unknown Source)
    at org.apache.derby.impl.sql.compile.CursorNode.bindStatement(Unknown Source)
    at org.apache.derby.impl.sql.GenericStatement.prepMinion(Unknown Source)
    at org.apache.derby.impl.sql.GenericStatement.prepare(Unknown Source)
    at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source)
    ... 9 more
</code>```

答:
Firstly table names are case-sensitive, please do a quick check on the same
Secondly, if you are using the right table name for your query, you need to change it to add the schema details as well.

This is one such example, how you could use a simple SELECT query.

```<code>SELECT * FROM {schema}."{tablename}"
</code>```

If you want to translate the above query into JAVA, you might have to use this and it should work.

```<code>String query = "SELECT * FROM {schema}.\"ALCOHOL\"";
</code>```

Hope that this helps!

Body:
Tried setting up a simple embedded Derby Database via IntelliJ. When trying to access the tables from jdbc I get errors saying the tables do not exist. When I type in the terminal for the database the same query I get data unlike jdbc.

Method

Scanner input = new Scanner(System.in);
        int wob = 0;
        ResultSet rset;
        Statement stmt;

        String qry = "SELECT * FROM ALCOHOL WHERE ALCOHOL.ALCOHOL_TYPE = ";

        do{
            System.out.println("");
            System.out.println("1: For Malt Beverages");
            System.out.println("2: For Wine");
            System.out.println("");
            wob = input.nextInt();
        }while(wob != 1 && wob != 2);

        stmt = conn.createStatement();
        rset = stmt.executeQuery(qry + wob);

        System.out.println(" ID|                     Name|               BrandName |APPELLATION |      Type");
        System.out.println("---|-------------------------|-------------------------|------------|----------");

        while(rset.next()){
            String ID = String.format("%1$"+3+ "s", rset.getString("AID"));
            String name = String.format("%1$"+25+ "s", rset.getString("NAME"));
            String brandname = String.format("%1$"+25+ "s", rset.getString("BRAND_NAME"));
            String app = String.format("%1$"+22+ "s", rset.getString("APPELLATION"));
            String type = String.format("%1$"+10+ "s", rset.getString("ALCOHOL_TYPE"));
            System.out.println(ID + "|" + name + "|" + brandname + "|" + app + "|" + type);
        }
        System.out.println("---|-------------------------|-------------------------|------------|----------");

        rset.close();
        stmt.close();
        input.close();

Trace:

java.sql.SQLSyntaxErrorException: Table/View 'ALCOHOL' does not exist.
    at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
    at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
    at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source)
    at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
    at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source)
    at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source)
    at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
    at org.apache.derby.impl.jdbc.EmbedStatement.executeQuery(Unknown Source)
    at Main.search(Main.java:89)
    at Main.main(Main.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: ERROR 42X05: Table/View 'ALCOHOL' does not exist.
    at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
    at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
    at org.apache.derby.impl.sql.compile.FromBaseTable.bindTableDescriptor(Unknown Source)
    at org.apache.derby.impl.sql.compile.FromBaseTable.bindNonVTITables(Unknown Source)
    at org.apache.derby.impl.sql.compile.FromList.bindTables(Unknown Source)
    at org.apache.derby.impl.sql.compile.SelectNode.bindNonVTITables(Unknown Source)
    at org.apache.derby.impl.sql.compile.DMLStatementNode.bindTables(Unknown Source)
    at org.apache.derby.impl.sql.compile.DMLStatementNode.bind(Unknown Source)
    at org.apache.derby.impl.sql.compile.CursorNode.bindStatement(Unknown Source)
    at org.apache.derby.impl.sql.GenericStatement.prepMinion(Unknown Source)
    at org.apache.derby.impl.sql.GenericStatement.prepare(Unknown Source)
    at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source)
    ... 9 more

Body:
Firstly table names are case-sensitive, please do a quick check on the same
Secondly, if you are using the right table name for your query, you need to change it to add the schema details as well.

This is one such example, how you could use a simple SELECT query.

SELECT * FROM {schema}."{tablename}"

If you want to translate the above query into JAVA, you might have to use this and it should work.

String query = "SELECT * FROM {schema}.\"ALCOHOL\"";

Hope that this helps!


问:
How to get access token via Google JavaScript oauth2 API
http://api.chan15.info/google-stackoverflow.html

This is the sample code I use to let user login via Google JavaScript API, and it's work, next step is use user id to login to local server via PHP, but use the user id by JavaScript is pretty danger, the real procedure I want is:

login user via JavaScript API

get access_token from JavaScript

pass the access token to PHP

use access token to Google OAuth to get user id again by PHP

login the user by user id

but I don't know how to get access token.

答:
After the user is logged in to their Google account using the Javascript Oauth2 API the access token can be found here:

gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().access_token;

I've used this to pass the token along to a separate curl PHP request as well as CORS. Since Google's JS API is still Beta I had to resort to sending a PHP curl request in the past. If you're planning to store the token for access after the user navigates away I'd also also get the token expiration date and call another function that wipes out the stored token whenever expired or explicitly revoked. But for me it was just easier to pull this right after successful login each time since I only needed to call the PHP function once and in real-time with AJAX as a bandaid.

PS: You might want to change the original category from Java to Javascript


答:
Try this:

```<code>#div {
  -ms-transform: rotate(-10deg);
  -webkit-transform: rotate(-10deg);
  transform: rotate(-10deg);
}
</code>```

Using a negative value rotates it counter-clockwise.

Source

Title: CSS rotate div 10deg full width

Body:
Try this:

#div {
  -ms-transform: rotate(-10deg);
  -webkit-transform: rotate(-10deg);
  transform: rotate(-10deg);
}

Using a negative value rotates it counter-clockwise.

Source