问:
Seeking out the optimum size for BufferedInputStream in Java
I was profiling my code that was loading a binary file. The load time was something around 15 seconds.

The majority of my load time was coming from the methods that were loading binary data.

I had the following code to create my DataInputStream:

```<code>is = new DataInputStream(
     new GZIPInputStream(
     new FileInputStream("file.bin")));
</code>```

And I changed it to this:

```<code>is = new DataInputStream(
     new BufferedInputStream(
     new GZIPInputStream(
     new FileInputStream("file.bin"))));
</code>```

So after I did this small modification the loading code went from 15 seconds to 4.

But then I found that BufferedInputStream has two constructors. The other constructor lets you explicitly define the buffer size.

I've got two questions:

What size is chosen in BufferedInputStream and is it ideal? If not, how can I find the optimum size for the buffer? Should I write a quick bit of code that does a binary search?

Is this the best way I can use BufferedInputStream? I originally had it within the GZIPInputStream but there was negligable benefit. I'm assuming what the code is doing now is every time that the file buffer needs to be filled, the GZIP input stream goes through and decodes x bytes (where x is the size of the buffer). Would it be worth just omitting the GZIPInputStream entirely? It's definitely not needed, but my file size is decreased dramatically when using it.

答:
Both the GZIPInputStream and the BufferedInputStream use an internal buffer. That is why using a BufferedInputStream inside the GZIPInputStream doesn't provide any benefit. The problem with the GZIPInputStream is that it doesn't buffer the output that it generates, thus your current version is much faster.

The default buffersize for the BufferedInputStream is 8kb, so you can try and increase or decrease that to see if it helps. I doubt that the exact number matters much, so you can simply multiply or divide by two.

If the file is small, you can also try to buffer it completely. This should give you the best performance in theory. You could also try to increase the buffer size of the GZIPInputStream (by default 512 bytes), since this might speed up reading from disk.

Body:
I was profiling my code that was loading a binary file. The load time was something around 15 seconds.

The majority of my load time was coming from the methods that were loading binary data.

I had the following code to create my DataInputStream:

is = new DataInputStream(
     new GZIPInputStream(
     new FileInputStream("file.bin")));

And I changed it to this:

is = new DataInputStream(
     new BufferedInputStream(
     new GZIPInputStream(
     new FileInputStream("file.bin"))));

So after I did this small modification the loading code went from 15 seconds to 4.

But then I found that BufferedInputStream has two constructors. The other constructor lets you explicitly define the buffer size.

I've got two questions:

What size is chosen in BufferedInputStream and is it ideal? If not, how can I find the optimum size for the buffer? Should I write a quick bit of code that does a binary search?

Is this the best way I can use BufferedInputStream? I originally had it within the GZIPInputStream but there was negligable benefit. I'm assuming what the code is doing now is every time that the file buffer needs to be filled, the GZIP input stream goes through and decodes x bytes (where x is the size of the buffer). Would it be worth just omitting the GZIPInputStream entirely? It's definitely not needed, but my file size is decreased dramatically when using it.


来源: stackexchange

问:
XML namespace missing in web api response
I have a class called Customer

```<code>[Serializable]
[DataContract]
[XmlRoot(Namespace = "http://noatariff.com")]
public class Customer
{
    public Customer()
    {
        DateTime now = DateTime.Now;
        string datePart = now.ToString("yyyy-MM-dd");
        string timePart = now.ToString("HH:mm:ss.fffzzz");
        this.TimeReceived = String.Format("{0}T{1}", datePart, timePart);
    }

    [DataMember]
    [XmlElement(Namespace = "http://noatariff.com")]
    public string TimeReceived { get; set; }
}
</code>```

Web api code

```<code>    [HttpGet]
    [Route("ping")]
    public HttpResponseMessage GetCustomerTime()
    {
        Customer cust = new Customer();
        HttpResponseMessage resp = Request.CreateResponse<Customer>(HttpStatusCode.OK, cust, new XmlMediaTypeFormatter(), "application/xml");
        return resp;
    }
</code>```

When I access my method, I get the response as follows:

```<code><Customer xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PMPI_InterconnectService.Controllers">
    <TimeReceived>2016-09-07T15:35:50.658-05:00</TimeReceived>
    <head/>
</Customer>
</code>```

I want to get the namespace information in response.

What I am missing?

```<code><mcn:Customer xmlns:mcn="http://noatariff.com">
   <mcn:TimeReceived>2016-09-07T15:46:46.845-05:00</mcn:TimeReceived>
</mcn:Customer>
</code>```

答:
just try this :

```<code>[DataContract(Namespace = "http://noatariff.com")]
public class Customer
{
    public Customer()
    {
        DateTime now = DateTime.Now;
        string datePart = now.ToString("yyyy-MM-dd");
        string timePart = now.ToString("HH:mm:ss.fffzzz");
        this.TimeReceived = String.Format("{0}T{1}", datePart, timePart);
    }

    [DataMember]
    public string TimeReceived { get; set; }
}
</code>```

if you are using DataContract as your serilizer you don't need any thing else.

ContentLicense: CC BY-SA 3.0

Body:
I have a class called Customer

[Serializable]
[DataContract]
[XmlRoot(Namespace = "http://noatariff.com")]
public class Customer
{
    public Customer()
    {
        DateTime now = DateTime.Now;
        string datePart = now.ToString("yyyy-MM-dd");
        string timePart = now.ToString("HH:mm:ss.fffzzz");
        this.TimeReceived = String.Format("{0}T{1}", datePart, timePart);
    }

    [DataMember]
    [XmlElement(Namespace = "http://noatariff.com")]
    public string TimeReceived { get; set; }
}

Web api code

    [HttpGet]
    [Route("ping")]
    public HttpResponseMessage GetCustomerTime()
    {
        Customer cust = new Customer();
        HttpResponseMessage resp = Request.CreateResponse<Customer>(HttpStatusCode.OK, cust, new XmlMediaTypeFormatter(), "application/xml");
        return resp;
    }

When I access my method, I get the response as follows:

<Customer xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PMPI_InterconnectService.Controllers">
    <TimeReceived>2016-09-07T15:35:50.658-05:00</TimeReceived>

</Customer>

I want to get the namespace information in response.

What I am missing?

<mcn:Customer xmlns:mcn="http://noatariff.com">
   <mcn:TimeReceived>2016-09-07T15:46:46.845-05:00</mcn:TimeReceived>
</mcn:Customer>

Body:
just try this :

[DataContract(Namespace = "http://noatariff.com")]
public class Customer
{
    public Customer()
    {
        DateTime now = DateTime.Now;
        string datePart = now.ToString("yyyy-MM-dd");
        string timePart = now.ToString("HH:mm:ss.fffzzz");
        this.TimeReceived = String.Format("{0}T{1}", datePart, timePart);
    }

    [DataMember]
    public string TimeReceived { get; set; }
}

if you are using DataContract as your serilizer you don't need any thing else.


问:
Maven - Missing archetype in STS (Eclipse) for Oracle Coherence
I am trying to follow this tutorial to develop an Oracle Coherence project in Maven:

https://docs.oracle.com/middleware/1212/core/MAVEN/coherence_project.htm#MAVEN8911

I have installed in my Spring Tool Suit (Eclipse) the following plugin:

Oracle Coherence Tools
Tools for developing applications for Oracle Coherence.  These features are also part of Oracle Enterprise Pack for Eclipse (OEPE)

But when I try to create a Maven project, in the list Archetypes I can't find
any with groupID = com.oracle.coherence

Anyone could tell me what am I missing?

答: due to oracle coherence is not in the public maven repository. you should first install the coherence to your local maven repository or use the oracle maven repository instead</p>


问:
Using the accessibility.js module with highcharter
I'm trying to get the accessibility module to work with highcharter, but I can't seem to figure out how to do it.

I'm trying to integrate it into a shiny app, so here's a very minimal example of where I'm at so far:

```<code>library(highcharter)
library(shiny)
x <- c("a", "b", "c", "d")
y <- c(1:4)
z <- c(4:7)

data <- data.frame(x,y,z)

ui <- fluidPage(
  fluidRow(
    highchartOutput("chart")
  )
)

server <- function(input, output, session){
  output$chart <- renderHighchart({
hchart(data, "bubble", hcaes(x = x, y = y, size = z))%>%
    hc_add_dependency(name = "modules/accessibility.js")
    })
}

shinyApp(ui = ui, server = server)
</code>```

But it still is not allowing me to tab through the bubbles.

答:
Edit:

I can't fix the tab option yet, I will check. sorry.

Previous answer

This was a error from highcharter and it was fixed in the development version. Update and test with:

```<code>source("https://install-github.me/jbkunst/highcharter")
</code>```

Now the accessibility pluging is included by default and you can configure using the hc_accessibility function with options described in the highcharts API documentation.

I tested using the NVDA.

```<code>highchart() %>%
  hc_add_series(data = 1:3, type = "column") %>%
  hc_accessibility(
    enabled = TRUE,
    keyboardNavigation = list(enabled = FALSE)
  )
</code>```

Body:
I'm trying to get the accessibility module to work with highcharter, but I can't seem to figure out how to do it.

I'm trying to integrate it into a shiny app, so here's a very minimal example of where I'm at so far:

library(highcharter)
library(shiny)
x <- c("a", "b", "c", "d")
y <- c(1:4)
z <- c(4:7)

data <- data.frame(x,y,z)

ui <- fluidPage(
  fluidRow(
    highchartOutput("chart")
  )
)

server <- function(input, output, session){
  output$chart <- renderHighchart({
hchart(data, "bubble", hcaes(x = x, y = y, size = z))%>%
    hc_add_dependency(name = "modules/accessibility.js")
    })
}

shinyApp(ui = ui, server = server)

But it still is not allowing me to tab through the bubbles.

Body:
Edit:

I can't fix the tab option yet, I will check. sorry.

Previous answer

This was a error from highcharter and it was fixed in the development version. Update and test with:

source("https://install-github.me/jbkunst/highcharter")

Now the accessibility pluging is included by default and you can configure using the hc_accessibility function with options described in the highcharts API documentation.

I tested using the NVDA.

highchart() %>%
  hc_add_series(data = 1:3, type = "column") %>%
  hc_accessibility(
    enabled = TRUE,
    keyboardNavigation = list(enabled = FALSE)
  )


问:
htaccess throws 500 Internal error
I have a directory structure with a subdirectory XYZ and index.php file. XYZ contains has few more child directories for css, images, js etc. I am trying to accomplish following:

gallery, img, css, js path should map to XYZ's subdirectories of the
same name

every single url such as http://example.com/my-page should map to http://example.com/xyz?route=my-page

Below is my .htaccess file, please help.

```<code>RewriteEngine on
RewriteRule ^((?:gallery|img|css|js).*)$ xyz/$1
RewriteRule ^(.*)$ /xyz/?route=$1 [QSA,L]
</code>```

答:
Have it this way:</p>

```<code>RewriteEngine on

RewriteRule ^(?:gallery|img|css|js)/.*$ xyz/$0 [L,NC]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ xyz/?route=$1 [QSA,L]
</code>```

Title: htaccess throws 500 Internal error

Body:
I have a directory structure with a subdirectory XYZ and index.php file. XYZ contains has few more child directories for css, images, js etc. I am trying to accomplish following:

gallery, img, css, js path should map to XYZ's subdirectories of the
same name

every single url such as http://example.com/my-page should map to http://example.com/xyz?route=my-page

Below is my .htaccess file, please help.

RewriteEngine on
RewriteRule ^((?:gallery|img|css|js).*)$ xyz/$1
RewriteRule ^(.*)$ /xyz/?route=$1 [QSA,L]

Body:
Have it this way:

RewriteEngine on

RewriteRule ^(?:gallery|img|css|js)/.*$ xyz/$0 [L,NC]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ xyz/?route=$1 [QSA,L]


问:
how to insert data from sql server to power bi graph after publish on web
i am using power bi report in my project but i need my graph be change according to SQL server data. it means when we will insert new data in SQL server it effect my graph.</p>

答:
Microsoft has already given the Documentation regarding it.

SQL Server Analysis Services live data in Power BI

In Power BI, there are two ways you can connect to a live SQL Server
  Analysis Services server. In Get data, you can connect to a SQL Server
  Analysis Services server, or you can connect to a Power BI Desktop
  file, or Excel workbook, that already connects to an Analysis
  Services server.

Important :

In order to connect to a live Analysis Services server, an On-premises Data Gateway must be installed and configured by an
  administrator. For more information, see On-premises Data
  Gateway.

When you use the gateway, your data remains on-premises.  The reports you create based on that data are saved in the Power BI
  service.

Q&A natural language querying is in preview for Analysis Services live connections.

To connect to a model from Get data

In My Workspace, select Get data. You can also change to a group workspace, if one is available.

Select Databases & More.

Select SQL Server Analysis Services > Connect.

Select a server. If you don't see any servers listed here, it means either a gateway, and data source, are not configured, or your account
  is not listed in the Users tab of the data source, in the gateway.
  Check with your adminsitrator.

Select the model you want to connect to. This could be either Tabular or Multidimensional.

After you connect to the model, it will appear in your Power BI site
  in My Workspace/Datasets. If you were swtiched to a group
  workspace, then the dataset will appear within the group.


问:
Why DOM didn't update by setAttribute when using Aframe v0.5.0?
I'm going to set the aframe-v0.5.0  position and color, and it renders correct in the browser, but when I use box.getAtrribute("position"), it returns "undefined", then I found  positon attribute is empty string showing in the DOM(same situation for scale/rotation):

```<code><a-box width="1" geometry="" height="1" depth="1" color="#0cf" material="" position="" rotation="" scale="" visible=""></a-box>
</code>```

So I switch back to aframe-v0.2.0, and everything works fine!
Can't get any answer from google, is it something changed in aframe-v0.5.0?
Here's my code below, and aframe.js is put in the , my script is put in the .

```<code>var body = document.body;
var scene = document.createElement("a-scene");
var camera = document.createElement("a-entity");
    camera.setAttribute("camera", "userHeight: 1.6");
    camera.setAttribute("look-controls", "");
    camera.setAttribute("wasd-controls", "");
var box = document.createElement("a-box");
    box.setAttribute("width", 1);
    box.setAttribute("height", 1);
    box.setAttribute("depth", 1);
    box.setAttribute("color", "#0cf");
    box.setAttribute("position", "0 0 -5");
scene.appendChild(camera);
scene.appendChild(box);
body.appendChild(scene);

console.log( box.getAttribute("position") ) //"undefined"
</code>```

example here:
http://minicg.com/demo/aframe050_test/

答:
https://aframe.io/docs/0.5.0/introduction/faq.html#why-is-the-html-not-updating-when-i-check-the-browser-inspector

If you open up your browser’s developer tools, you’ll see that the HTML attribute values are empty.

To improve performance, A-Frame does not update the HTML to save on stringification operations. Use the debug component or .flushToDOM methods if you need to sync to the DOM.

Body:
I'm going to set the aframe-v0.5.0  position and color, and it renders correct in the browser, but when I use box.getAtrribute("position"), it returns "undefined", then I found  positon attribute is empty string showing in the DOM(same situation for scale/rotation):

So I switch back to aframe-v0.2.0, and everything works fine!
Can't get any answer from google, is it something changed in aframe-v0.5.0?
Here's my code below, and aframe.js is put in the , my script is put in the .

var body = document.body;
var scene = document.createElement("a-scene");
var camera = document.createElement("a-entity");
    camera.setAttribute("camera", "userHeight: 1.6");
    camera.setAttribute("look-controls", "");
    camera.setAttribute("wasd-controls", "");
var box = document.createElement("a-box");
    box.setAttribute("width", 1);
    box.setAttribute("height", 1);
    box.setAttribute("depth", 1);
    box.setAttribute("color", "#0cf");
    box.setAttribute("position", "0 0 -5");
scene.appendChild(camera);
scene.appendChild(box);
body.appendChild(scene);

console.log( box.getAttribute("position") ) //"undefined"

example here:
http://minicg.com/demo/aframe050_test/


问:
How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)
I am writing my testcode and I do not want wo write:

```<code>List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");
</code>```

I would love to write

```<code>List<string> nameslist = new List<string>({"one", "two", "three"});
</code>```

However {"one", "two", "three"} is not an "IEnumerable string Collection". How can I initialise this in one line using the IEnumerable string Collection"?

答:
Just lose the parenthesis:</p>

```<code>var nameslist = new List<string> { "one", "two", "three" };
</code>```

Body:
I am writing my testcode and I do not want wo write:

List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two");
nameslist.Add("three");

I would love to write

List<string> nameslist = new List<string>({"one", "two", "three"});

However {"one", "two", "three"} is not an "IEnumerable string Collection". How can I initialise this in one line using the IEnumerable string Collection"?

Body:
Just lose the parenthesis:

var nameslist = new List<string> { "one", "two", "three" };


问:
Disable directory listing on apache; but access to individual files should be allowed
I do not want to use .htaccess. How should I change my Directory attributes?</p>

```<code><VirtualHost *:80>
   ServerName abc.com
   DocumentRoot /usr/share/uploads
   <Directory " /usr/share/uploads">
      Order allow,deny
      Allow from all
   </Directory>
</VirtualHost>
</code>```

答:
All done above, but the directory info is still coming up?
If you use index.php, rather than index.html, Check the following:</p>

```<code><IfModule dir_module>
    DirectoryIndex index.php
</IfModule>
</code>```

Body:
I do not want to use .htaccess. How should I change my Directory attributes?

<VirtualHost *:80>
   ServerName abc.com
   DocumentRoot /usr/share/uploads
   <Directory " /usr/share/uploads">
      Order allow,deny
      Allow from all
   </Directory>
</VirtualHost>

Body:
All done above, but the directory info is still coming up?
If you use index.php, rather than index.html, Check the following:

<IfModule dir_module>
    DirectoryIndex index.php
</IfModule>


问:
Elasticsearch 1.x add field copy of timestamp
I am working in ES 1.5.2. I have an index with documents, with stored timestamp values. I want to add a regular field to it, which will assume the value of the _timestamp field for that document. How can I do this? I could do

```<code>PUT twitter/_mapping/new_timestamp
{
  "properties": {
    "name": {
      "type": "float"
    }
  }
}
</code>```

to create a regular field, but how can I copy over all the _timestamp values to it?

答:
In ES 1.5.2, you can use the update by query plugin in order to reindex your documents and copy the _timestamp field to a regular field.

After installing the plugin with the following command:

```<code>bin/plugin -url http://oss.sonatype.org/content/repositories/releases/com/yakaz/elasticsearch/plugins/elasticsearch-action-updatebyquery/1.0.0/elasticsearch-action-updatebyquery-1.0.0.zip install elasticsearch-action-updatebyquery
</code>```

And making sure that dynamic scripting is enabled in your elasticsearch.yml configuration file, you'll be able to run the following command

```<code>POST /twitter/_update_by_query
{
  "script": {
    "inline": "ctx._source.new_timestamp = ctx._timestamp”
  },
  "query": {
    "match_all": {}
  }
}
</code>```

Body:
I am working in ES 1.5.2. I have an index with documents, with stored timestamp values. I want to add a regular field to it, which will assume the value of the _timestamp field for that document. How can I do this? I could do

PUT twitter/_mapping/new_timestamp
{
  "properties": {
    "name": {
      "type": "float"
    }
  }
}

to create a regular field, but how can I copy over all the _timestamp values to it?

Body:
In ES 1.5.2, you can use the update by query plugin in order to reindex your documents and copy the _timestamp field to a regular field.

After installing the plugin with the following command:

bin/plugin -url http://oss.sonatype.org/content/repositories/releases/com/yakaz/elasticsearch/plugins/elasticsearch-action-updatebyquery/1.0.0/elasticsearch-action-updatebyquery-1.0.0.zip install elasticsearch-action-updatebyquery

And making sure that dynamic scripting is enabled in your elasticsearch.yml configuration file, you'll be able to run the following command

POST /twitter/_update_by_query
{
  "script": {
    "inline": "ctx._source.new_timestamp = ctx._timestamp”
  },
  "query": {
    "match_all": {}
  }
}


问:
Can't remove canonical link in WordPress with Yoast SEO Plugin
So I'm trying to remove the canonical link in the header of WordPress for paginated pages but all the suggestions I tried aren't working.

Here is my code which is in my functions.php file:

```<code>function my_add_noindex_tags(){
    $paged = intval( get_query_var( 'paged' ) );

    if(is_search() || is_404() ) :
        echo '<meta name="robots" content="noindex,follow">';
    endif;

    if ($paged >= 2) :
        add_filter( 'wpseo_canonical', '__return_false', 10, 1 );

        remove_action('wp_head', 'rel_canonical');

        echo '<meta name="robots" content="noindex,follow">';
    endif;
}
add_action('wp_head','my_add_noindex_tags', 4 );
</code>```

I know the code inside if ($paged >= 2) : runs because this tag <meta name="robots" content="noindex,follow"> is in the head section.

Anyone know where I might be going wrong.

The issue here is the canonical link added by Yoast SEO aren't properly removed as expected.

Cheers

答:
After going through the Yoast SEO codes, it seems like the canonical action is added to wpseo_head action.

You either have to use priority 1 when adding your function to run in wp_head to get this to execute properly, or do it with the appropriate method below ie. using wpseo_head action.

```<code>function remove_canonical() {
    $paged = intval( get_query_var( 'paged' ) );

    if ($paged >= 2) {
        add_filter( 'wpseo_canonical', '__return_false', 10 );
    }
}
add_action( 'wpseo_head', 'remove_canonical', 4);
</code>```

Body:
So I'm trying to remove the canonical link in the header of WordPress for paginated pages but all the suggestions I tried aren't working.

Here is my code which is in my functions.php file:

function my_add_noindex_tags(){
    $paged = intval( get_query_var( 'paged' ) );

    if(is_search() || is_404() ) :
        echo '<meta name="robots" content="noindex,follow">';
    endif;

    if ($paged >= 2) :
        add_filter( 'wpseo_canonical', '__return_false', 10, 1 );

        remove_action('wp_head', 'rel_canonical');

        echo '<meta name="robots" content="noindex,follow">';
    endif;
}
add_action('wp_head','my_add_noindex_tags', 4 );

I know the code inside if ($paged >= 2) : runs because this tag <meta name="robots" content="noindex,follow"> is in the head section.

Anyone know where I might be going wrong.

The issue here is the canonical link added by Yoast SEO aren't properly removed as expected.

Cheers

Body:
After going through the Yoast SEO codes, it seems like the canonical action is added to wpseo_head action.

You either have to use priority 1 when adding your function to run in wp_head to get this to execute properly, or do it with the appropriate method below ie. using wpseo_head action.

function remove_canonical() {
    $paged = intval( get_query_var( 'paged' ) );

    if ($paged >= 2) {
        add_filter( 'wpseo_canonical', '__return_false', 10 );
    }
}
add_action( 'wpseo_head', 'remove_canonical', 4);


问:
media queries min width doesn't work
I have two media queries.

```<code>@media (min-width: 1300px) {
    .container {
        width: auto;
        max-width: 1360px;
    }
}
@media (min-width: 1565px) {
    .container {
        width: auto;
        max-width: 1576px;
    }
}
</code>```

whatever the width is. the container always as the first media query.
 I mean when the width of body is 1570px the container width still 1360px !

答:
It's important to set the viewport in the HTML .

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Title: media queries min width doesn't work

Body:
I have two media queries.

@media (min-width: 1300px) {
    .container {
        width: auto;
        max-width: 1360px;
    }
}
@media (min-width: 1565px) {
    .container {
        width: auto;
        max-width: 1576px;
    }
}

whatever the width is. the container always as the first media query.
 I mean when the width of body is 1570px the container width still 1360px !

Body:
It's important to set the viewport in the HTML <head>.

<meta name="viewport" content="width=device-width, initial-scale=1.0">


问:
R fuzzy string match to return specific column based on matched string
I have two large datasets, one around half a million records and the other one around 70K. These datasets have address. I want to match if any of the address in the smaller data set are present in the large one. As you would imagine address can be written in different ways and in different cases / spellings etc.  Apart from this address can be duplicated if written only till the building level. So different flats have the same address. I did some research and figured out the package stringdist that can be used.

I did some work and managed to get the closest match based on distance. However I am not able to return the corresponding columns for which the address match.

Below is a sample dummy data along with code that I have created to explain the situation

```<code>library(stringdist)
Address1 <- c("786, GALI NO 5, XYZ","rambo, 45, strret 4, atlast, pqr","23/4, 23RD FLOOR, STREET 2, ABC-E, PQR","45-B, GALI NO5, XYZ","HECTIC, 99 STREET, PQR","786, GALI NO 5, XYZ","rambo, 45, strret 4, atlast, pqr")
Year1 <- c(2001:2007)

Address2 <- c("abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR","abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR")
Year2 <- c(2001:2010)

df1 <- data.table(Address1,Year1)
df2 <- data.table(Address2,Year2)
df2[,unique_id := sprintf("%06d", 1:nrow(df2))]

fn_match = function(str, strVec, n){
  strVec[amatch(str, strVec, method = "dl", maxDist=n,useBytes = T)]
}

df1[!is.na(Address1)
    , address_match :=
      fn_match(Address1, df2$Address2,3)
    ]
</code>```

This returns me the closed string match based on distance of 3, however I wanted to also have columns of "Year" and "unique_id" from df2 in df1. This would help me to know with which row of data the string was matched from df2. So finally I want to know for each row in df1 what was the closet match from df2 based on the distance specified and have for the matching rows the specific "Year" and "unique_id" from df2.

I guess there is something to do with merge (left join), but I am not sure how I can merge keeping the duplicates and ensuring that I have same number of rows as in df1 (small data set).

Any kind of solution would help!!

答:
Here is a solution using the fuzzyjoin package. It uses dplyr-like syntax and stringdist as one of the possible types of fuzzy matching.

You can use stringdist method="dl" (or others that might work better).

To meet your requirement of "ensuring that I have same number of rows as in df1", I used a large max_dist and then used dplyr::group_by and dplyr::top_n to get only the best match with minimum distance. This was suggested by dgrtwo, the developer of fuzzyjoin. (Hopefully it'll be part of the package itself in the future.)

(I also had to make an assumption to take the max year2 in the event of distance ties.)

Code:

```<code>library(data.table, quietly = TRUE)
df1 <- data.table(Address1 = c("786, GALI NO 5, XYZ","rambo, 45, strret 4, atlast, pqr","23/4, 23RD FLOOR, STREET 2, ABC-E, PQR","45-B, GALI NO5, XYZ","HECTIC, 99 STREET, PQR","786, GALI NO 5, XYZ","rambo, 45, strret 4, atlast, pqr"),
                  Year1 = 2001:2007)
df2 <- data.table(Address2=c("abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR","abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR"),
                  Year2=2001:2010)
df2[,unique_id := sprintf("%06d", .I)]

library(fuzzyjoin, quietly = TRUE); library(dplyr, quietly = TRUE)
stringdist_join(df1, df2,
                by = c("Address1" = "Address2"),
                mode = "left",
                method = "dl",
                max_dist = 99,
                distance_col = "dist") %>%
  group_by(Address1, Year1) %>%
  top_n(1, -dist) %>%
  top_n(1, Year2)
</code>```

Result:

```<code># A tibble: 7 x 6
# Groups:   Address1, Year1 [7]
                                Address1 Year1                             Address2 Year2 unique_id  dist
                                   <chr> <int>                                <chr> <int>     <chr> <dbl>
1                    786, GALI NO 5, XYZ  2001                   786, GALI NO 4 XYZ  2007    000007     2
2       rambo, 45, strret 4, atlast, pqr  2002 del, 546, strret2, towards east, pqr  2009    000009    17
3 23/4, 23RD FLOOR, STREET 2, ABC-E, PQR  2003                  23/4, STREET 2, PQR  2010    000010    19
4                    45-B, GALI NO5, XYZ  2004                  45B, GALI NO 5, XYZ  2008    000008     2
5                 HECTIC, 99 STREET, PQR  2005                  23/4, STREET 2, PQR  2010    000010    11
6                    786, GALI NO 5, XYZ  2006                   786, GALI NO 4 XYZ  2007    000007     2
7       rambo, 45, strret 4, atlast, pqr  2007 del, 546, strret2, towards east, pqr  2009    000009    17
</code>```

Body:
I have two large datasets, one around half a million records and the other one around 70K. These datasets have address. I want to match if any of the address in the smaller data set are present in the large one. As you would imagine address can be written in different ways and in different cases / spellings etc.  Apart from this address can be duplicated if written only till the building level. So different flats have the same address. I did some research and figured out the package stringdist that can be used.

I did some work and managed to get the closest match based on distance. However I am not able to return the corresponding columns for which the address match.

Below is a sample dummy data along with code that I have created to explain the situation

library(stringdist)
Address1 <- c("786, GALI NO 5, XYZ","rambo, 45, strret 4, atlast, pqr","23/4, 23RD FLOOR, STREET 2, ABC-E, PQR","45-B, GALI NO5, XYZ","HECTIC, 99 STREET, PQR","786, GALI NO 5, XYZ","rambo, 45, strret 4, atlast, pqr")
Year1 <- c(2001:2007)

Address2 <- c("abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR","abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR")
Year2 <- c(2001:2010)

df1 <- data.table(Address1,Year1)
df2 <- data.table(Address2,Year2)
df2[,unique_id := sprintf("%06d", 1:nrow(df2))]

fn_match = function(str, strVec, n){
  strVec[amatch(str, strVec, method = "dl", maxDist=n,useBytes = T)]
}

df1[!is.na(Address1)
    , address_match :=
      fn_match(Address1, df2$Address2,3)
    ]

This returns me the closed string match based on distance of 3, however I wanted to also have columns of "Year" and "unique_id" from df2 in df1. This would help me to know with which row of data the string was matched from df2. So finally I want to know for each row in df1 what was the closet match from df2 based on the distance specified and have for the matching rows the specific "Year" and "unique_id" from df2.

I guess there is something to do with merge (left join), but I am not sure how I can merge keeping the duplicates and ensuring that I have same number of rows as in df1 (small data set).

Any kind of solution would help!!

Body:
Here is a solution using the fuzzyjoin package. It uses dplyr-like syntax and stringdist as one of the possible types of fuzzy matching.

You can use stringdist method="dl" (or others that might work better).

To meet your requirement of "ensuring that I have same number of rows as in df1", I used a large max_dist and then used dplyr::group_by and dplyr::top_n to get only the best match with minimum distance. This was suggested by dgrtwo, the developer of fuzzyjoin. (Hopefully it'll be part of the package itself in the future.)

(I also had to make an assumption to take the max year2 in the event of distance ties.)

Code:

library(data.table, quietly = TRUE)
df1 <- data.table(Address1 = c("786, GALI NO 5, XYZ","rambo, 45, strret 4, atlast, pqr","23/4, 23RD FLOOR, STREET 2, ABC-E, PQR","45-B, GALI NO5, XYZ","HECTIC, 99 STREET, PQR","786, GALI NO 5, XYZ","rambo, 45, strret 4, atlast, pqr"),
                  Year1 = 2001:2007)
df2 <- data.table(Address2=c("abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR","abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR"),
                  Year2=2001:2010)
df2[,unique_id := sprintf("%06d", .I)]

library(fuzzyjoin, quietly = TRUE); library(dplyr, quietly = TRUE)
stringdist_join(df1, df2,
                by = c("Address1" = "Address2"),
                mode = "left",
                method = "dl",
                max_dist = 99,
                distance_col = "dist") %>%
  group_by(Address1, Year1) %>%
  top_n(1, -dist) %>%
  top_n(1, Year2)

Result:

# A tibble: 7 x 6
# Groups:   Address1, Year1 [7]
                                Address1 Year1                             Address2 Year2 unique_id  dist
                                   <chr> <int>                                <chr> <int>     <chr> <dbl>
1                    786, GALI NO 5, XYZ  2001                   786, GALI NO 4 XYZ  2007    000007     2
2       rambo, 45, strret 4, atlast, pqr  2002 del, 546, strret2, towards east, pqr  2009    000009    17
3 23/4, 23RD FLOOR, STREET 2, ABC-E, PQR  2003                  23/4, STREET 2, PQR  2010    000010    19
4                    45-B, GALI NO5, XYZ  2004                  45B, GALI NO 5, XYZ  2008    000008     2
5                 HECTIC, 99 STREET, PQR  2005                  23/4, STREET 2, PQR  2010    000010    11
6                    786, GALI NO 5, XYZ  2006                   786, GALI NO 4 XYZ  2007    000007     2
7       rambo, 45, strret 4, atlast, pqr  2007 del, 546, strret2, towards east, pqr  2009    000009    17


问:
Can we run a Java program without main method?
For example I want to print statement like -

```<code>System.out.println("Hello");
</code>```

How can the above line be printed on console without using the public static void main(String arg[]); in the class.

答:
You will soon be able to do that with JShell, this allow you to type java expression in a shell to get the result, without having to compile the program. Here is a simple example from JShell - Java 9 interpreter (REPL) - Getting Started and Examples

```<code>> jdk-9/bin/jshell -v

jshell> void helloJShell() { System.out.println("hello JShell"); }
|  created method helloJShell()

jshell> helloJShell();
hello JShell
</code>```

You could then simply do

```<code>jshell> System.out.println("hello");
</code>```

I didn't get time to try this yet but it look as simple as this.

Body:
For example I want to print statement like -

System.out.println("Hello");

How can the above line be printed on console without using the public static void main(String arg[]); in the class.

Body:
You will soon be able to do that with JShell, this allow you to type java expression in a shell to get the result, without having to compile the program. Here is a simple example from JShell - Java 9 interpreter (REPL) - Getting Started and Examples

> jdk-9/bin/jshell -v

jshell> void helloJShell() { System.out.println("hello JShell"); }
|  created method helloJShell()

jshell> helloJShell();
hello JShell

You could then simply do

jshell> System.out.println("hello");

I didn't get time to try this yet but it look as simple as this.


问:
Show only the first row in a UITableView
So, most of the questions are "my tableView only shows the first row, what's wrong?".
Well, what I need is exactly the opposite.

I have a SearchBar (not Search Display Controller) and until the user starts typing, I want to show ONLY the first row and nothing more.

My TableView's content is Dynamic Prototypes, with 2 Prototype Cells.
The first is the only one I want to show, but it shows others in blank.

https://www.dropbox.com/s/q4ak6z3gbc0gh5c/Screenshot%202014-07-22%2011.24.22.png

This is my tableView:numberOfRowsInSection:.

```<code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger numberOfRows = 0;

    if ([self.searchBar.text isEqualToString:@""]) {
        numberOfRows = 1;
    }

    return numberOfRows;
}
</code>```

All the help will be very appreciated! \o/

答:
Write the below 4 lines to make a table with one row. If you want to extend the content of the table just make the tableview scrollable.</p>

```<code>tblView                     = [[UITableView alloc]initWithFrame:CGRectZero];
tblView.separatorColor      = [UIColor clearColor];
tblView.tableFooterView     = [[UIView alloc] initWithFrame:CGRectZero];
tblView.scrollEnabled       = NO;
</code>```

Body:
So, most of the questions are "my tableView only shows the first row, what's wrong?".
Well, what I need is exactly the opposite.

I have a SearchBar (not Search Display Controller) and until the user starts typing, I want to show ONLY the first row and nothing more.

My TableView's content is Dynamic Prototypes, with 2 Prototype Cells.
The first is the only one I want to show, but it shows others in blank.

https://www.dropbox.com/s/q4ak6z3gbc0gh5c/Screenshot%202014-07-22%2011.24.22.png

This is my tableView:numberOfRowsInSection:.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger numberOfRows = 0;

    if ([self.searchBar.text isEqualToString:@""]) {
        numberOfRows = 1;
    }

    return numberOfRows;
}

All the help will be very appreciated! \o/

Body:
Write the below 4 lines to make a table with one row. If you want to extend the content of the table just make the tableview scrollable.

tblView                     = [[UITableView alloc]initWithFrame:CGRectZero];
tblView.separatorColor      = [UIColor clearColor];
tblView.tableFooterView     = [[UIView alloc] initWithFrame:CGRectZero];
tblView.scrollEnabled       = NO;


问:
Selectize - on change add URL parameter and refresh the page
URL using "http://localhost:8000/test.html"

I want to change URL to "http://localhost:8000/test.html?countrycode=SG" or "http://localhost:8000/test.html?countrycode=MY" or "http://localhost:8000/test.html?countrycode=IN" based on the selectize value selected.

Also, On select change it have get value and refresh the page.

Thanks

HTML:

```<code><div class="select-container">
  <select class="custom-select">
    <option value="SG">Singapore</option>
    <option value="MY">Malaysia</option>
    <option value="IN">India</option>
  </select>
</div>
</code>```

JS:

```<code>$('.custom-select').selectize();
</code>```

答:
You can do this

```<code><div class="select-container">
  <select class="custom-select">
    <option value="SG">Singapore</option>
    <option value="MY">Malaysia</option>
    <option value="IN">India</option>
  </select>
</div>

$(function() {
  $('.custom-select').selectize({
      onChange: function(value) {
        window.location = $getURLPath+'?countrycode=' + value;
      }
  });
});
</code>```

Demo : http://jsfiddle.net/jalayoza/uZmcD/88/

Hope this helps

Body:
URL using "http://localhost:8000/test.html"

I want to change URL to "http://localhost:8000/test.html?countrycode=SG" or "http://localhost:8000/test.html?countrycode=MY" or "http://localhost:8000/test.html?countrycode=IN" based on the selectize value selected.

Also, On select change it have get value and refresh the page.

Thanks

HTML:

  <select class="custom-select">
    <option value="SG">Singapore</option>
    <option value="MY">Malaysia</option>
    <option value="IN">India</option>
  </select>

JS:

$('.custom-select').selectize();

Body:
You can do this

<div class="select-container">
  <select class="custom-select">
    <option value="SG">Singapore</option>
    <option value="MY">Malaysia</option>
    <option value="IN">India</option>
  </select>
</div>

$(function() {
  $('.custom-select').selectize({
      onChange: function(value) {
        window.location = $getURLPath+'?countrycode=' + value;
      }
  });
});

Demo : http://jsfiddle.net/jalayoza/uZmcD/88/

Hope this helps


问:
Install two apks of different versions of application
I have two versions of the same Android application that I would like to have simultaneously on my Android device for easier testing. Is there a way to install both apk files such that they coexist on the same device?</p>

答:
use product flavours

```<code>productFlavors {
dev {
    applicationIdSuffix ".dev"
    versionCode 1
    versionName '1.0.0'
}
pro {
    applicationIdSuffix ".pro"
    versionCode 1
    versionName '1.0.0'
 }
}
</code>```

BUILDING APK

Click on gradle on right side of android studio

app --> tasks --> build --> assemble

OUTPUT

generated at --> app --> build --> outputs --> apk

Body:
use product flavours

productFlavors {
dev {
    applicationIdSuffix ".dev"
    versionCode 1
    versionName '1.0.0'
}
pro {
    applicationIdSuffix ".pro"
    versionCode 1
    versionName '1.0.0'
 }
}

BUILDING APK

Click on gradle on right side of android studio

app --> tasks --> build --> assemble

OUTPUT

generated at --> app --> build --> outputs --> apk


问:
OAuth2.0 token strange behaviour (Invalid Credentials 401)
Usually, Google OAuth2.0 mechanism is working great.

The user confirms permission to access Google account with selected scopes.

The refresh token is retrieved and saved to long time storage.

Each time needed (if the access token expired) access token is retrieved and used to access APIs.

But sometimes (thus far only two times for more than 6 months) I've experienced strange behaviour:

Requests to Google APIs return Invalid Credentials (401) error.
Refreshing the access token (using the stored refresh token) does not help.

Here is some structured output I've got when testing this issue:

```
    + ------------------------------------------------------------------------- +
    | 1.TRYING TO REFRESH THE TOKEN.                                            |
    | 2.DONE REFRESHING THE TOKEN.                                              |
    + ------------------------------------------------------------------------- +
    |    access:           **************************************************** |
    |   refresh:                  ********************************************* |
    |   expires:                                                           3600 |
    |   created:                                            2013-07-23 13:12:36 |
    + ------------------------------------------------------------------------- +
```

I've also tried to verify the "fresh" access token by sending requests to
 https://www.googleapis.com/oauth2/v1/tokeninfo

```
    + ------------------------------------------------------------------------- +
    | 1. TRYING TO CHECK THE TOKEN .                                            |
    | 2. DONE CHECKING THE TOKEN THE TOKEN.                                     |
    + ------------------------------------------------------------------------- +
    |       issued_to:                  ************.apps.googleusercontent.com |
    |        audience:                  ************.apps.googleusercontent.com |
    |         user_id:                                             ************ |
    |      expires_in:                                                     3600 |
    |           email:                                     **********@gmail.com |
    |  verified_email:                                                        1 |
    |     access_type:                                                  offline |
    |         scopes::                                                          |
    + ------------------------------------------------------------------------- +
    | https://www.googleapis.com/auth/userinfo.email                            |
    | https://www.googleapis.com/auth/userinfo.profile                          |
    | https://www.googleapis.com/auth/plus.me                                   |
    | https://www.googleapis.com/auth/drive                                     |
    + ------------------------------------------------------------------------- +
```

But when I try to access drive feed the response is:

```
    Error calling GET https://www.googleapis.com/drive/v2/files (401) Invalid Credentials

    domain:         global
    reason:         authError
    message:        Invalid Credentials
    locationType:   header
    location:       Authorization
```

We also experienced the same issue with calendars.
So:

Token was valid before (everything worked).

Refreshing token still works.

Requesting a feed responds with "Invalid Credentials" error.

All the other tokens are still working great, meaning that the code is valid.

Normally when the token is revoked "invalid_grant" error is returned when trying to refresh the token.

Questions

What can be the reason for this behaviour? If the refresh token was revoked or got invalid in some other way, should the request for new access token produce error?

Is there a way to validate the refresh token?

答:
I ran into this same problem when I needed to change my scopes from Read Only to Read And Write All Files. So, I updated my scopes from at the top of my file from Read Only to:

```<code>// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/drive'];
</code>```

Google, from their API guide, has these comments that say whenever you change scopes, you must update credentials. I believe this means, although I am not certain, that the token must be updated. The old token is still held by Google and it thought that I only had Read Only access, hence why it would return a 401 error. So, I need to remake my token, but Google never offered a new consent screen that would allow me to say allow Read And Write To All Files. So, I needed to get that screen to come up again, so it would create a new token to replace the old one:

```<code>fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
        getNewToken(oauth2Client, callback);
    //   oauth2Client.credentials = JSON.parse(token);
    //   callback(oauth2Client);
    }
  });
</code>```

Since I already had a saved token, it was never creating a new one. So, I just commented out the using of the old token and told it to get a new token, no matter if we have one or not. Then, I went to my Connected Apps in Google and deleted my old connecting credential. I'm not sure if this step is necessary, but I am only trying to access my personal account. Then, when I ran my program, it prompted me to re-authenticate, and everything worked and I did not receive an authentication error. Once done, make sure to remove the commented out lines for using already made tokens. I was using the Google API quickstart.js file for all of this.

So, when I updated my scopes, the old token was still using the Read Only scope, therefore I would get (401) Invalid Credentials.

Body:
Usually, Google OAuth2.0 mechanism is working great.

The user confirms permission to access Google account with selected scopes.

The refresh token is retrieved and saved to long time storage.

Each time needed (if the access token expired) access token is retrieved and used to access APIs.

But sometimes (thus far only two times for more than 6 months) I've experienced strange behaviour:

Requests to Google APIs return Invalid Credentials (401) error.
Refreshing the access token (using the stored refresh token) does not help.

Here is some structured output I've got when testing this issue:

    + ------------------------------------------------------------------------- +
    | 1.TRYING TO REFRESH THE TOKEN.                                            |
    | 2.DONE REFRESHING THE TOKEN.                                              |
    + ------------------------------------------------------------------------- +
    |    access:           **************************************************** |
    |   refresh:                  ********************************************* |
    |   expires:                                                           3600 |
    |   created:                                            2013-07-23 13:12:36 |
    + ------------------------------------------------------------------------- +

I've also tried to verify the "fresh" access token by sending requests to
 https://www.googleapis.com/oauth2/v1/tokeninfo

    + ------------------------------------------------------------------------- +
    | 1. TRYING TO CHECK THE TOKEN .                                            |
    | 2. DONE CHECKING THE TOKEN THE TOKEN.                                     |
    + ------------------------------------------------------------------------- +
    |       issued_to:                  ************.apps.googleusercontent.com |
    |        audience:                  ************.apps.googleusercontent.com |
    |         user_id:                                             ************ |
    |      expires_in:                                                     3600 |
    |           email:                                     **********@gmail.com |
    |  verified_email:                                                        1 |
    |     access_type:                                                  offline |
    |         scopes::                                                          |
    + ------------------------------------------------------------------------- +
    | https://www.googleapis.com/auth/userinfo.email                            |
    | https://www.googleapis.com/auth/userinfo.profile                          |
    | https://www.googleapis.com/auth/plus.me                                   |
    | https://www.googleapis.com/auth/drive                                     |
    + ------------------------------------------------------------------------- +

But when I try to access drive feed the response is:

    Error calling GET https://www.googleapis.com/drive/v2/files (401) Invalid Credentials

    domain:         global
    reason:         authError
    message:        Invalid Credentials
    locationType:   header
    location:       Authorization

We also experienced the same issue with calendars.
So:

Token was valid before (everything worked).

Refreshing token still works.

Requesting a feed responds with "Invalid Credentials" error.

All the other tokens are still working great, meaning that the code is valid.

Normally when the token is revoked "invalid_grant" error is returned when trying to refresh the token.

Questions

What can be the reason for this behaviour? If the refresh token was revoked or got invalid in some other way, should the request for new access token produce error?

Is there a way to validate the refresh token?

Body:
I ran into this same problem when I needed to change my scopes from Read Only to Read And Write All Files. So, I updated my scopes from at the top of my file from Read Only to:

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/drive'];

Google, from their API guide, has these comments that say whenever you change scopes, you must update credentials. I believe this means, although I am not certain, that the token must be updated. The old token is still held by Google and it thought that I only had Read Only access, hence why it would return a 401 error. So, I need to remake my token, but Google never offered a new consent screen that would allow me to say allow Read And Write To All Files. So, I needed to get that screen to come up again, so it would create a new token to replace the old one:

fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
        getNewToken(oauth2Client, callback);
    //   oauth2Client.credentials = JSON.parse(token);
    //   callback(oauth2Client);
    }
  });

Since I already had a saved token, it was never creating a new one. So, I just commented out the using of the old token and told it to get a new token, no matter if we have one or not. Then, I went to my Connected Apps in Google and deleted my old connecting credential. I'm not sure if this step is necessary, but I am only trying to access my personal account. Then, when I ran my program, it prompted me to re-authenticate, and everything worked and I did not receive an authentication error. Once done, make sure to remove the commented out lines for using already made tokens. I was using the Google API quickstart.js file for all of this.

So, when I updated my scopes, the old token was still using the Read Only scope, therefore I would get (401) Invalid Credentials.


问:
How do I mount a remote Linux folder in Windows through SSH?
I'm a blind student currently in a system admin/shell programming class. Although ssh works fine for executing commands like ls, pwd, etc editors do not work well with my screen reader and an ssh session. I was wondering if it is possible to mount a Linux folder over ssh so it appears as a windows drive? This way I could edit any files I needed to with accessible software and not have to constantly use SCP to send files back and fourth.</p>

答:
Take a look at CIFS (http://www.samba.org/cifs/). It is a virtual file system you can run on your linux machine that will allow you to mount folders on your linux machine in windows using SMB.

CIFS on linux information can be found here: http://linux-cifs.samba.org/

OwnerDisplayName: Jared

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Michael Haren

OwnerDisplayName: neesh

LastEditorDisplayName: neesh


问:
how to setup a .bat file as windows service?
how to setup a .bat file as windows service using command?</p>

答:
You can't.

Batch files can't be used as windows services.


问:
How do I set AFrame position using variables and javascript?
When I use:

```<code>myObject.setAttribute('position','3 0 35' );
</code>```

everything works fine.

I want to set attributes from variables,
instead of having to manually type in the numbers,
like this:

```<code>myObject.setAttribute('position','myX myY myZ' );
</code>```

What am I doing wrong?

答:
https://aframe.io/docs/0.5.0/introduction/javascript-events-dom-apis.html#adding-a-component-with-setattribute

el.setAttribute('position', {x: myX, y: myY, z: myZ});

Body:
When I use:

myObject.setAttribute('position','3 0 35' );

everything works fine.

I want to set attributes from variables,
instead of having to manually type in the numbers,
like this:

myObject.setAttribute('position','myX myY myZ' );

What am I doing wrong?


问:
How to make div appear on button click using Javascript
I'm trying to make a div appear on button click which I've not succeeded from the below code.Please let me know if I've done any thing wrong in the code.

function showDiv() {
  document.getElementById('sign-in').style.display = "block";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Login

<div id="sign-in" class="login" style="display: none;">
  <form>
    <div class="row">
      <div class="col-md-3">
        <div class="form-group inline-form">
          <input type="email" class="form-control" id="email" Placeholder="email">
        </div>
      </div>
      <div class="col-md-3">
        <div class="form-group inline-form">
          <input type="password" class="form-control" id="pwd">
        </div>
      </div>
      <div class="col-md-3">
        <div class="checkbox">
          <label><input type="checkbox"> Remember me</label>
        </div>
      </div>
      <div class="col-md-3">
        <button type="submit" class="btn btn-default ">Submit</button>
      </div>
    </div>
  </form>
</div></code>```

答:
change getElementByid to getElementById (i to I)

function showDiv() {
  document.getElementById('sign-in').style.display = "block";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Login

<div id="sign-in" class="login" style="display: none;">
  <form>
    <div class="row">
      <div class="col-md-3">
        <div class="form-group inline-form">
          <input type="email" class="form-control" id="email" Placeholder="email">
        </div>
      </div>
      <div class="col-md-3">
        <div class="form-group inline-form">
          <input type="password" class="form-control" id="pwd">
        </div>
      </div>
      <div class="col-md-3">
        <div class="checkbox">
          <label><input type="checkbox"> Remember me</label>
        </div>
      </div>
      <div class="col-md-3">
        <button type="submit" class="btn btn-default ">Submit</button>
      </div>
    </div>
  </form>
</div></code>```

Body:
I'm trying to make a div appear on button click which I've not succeeded from the below code.Please let me know if I've done any thing wrong in the code.

function showDiv() {
  document.getElementById('sign-in').style.display = "block";
}

Login

  <form>

          <input type="email" class="form-control" id="email" Placeholder="email">

          <input type="password" class="form-control" id="pwd">

          <input type="checkbox"> Remember me

        <button type="submit" class="btn btn-default ">Submit</button>

  </form>

Body:
change getElementByid to getElementById (i to I)

function showDiv() {
  document.getElementById('sign-in').style.display = "block";
}

<a class="btn btn-default log-bar" href="#" role="button" onclick="showDiv()">Login</a>

<div id="sign-in" class="login" style="display: none;">
  <form>
    <div class="row">
      <div class="col-md-3">
        <div class="form-group inline-form">
          <input type="email" class="form-control" id="email" Placeholder="email">
        </div>
      </div>
      <div class="col-md-3">
        <div class="form-group inline-form">
          <input type="password" class="form-control" id="pwd">
        </div>
      </div>
      <div class="col-md-3">
        <div class="checkbox">
          <label><input type="checkbox"> Remember me</label>
        </div>
      </div>
      <div class="col-md-3">
        <button type="submit" class="btn btn-default ">Submit</button>
      </div>
    </div>
  </form>
</div>


问:
How to remove the "Connected to BrowserSync" badge from lite-server in the browser
I've installed the John Papa's lite-server NPM package via VS Code console and it's working. But, how can I remove the "Connected to BrowserSync" badge that appears in the browser every time a save a file - and it reloads the file automatically in the browser?</p>

答:
create a config file  bs-config.js

and add "notify": false

```<code>module.exports = {
     "notify": false,
};
</code>```

if config file location is different from where server starts then specify it

```<code>lite-server -c path/config-file-name.js
</code>```

Body:
create a config file  bs-config.js

and add "notify": false

module.exports = {
     "notify": false,
};

if config file location is different from where server starts then specify it

lite-server -c path/config-file-name.js


问:
Adding css in rails
I'm building a simple rails app and in the application.html.erb file I created a Bootstrap navbar inside the body.

I realised that when I put any content in index.html.erb (the home page), the navbar blocks the content. So I am going to add a padding to the 'body' element in 'application.html.erb' i.e., the common layout file.

But when I add the padding to 'home.scss', it doesn't work. The file says:

// Place all the styles related to the home controller here.
// They will automatically be included in application.css.

So by right, this body style should be reflected in the navbar, but it doesn't. Where should I be including the style css for the common layout (application.html.erb)?

also, for other pages (ex. index.html.erb), 1) How do I link up the css file (do I do it like any other html file) and 2) Where do I edit the css?

I've browsed over 20 resources but I don't seem to be able to find a good explanation.

+ Fixed:

My css file was named 'application.scss.css' . When I renamed it to 'application.css.scss', it worked. Thank you!

答:
Step 1.
Checked out Your GEmfile. </p>

```<code>gem 'bootstrap-sass', '~> 3.3.6'
gem 'sass-rails', '~> 5.0'
bundle install
</code>```

<p>This gems are Both Css and Bootstrap.
Step 2.
    cd /app/assets/stylesheets
    Rename the file Application.css - To- Application.scss
  then run your code </p>

Title: Adding css in rails

Body:
Step 1.
Checked out Your GEmfile.

gem 'bootstrap-sass', '~> 3.3.6'
gem 'sass-rails', '~> 5.0'
bundle install

This gems are Both Css and Bootstrap.
Step 2.
    cd /app/assets/stylesheets
    Rename the file Application.css - To- Application.scss
  then run your code


问:
open new activity with button
here is the code of my xml.

```<code><Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn2"
            android:layout_gravity="center_horizontal"
            android:text="Make New Account"
            android:onClick="new"
            android:textColor="#E74C3C"
            android:textStyle="bold"
            android:paddingTop="20dp"/>
</code>```

and here is my code of java.

```<code> public Button btn2;
public void onClick(){
    btn2=(Button)findViewById(R.id.btn2);
    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,submit.class);
            startActivity(intent);
        }
    });

}
</code>```

my button is not working yet, even an message will appear after clicking on button that unfortunately application has stopped... what is the reason??

答:
Try this code:-

```<code><Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn2"
    android:layout_gravity="center_horizontal"
    android:text="Make New Account"
    android:textColor="#E74C3C"
    android:textStyle="bold"
    android:paddingTop="20dp"/>
</code>```

Put this in your activity:-

```<code>    btn2 = (Button) findViewById(R.id.btn2);
    btn2.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Intent intent = new Intent(MainActivity.this,submit.class);
            startActivity(intent);
        }
    });
</code>```

Title: open new activity with button

Body:
here is the code of my xml.

<Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn2"
            android:layout_gravity="center_horizontal"
            android:text="Make New Account"
            android:onClick="new"
            android:textColor="#E74C3C"
            android:textStyle="bold"
            android:paddingTop="20dp"/>

and here is my code of java.

 public Button btn2;
public void onClick(){
    btn2=(Button)findViewById(R.id.btn2);
    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,submit.class);
            startActivity(intent);
        }
    });

}

my button is not working yet, even an message will appear after clicking on button that unfortunately application has stopped... what is the reason??

Body:
Try this code:-

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn2"
    android:layout_gravity="center_horizontal"
    android:text="Make New Account"
    android:textColor="#E74C3C"
    android:textStyle="bold"
    android:paddingTop="20dp"/>

Put this in your activity:-

    btn2 = (Button) findViewById(R.id.btn2);
    btn2.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Intent intent = new Intent(MainActivity.this,submit.class);
            startActivity(intent);
        }
    });


问:
MySQL where clause not returning expected value
I have a query

```<code>SELECT *
FROM   hayabusa.customer_staging
WHERE  tin = "888-596-592"
        OR gsis_sss_no = "bp0279638"
        OR last_name LIKE "%dela cruz%"
        OR first_name LIKE "%jose%"
        OR date_of_birth = "8/8/1978"
        OR gender = "male"
           AND parent_id = 0
           AND is_proccessed = 0
           AND id > 27
           AND ( filename = "sample cif csv file - copy.csv"
                  OR filename = "sample cif csv file2.csv" )
GROUP  BY tin,
          gsis_sss_no,
          last_name,
          first_name,
          date_of_birth,
          gender
ORDER  BY CASE
            WHEN tin = "888-596-592" THEN 1
            ELSE 2
          end,
          id
LIMIT  1;
</code>```

But it's returning a row with an id of 3 and a filename which is not in the where clause. What is wrong with it?

答:
I believe that AND has higher precedence than OR in MySQL (and most databases), so your current query is treating your AND condition with the filename as being optional.  Try rewriting the WHERE clause as this:

```<code>WHERE
    (tin = "888-596-592"
    OR gsis_sss_no = "bp0279638"
    OR last_name LIKE "%dela cruz%"
    OR first_name LIKE "%jose%"
    OR date_of_birth = "8/8/1978"
    OR gender = "male")
       AND parent_id = 0
       AND is_proccessed = 0
       AND id > 27
       AND ( filename = "sample cif csv file - copy.csv"
              OR filename = "sample cif csv file2.csv" )
</code>```

Also, I don't know which columns you intend to select, but using SELECT * here is probably inappropriate.  Instead, you should list out which columns you want to select.  Strictly speaking, only columns appearing in the GROUP BY clause or columns which are inside aggregate functions are eligible for selection in your query.

Body:
I have a query

SELECT *
FROM   hayabusa.customer_staging
WHERE  tin = "888-596-592"
        OR gsis_sss_no = "bp0279638"
        OR last_name LIKE "%dela cruz%"
        OR first_name LIKE "%jose%"
        OR date_of_birth = "8/8/1978"
        OR gender = "male"
           AND parent_id = 0
           AND is_proccessed = 0
           AND id > 27
           AND ( filename = "sample cif csv file - copy.csv"
                  OR filename = "sample cif csv file2.csv" )
GROUP  BY tin,
          gsis_sss_no,
          last_name,
          first_name,
          date_of_birth,
          gender
ORDER  BY CASE
            WHEN tin = "888-596-592" THEN 1
            ELSE 2
          end,
          id
LIMIT  1;

But it's returning a row with an id of 3 and a filename which is not in the where clause. What is wrong with it?

Body:
I believe that AND has higher precedence than OR in MySQL (and most databases), so your current query is treating your AND condition with the filename as being optional.  Try rewriting the WHERE clause as this:

WHERE
    (tin = "888-596-592"
    OR gsis_sss_no = "bp0279638"
    OR last_name LIKE "%dela cruz%"
    OR first_name LIKE "%jose%"
    OR date_of_birth = "8/8/1978"
    OR gender = "male")
       AND parent_id = 0
       AND is_proccessed = 0
       AND id > 27
       AND ( filename = "sample cif csv file - copy.csv"
              OR filename = "sample cif csv file2.csv" )

Also, I don't know which columns you intend to select, but using SELECT * here is probably inappropriate.  Instead, you should list out which columns you want to select.  Strictly speaking, only columns appearing in the GROUP BY clause or columns which are inside aggregate functions are eligible for selection in your query.


答:
You have typed wrong  document.getElementByid it should be capital I document.getElementById

function showDiv() {
  document.getElementById('sign-in').style.display = "block";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Login

<div id="sign-in" class="login" style="display: none;">
  <form>
    <div class="row">
      <div class="col-md-3">
        <div class="form-group inline-form">
          <input type="email" class="form-control" id="email" Placeholder="email">
        </div>
      </div>
      <div class="col-md-3">
        <div class="form-group inline-form">
          <input type="password" class="form-control" id="pwd">
        </div>
      </div>
      <div class="col-md-3">
        <div class="checkbox">
          <label><input type="checkbox"> Remember me</label>
        </div>
      </div>
      <div class="col-md-3">
        <button type="submit" class="btn btn-default ">Submit</button>
      </div>
    </div>
  </form>
</div></code>```

Title: How to make div appear on button click using Javascript

Body:
You have typed wrong  document.getElementByid it should be capital I document.getElementById

function showDiv() {
  document.getElementById('sign-in').style.display = "block";
}

<a class="btn btn-default log-bar" href="#" role="button" onclick="showDiv()">Login</a>

<div id="sign-in" class="login" style="display: none;">
  <form>
    <div class="row">
      <div class="col-md-3">
        <div class="form-group inline-form">
          <input type="email" class="form-control" id="email" Placeholder="email">
        </div>
      </div>
      <div class="col-md-3">
        <div class="form-group inline-form">
          <input type="password" class="form-control" id="pwd">
        </div>
      </div>
      <div class="col-md-3">
        <div class="checkbox">
          <label><input type="checkbox"> Remember me</label>
        </div>
      </div>
      <div class="col-md-3">
        <button type="submit" class="btn btn-default ">Submit</button>
      </div>
    </div>
  </form>
</div>


问:
Changing Deeply Nested Object Value
This seems to be obvious, but i can't figure out how to shortening change deeply nested object value in multiple places in the code without retyping each time keys path to this value:

```<code>> obj = { 'key1': { 'key2': { 'key3': { 'key4': { 'key5': 'value' }}}}}
> obj.key1.key2.key3.key4.key5
'value'
</code>```

```<code>> obj.key1.key2.key3.key4.key5 = 'changeme'
> obj.key1.key2.key3.key4.key5
'changeme'

> obj.key1.key2.key3.key4.key5 = 'changeme2'
> obj.key1.key2.key3.key4.key5
'changeme2'
</code>```

答:
You could use a bit of recursion to iterate over every key in your object and update where it finds a matching key.

const obj = { 'key1': { 'key2': { 'key3': { 'key4': { 'key5': 'value' }}}, 'key5': 'test'}}

const mutateObjectProperty = (prop, value, obj) =>
  obj.constructor === Object && Object.keys(obj).forEach(key => {
    if (key === prop) obj[key] = value
    mutateObjectProperty(prop, value, obj[key])
  })

mutateObjectProperty('key5', 'updated', obj)

console.log(obj)```

Title: Changing Deeply Nested Object Value

Body:
This seems to be obvious, but i can't figure out how to shortening change deeply nested object value in multiple places in the code without retyping each time keys path to this value:

> obj = { 'key1': { 'key2': { 'key3': { 'key4': { 'key5': 'value' }}}}}
> obj.key1.key2.key3.key4.key5
'value'

> obj.key1.key2.key3.key4.key5 = 'changeme'
> obj.key1.key2.key3.key4.key5
'changeme'

> obj.key1.key2.key3.key4.key5 = 'changeme2'
> obj.key1.key2.key3.key4.key5
'changeme2'


答:
Its Simple </p>

```<code><script>
function showDiv() {
   document.getElementById('sign-in').style.display = "block";
}
</script>
</code>```

Body:
Its Simple

<script>
function showDiv() {
   document.getElementById('sign-in').style.display = "block";
}
</script>


问:
Solve one-to-many relationship in Data warehouse?
I'm a new member of Data warehouse. I'm designing model alter Star Schema.
I have a 2 table: Contract table & Complain table. One Contract can have one or more value in Complain table. You can see 2 photo below.

in facttable, 1 contract only have one row. complain table can have 1 or more values for each contract_id. i've tried the bridges table, but it wasn't good enough.
Thank all

http://prntscr.com/fgdnpb (Conplain table)

http://prntscr.com/fgdorh (Contract table)

My Skype: dinhhungdigital

答:
You are confusing fact table and dimension table. Your dimension should be "Contract", and your fact table should be "Complaint", connected on Contract_Id as one-to-many (as start schema requires).

Learn about Star Schema Design


问:
Count keywords occurrence in a file to another file
I have two files File1 and File2. I have to find keywords in File2 to File1 and count it. Lines in File1 that don't have any keywords in File2 shall be counted as OTHERS and probably save it in File3 (for validation).

File1

```<code> 000001111YYYY0000
 122334YYYY9999
 89898989AAAA89899
 AAAA7678989812234
 ZZZZ878098098098
 0000000000000000
</code>```

File2

```<code>YYYY
AAAA
ZZZZ
</code>```

Output

```<code>YYYY: 2
AAAA: 2
ZZZZ: 1
OTHERS: 1
</code>```

File3 (OTHERS)

```<code>0000000000000000
</code>```

The way I know is to count the keywords using grep and wc -l, and its not ideal especially when I have many keywords to find.

答:
```<code>awk 'BEGIN{a["OTHERS"]=0}
  (NR==FNR) {a[$0]=0;next}
  {b=0}{for(i in a) if( match($0,i) !=0 ){a[i]++;b=1} }
  {if(b==0) a["OTHERS"]++}
  END{for(i in a) print i,": ",a[i]}'
  File2 File1
</code>```

Body:
I have two files File1 and File2. I have to find keywords in File2 to File1 and count it. Lines in File1 that don't have any keywords in File2 shall be counted as OTHERS and probably save it in File3 (for validation).

File1

 000001111YYYY0000
 122334YYYY9999
 89898989AAAA89899
 AAAA7678989812234
 ZZZZ878098098098
 0000000000000000

File2

YYYY
AAAA
ZZZZ

Output

YYYY: 2
AAAA: 2
ZZZZ: 1
OTHERS: 1

File3 (OTHERS)

0000000000000000

The way I know is to count the keywords using grep and wc -l, and its not ideal especially when I have many keywords to find.


问:
SQL Server : select distinct until the value is changed
I have a table of tasks (each task can has a few rows) that looks something like this:

```<code>TaskID | DateCreated | Status
-------+-------------+------------
  1    | 01-01-2017  | Started
  2    | 02-02-2017  | InProgress
  1    | 02-02-2017  | Started
  1    | 03-03-2017  | InProgress
  2    | 03-03-2017  | InProgress
  1    | 04-04-2017  | InProgress
  2    | 04-04-2017  | Done
  1    | 05-05-2017  | Done
</code>```

I have more columns which are not relevant for this requirement.

What I need here is to select the actual status flow that a specific task has passed.

For example, for task with TaskID = 1, I want to get the following result:

```<code>TaskID | Status
-------+-------------
  1    | Started
  1    | InProgress
  1    | Done
</code>```

Notes:

The rows may be not sorted

A status can repeat itself, e.g. there can be a task that its' status flow was:

```<code>Started ==> InProgress ==> Break ==> InProgress ==> Done
</code>```

so will not help me to get for each task the unique status from each status type it passed

答:
Below is the query where in partition by will fetch you the desired result.</p>

```<code>select taskid,status(select taskid,status
,row_number()over(partition by taskid,status order by taskid)rownum
from [yourtablename])tmp
where rownum = 1
</code>```

Body:
I have a table of tasks (each task can has a few rows) that looks something like this:

TaskID | DateCreated | Status
-------+-------------+------------
  1    | 01-01-2017  | Started
  2    | 02-02-2017  | InProgress
  1    | 02-02-2017  | Started
  1    | 03-03-2017  | InProgress
  2    | 03-03-2017  | InProgress
  1    | 04-04-2017  | InProgress
  2    | 04-04-2017  | Done
  1    | 05-05-2017  | Done

I have more columns which are not relevant for this requirement.

What I need here is to select the actual status flow that a specific task has passed.

For example, for task with TaskID = 1, I want to get the following result:

TaskID | Status
-------+-------------
  1    | Started
  1    | InProgress
  1    | Done

Notes:

The rows may be not sorted

A status can repeat itself, e.g. there can be a task that its' status flow was:

Started ==> InProgress ==> Break ==> InProgress ==> Done

so will not help me to get for each task the unique status from each status type it passed

Body:
Below is the query where in partition by will fetch you the desired result.

select taskid,status(select taskid,status
,row_number()over(partition by taskid,status order by taskid)rownum
from [yourtablename])tmp
where rownum = 1


问:
Ambiguous Reference in ASP.Net Core API
I created a ASP.Net Core application within Visual Studio 2017 and referenced my Core library as a project reference which is now giving me ambiguous reference errors. For some reason it is getting 2 instances of each class

Here is a list of my included dependencies

答: Have you tried restarting your Visual Studio? this seems to help sometimes.</p>

Title: Ambiguous Reference in ASP.Net Core API


问:
How to convert date 1110101 which means 1/1/2011 to a date that Tableau can recognize
I have a data set with date format (which according to our IT it's an IBM format) 1110101 which means 1/1/2011, so 1160506 means 5/6/2016. I tried to convert it to date format that tableau can recognize and here's the plan:

Step 1, I create a field called "Date Converted"= Date I have + 19000000
Step 2, I use DATEPARSE to convert it to date by:

DATEPARSE("yyyymmdd",19000000+[Date I have])

But Tableau doesn't accept DATEPARSE and it says it's an unknown syntax. Anyone know's how to correctly convert IBM date format to a date that Tableau can recognize?

答:
My date format

Change your format in string

Create custom calculation

```<code>MID([Date],6,2) + "/" + MID([Date],4,2) + "/" +MID([Date],2,2)
</code>```

Change your data type to date

You date will look like this

Body:
My date format

Change your format in string

Create custom calculation

MID([Date],6,2) + "/" + MID([Date],4,2) + "/" +MID([Date],2,2)

Change your data type to date

You date will look like this


问:
Include headers in header files because of Qt moc
I try to stick to the principle of including headers in implementation files and not in .h files. But for qt projects I have to run most of my header files through moc which then complains about classes it doesn't know about. I use moc header.h -o header.moc.cpp and then link all cpp's and the .moc.cpp's together.
Example:

header1.h and a cpp file to go with it where I include header1.h at the top

```<code>#ifndef __HEADER_1_H
#define __HEADER_1_H

class Baseclass { /* ... */ };

#endif
</code>```

header2.h and a cpp file to go with it where I include header1.h and header2.h at the top

```<code>#ifndef __HEADER_2_H
#define __HEADER_2_H
//here is where I then have to #include "header1.h" because of moc

class Derived: public QObject, public Base { Q_OBJECT; /* ... */ };
#endif
</code>```

Now the problem is when I have another class in another header and cpp file:

header3.h
    #ifndef __HEADER_3_H
    #define __HEADER_3_H

```<code>//I have to include header2.h because moc doesn't know about Derived.

class Other : public QWidget { Q_OBJECT; Derived* d };
</code>```

Then in an implementation file I need to use Derived and Other, but when I include their headers I obviously get multiple definition errors. I can circumvent this by including only header3.h which will in turn include the other headers.
I think this leads to very confusing code with unnecessarily included stuff and other invisibly included stuff (thus being error prone). How can I do this better?

答:
You have multiple definitions because probably you have some function definitions in the header files, so move those to the corresponding .cpp files.

Now about includes:
You need the include (full type) for inheritance (not for moc):

```<code>#ifndef __HEADER_2_H
#define __HEADER_2_H
//here you need to include header1, because you inherit from that class
//and this needs to see the whole object blueprint
//forward declaration is not enough.
#include <QObject>
#include "Baseclass.h" //or header1.h or whateven the file name is

class Derived: public QObject, public Baseclass { Q_OBJECT; /* ... */ };
#endif
</code>```

You need full type for inheritance and for the Derived you can use forward declaration, because you only have a pointer:

```<code>//you need include for QWidget, because you inherit from it
#include <QWidget>
//and forward declaration for derived
Class Derived;

class Other : public QWidget { Q_OBJECT; Derived* d };
</code>```

In the file other.cpp you'll need to include the "Derived.h" if you want to use functionality from Derived

Body:
I try to stick to the principle of including headers in implementation files and not in .h files. But for qt projects I have to run most of my header files through moc which then complains about classes it doesn't know about. I use moc header.h -o header.moc.cpp and then link all cpp's and the .moc.cpp's together.
Example:

header1.h and a cpp file to go with it where I include header1.h at the top

#ifndef __HEADER_1_H
#define __HEADER_1_H

class Baseclass { /* ... */ };

#endif

header2.h and a cpp file to go with it where I include header1.h and header2.h at the top

#ifndef __HEADER_2_H
#define __HEADER_2_H
//here is where I then have to #include "header1.h" because of moc

class Derived: public QObject, public Base { Q_OBJECT; /* ... */ };
#endif

Now the problem is when I have another class in another header and cpp file:

header3.h
    #ifndef __HEADER_3_H
    #define __HEADER_3_H

//I have to include header2.h because moc doesn't know about Derived.

class Other : public QWidget { Q_OBJECT; Derived* d };

Then in an implementation file I need to use Derived and Other, but when I include their headers I obviously get multiple definition errors. I can circumvent this by including only header3.h which will in turn include the other headers.
I think this leads to very confusing code with unnecessarily included stuff and other invisibly included stuff (thus being error prone). How can I do this better?

Body:
You have multiple definitions because probably you have some function definitions in the header files, so move those to the corresponding .cpp files.

Now about includes:
You need the include (full type) for inheritance (not for moc):

#ifndef __HEADER_2_H
#define __HEADER_2_H
//here you need to include header1, because you inherit from that class
//and this needs to see the whole object blueprint
//forward declaration is not enough.
#include <QObject>
#include "Baseclass.h" //or header1.h or whateven the file name is

class Derived: public QObject, public Baseclass { Q_OBJECT; /* ... */ };
#endif

You need full type for inheritance and for the Derived you can use forward declaration, because you only have a pointer:

//you need include for QWidget, because you inherit from it
#include <QWidget>
//and forward declaration for derived
Class Derived;

class Other : public QWidget { Q_OBJECT; Derived* d };

In the file other.cpp you'll need to include the "Derived.h" if you want to use functionality from Derived


问:
ASP.Net: How to control div-style in backend?
I will control the style from a div-container from the backend (c#, code behind).

I will not use the runat="server"-tag, because the div-id is much used in javaScript.

How to do?

答: In .net 4.0 just use a panel control (which gets rendered as a div) and set the ClientIDMode to static. So you can set your styles on the server-side and still easily access it in your JS code.</p>


问:
'required' css selector syntax
I found following CSS in https://angular.io/docs/ts/latest/guide/forms.html

```<code>.ng-valid[required], .ng-valid.required  {
  border-left: 5px solid #42A948; /* green */
}
.ng-invalid:not(form)  {
  border-left: 5px solid #a94442; /* red */
}
</code>```

I have not seen .ng-valid[required] syntax before. I guess .ng-valid is a class. Is [required] some new CSS syntax?

答:
With the CSS attribute selector *[required] you can format elements with the attribute required. The syntax isn't new. See the following example:

input[required] {
  border:1px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" required/>
<input type="text"/></code>```

This is often used in <form>s to define some elements like <input> as required. With the CSS attribute selector *[required] you can format these required elements.

You can also use the :required pseudo-class to format the required elements:

input:required {
  border:1px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" required/>
<input type="text"/></code>```

The :required CSS pseudo-class represents any <input> element that has the required attribute set on it. This allows forms to easily indicate which fields must have valid data before the form can be submitted.

  source: https://developer.mozilla.org/en-US/docs/Web/CSS/:required

Title: 'required' css selector syntax

Body:
I found following CSS in https://angular.io/docs/ts/latest/guide/forms.html

.ng-valid[required], .ng-valid.required  {
  border-left: 5px solid #42A948; /* green */
}
.ng-invalid:not(form)  {
  border-left: 5px solid #a94442; /* red */
}

I have not seen .ng-valid[required] syntax before. I guess .ng-valid is a class. Is [required] some new CSS syntax?

Body:
With the CSS attribute selector *[required] you can format elements with the attribute required. The syntax isn't new. See the following example:

input[required] {
  border:1px solid red;
}

<input type="text" required/>
<input type="text"/>

This is often used in <form>s to define some elements like <input> as required. With the CSS attribute selector *[required] you can format these required elements.

You can also use the :required pseudo-class to format the required elements:

input:required {
  border:1px solid red;
}

<input type="text" required/>
<input type="text"/>

The :required CSS pseudo-class represents any <input> element that has the required attribute set on it. This allows forms to easily indicate which fields must have valid data before the form can be submitted.

  source: https://developer.mozilla.org/en-US/docs/Web/CSS/:required


问:
Multiple search view for single array list model class data
I have a model class array list with field name, code and mobile. I want to use search view for all. For example, if I write in name search view xyz and in mobile search view 9768 then it gives all the match of xyz and 9768.</p>

```<code> searchMasterList2.add(new SearchItemMaster("111", "222", "333"));
        searchMasterList2.add(new SearchItemMaster("555", "333", "444"));
        searchMasterList2.add(new SearchItemMaster("222", "444", "555"));
        searchMasterList2.add(new SearchItemMaster("333", "111", "222"));
        searchMasterList2.add(new SearchItemMaster("444", "555", "111"));

        final android.support.v7.widget.SearchView searchView1 = (android.support.v7.widget.SearchView) getView().findViewById(R.id.item_name_edtv);

        searchView1.setOnSearchClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                is_click_search_item=true;
                is_click_search_group=false;
            }
        });
        searchView1.setOnQueryTextListener(this);
        searchView1.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                is_click_search_item=true;
                is_click_search_group=false;
            }
        });
        final android.support.v7.widget.SearchView searchView2 = (android.support.v7.widget.SearchView) getView().findViewById(R.id.group_edtv);
        searchView2.setOnSearchClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                is_click_search_item=false;
                is_click_search_group=true;

            }
        });

        searchView2.setOnQueryTextListener(this);
        searchView2.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                is_click_search_item=false;
                is_click_search_group=true;

            }
        });

     @Override
        public boolean onQueryTextChange(String newText) {

            final List<SearchItemMaster> filteredModelList = filter(searchMasterList2, newText);
            Log.v("App", newText + ", " + searchMasterList2.size() + ", " + filteredModelList.size());
            adapter.animateTo(filteredModelList);
            recyclerView.scrollToPosition(0);
            return false;
        }

 private List<SearchItemMaster> filter(List<SearchItemMaster> numbers, String input_text) {
        input_text = input_text.toLowerCase();
        ArrayList<SearchItemMaster> filteredCompanyList = new ArrayList<>();
        for (SearchItemMaster searchItemMaster : numbers) {

            if (is_click_search_group) {
                final String moblieNo = searchItemMaster.getMoblieNo();
                if (moblieNo.contains(input_text)) {
                    filteredCompanyList.add(searchItemMaster);
                }
            }

            if (is_click_search_item) {

                final String code = searchItemMaster.getCode().toLowerCase();
                if (code.contains(input_text)) {
                    filteredCompanyList.add(searchItemMaster);
                }
            }
        }

        return filteredCompanyList;
    }
</code>```

答:
You can do it using loop and comparing each item values.

For Ex. if you enter Xyz in name search and 9876 in number then loop like:-

```<code>ArrayList<SearchItemMaster> resultArrayList = new ArrayList<>();
for(SearchItemMaster searchItemMasterObj : searchItemMasterList) {
    if(searchItemMasterObj.getName().contains("Xyz") && searchItemMasterObj.getNumber().contains("9876")) {
        resultArrayList.add(searchItemMasterObj);
    }
}
</code>```

and then you can use resultArrayList to show the result.

hope this will help you. :)

Body:
I have a model class array list with field name, code and mobile. I want to use search view for all. For example, if I write in name search view xyz and in mobile search view 9768 then it gives all the match of xyz and 9768.

 searchMasterList2.add(new SearchItemMaster("111", "222", "333"));
        searchMasterList2.add(new SearchItemMaster("555", "333", "444"));
        searchMasterList2.add(new SearchItemMaster("222", "444", "555"));
        searchMasterList2.add(new SearchItemMaster("333", "111", "222"));
        searchMasterList2.add(new SearchItemMaster("444", "555", "111"));

        final android.support.v7.widget.SearchView searchView1 = (android.support.v7.widget.SearchView) getView().findViewById(R.id.item_name_edtv);

        searchView1.setOnSearchClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                is_click_search_item=true;
                is_click_search_group=false;
            }
        });
        searchView1.setOnQueryTextListener(this);
        searchView1.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                is_click_search_item=true;
                is_click_search_group=false;
            }
        });
        final android.support.v7.widget.SearchView searchView2 = (android.support.v7.widget.SearchView) getView().findViewById(R.id.group_edtv);
        searchView2.setOnSearchClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                is_click_search_item=false;
                is_click_search_group=true;

            }
        });

        searchView2.setOnQueryTextListener(this);
        searchView2.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                is_click_search_item=false;
                is_click_search_group=true;

            }
        });

     @Override
        public boolean onQueryTextChange(String newText) {

            final List<SearchItemMaster> filteredModelList = filter(searchMasterList2, newText);
            Log.v("App", newText + ", " + searchMasterList2.size() + ", " + filteredModelList.size());
            adapter.animateTo(filteredModelList);
            recyclerView.scrollToPosition(0);
            return false;
        }

 private List<SearchItemMaster> filter(List<SearchItemMaster> numbers, String input_text) {
        input_text = input_text.toLowerCase();
        ArrayList<SearchItemMaster> filteredCompanyList = new ArrayList<>();
        for (SearchItemMaster searchItemMaster : numbers) {

            if (is_click_search_group) {
                final String moblieNo = searchItemMaster.getMoblieNo();
                if (moblieNo.contains(input_text)) {
                    filteredCompanyList.add(searchItemMaster);
                }
            }

            if (is_click_search_item) {

                final String code = searchItemMaster.getCode().toLowerCase();
                if (code.contains(input_text)) {
                    filteredCompanyList.add(searchItemMaster);
                }
            }
        }

        return filteredCompanyList;
    }

Body:
You can do it using loop and comparing each item values.

For Ex. if you enter Xyz in name search and 9876 in number then loop like:-

ArrayList<SearchItemMaster> resultArrayList = new ArrayList<>();
for(SearchItemMaster searchItemMasterObj : searchItemMasterList) {
    if(searchItemMasterObj.getName().contains("Xyz") && searchItemMasterObj.getNumber().contains("9876")) {
        resultArrayList.add(searchItemMasterObj);
    }
}

and then you can use resultArrayList to show the result.

hope this will help you. :)


问:
DKImagePickerController fatal error: unexpectedly found nil while unwrapping an Optional value
I am trying to integrate DKImagePickerController into my project.

The github is here:
DKImagePickerController

I did the cocoapods update. The demo project is running fine, but my project has the error when I click button to the view of the photos library:

unexpectedly found nil while unwrapping an Optional value

in the first line of

```<code>func showImagePicker() {
        pickerController.defaultSelectedAssets = self.assets  /* this one
If anyone know what wrong, I appreciate it*/
</code>```

答:
The object pickerController is only declared, not initialized. The SDK's guide page has already given the example, and I changed some lines for your situation:

```<code>func showImagePicker() {
    if pickerController == nil {
         pickerController = DKImagePickerController()
    }

    pickerController.defaultSelectedAssets = self.assets
    pickerController.didSelectAssets = { (assets: [DKAsset]) in
        self.assets = assets
        //Continue handle images which in the assets.
    }

    self.presentViewController(pickerController, animated: true) {}
}
</code>```

Body:
I am trying to integrate DKImagePickerController into my project.

The github is here:
DKImagePickerController

I did the cocoapods update. The demo project is running fine, but my project has the error when I click button to the view of the photos library:

unexpectedly found nil while unwrapping an Optional value

in the first line of

func showImagePicker() {
        pickerController.defaultSelectedAssets = self.assets  /* this one
If anyone know what wrong, I appreciate it*/

Body:
The object pickerController is only declared, not initialized. The SDK's guide page has already given the example, and I changed some lines for your situation:

func showImagePicker() {
    if pickerController == nil {
         pickerController = DKImagePickerController()
    }

    pickerController.defaultSelectedAssets = self.assets
    pickerController.didSelectAssets = { (assets: [DKAsset]) in
        self.assets = assets
        //Continue handle images which in the assets.
    }

    self.presentViewController(pickerController, animated: true) {}
}


问:
how to read some data from particular url in android
how to read some data from particular url  in android</p>

答:
```
Try this code in your file:

USE
url = "your url name+filename.jpg,mp3,etc..."
FileName = "/sdcard/savefilename"

try{
            java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL(url).openStream());
            java.io.FileOutputStream fos = new java.io.FileOutputStream(FileName);
            java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
            byte[] data = new byte[1024];
            int x=0;
            while((x=in.read(data,0,1024))>=0){
                bout.write(data,0,x);
            }
            fos.flush();
            bout.flush();
            fos.close();
            bout.close();
            in.close();
      }
        catch (Exception ex)
        {
         }
```