问:
Performance issue using mediumtext causing slow page speed
I've been analysing my website's performance using Google PageSpeed Insights, and the main issue it's reporting is slow server response times, which seem to average around 1.5 - 2 seconds. Google recommend trying to achieve 200ms, so I'm way off.

What I've established is that the queries to retrieve the data from the database are causing quite significant performance issues.  My website makes extensive use of caching to retrieve the sections of the website. The entire webpage can usually be generated from 5 database queries from the cache table.

When I hard-code my return value to this (note the 'This is a test' selection):

```<code>$sql = "SELECT 'This is a test'
        FROM cache
        WHERE url = ?
         AND language = ?
         AND currency = ?";
$stmt = $conn->prepare($sql);
if (!$stmt) {
    ThrowDBError($conn, $stmt, $sql);
}
$stmt->bind_param('sss', $url, $language, $currency);
if (!$stmt->execute()) {
    ThrowDBError($conn, $stmt, $sql);
}
$stmt->bind_result($cache);
$stmt->fetch();
$stmt->close();
</code>```

The server response speed drops to 0.5 seconds.  When I put it back to select the actual data column page_body, like this:

```<code>$sql = "SELECT page_body
        FROM cache_copy
        WHERE url = ?
         AND language = ?
         AND currency = ?";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    ThrowDBError($conn, $stmt, $sql);
}
$stmt->bind_param('sss', $url, $language, $currency);
if (!$stmt->execute()) {
    ThrowDBError($conn, $stmt, $sql);
}
$stmt->bind_result($cache);
$stmt->fetch();
$stmt->close();
</code>```

The the server response time jumps consistently to 1.5 - 2 seconds for the 5 queries the website makes to the cache table.

The cache table only contains 8,000 rows and I think I've correctly indexed it. The column page_body is a mediumtext - does anyone know of performance-related issues using mediumtext?  I just can't figure why it would add 1.5 seconds to the load time.

Here is the DDL for the cache table:

```<code>CREATE TABLE `cache` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `url` varchar(255) NOT NULL,
  `language` varchar(2) NOT NULL,
  `currency` varchar(3) NOT NULL,
  `page_body` mediumtext NOT NULL,
  `cached_time` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `url, language, currency` (`url`,`language`,`currency`) USING BTREE,
  KEY `cached_time` (`cached_time`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
</code>```

Any ideas?
Many thanks

答:
How many rows does it return?  If it returning only 1 row, it should be well under 200ms.

Oh!  Is see the problem.  You are using MyISAM.  Don't.  Switch to InnoDB.

If the real table is like cache, you will get virtually the same speed from it.  I suggest your get rid of the cache.

Body:
I've been analysing my website's performance using Google PageSpeed Insights, and the main issue it's reporting is slow server response times, which seem to average around 1.5 - 2 seconds. Google recommend trying to achieve 200ms, so I'm way off.

What I've established is that the queries to retrieve the data from the database are causing quite significant performance issues.  My website makes extensive use of caching to retrieve the sections of the website. The entire webpage can usually be generated from 5 database queries from the cache table.

When I hard-code my return value to this (note the 'This is a test' selection):

$sql = "SELECT 'This is a test'
        FROM cache
        WHERE url = ?
         AND language = ?
         AND currency = ?";
$stmt = $conn->prepare($sql);
if (!$stmt) {
    ThrowDBError($conn, $stmt, $sql);
}
$stmt->bind_param('sss', $url, $language, $currency);
if (!$stmt->execute()) {
    ThrowDBError($conn, $stmt, $sql);
}
$stmt->bind_result($cache);
$stmt->fetch();
$stmt->close();

The server response speed drops to 0.5 seconds.  When I put it back to select the actual data column page_body, like this:

$sql = "SELECT page_body
        FROM cache_copy
        WHERE url = ?
         AND language = ?
         AND currency = ?";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    ThrowDBError($conn, $stmt, $sql);
}
$stmt->bind_param('sss', $url, $language, $currency);
if (!$stmt->execute()) {
    ThrowDBError($conn, $stmt, $sql);
}
$stmt->bind_result($cache);
$stmt->fetch();
$stmt->close();

The the server response time jumps consistently to 1.5 - 2 seconds for the 5 queries the website makes to the cache table.

The cache table only contains 8,000 rows and I think I've correctly indexed it. The column page_body is a mediumtext - does anyone know of performance-related issues using mediumtext?  I just can't figure why it would add 1.5 seconds to the load time.

Here is the DDL for the cache table:

CREATE TABLE `cache` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `url` varchar(255) NOT NULL,
  `language` varchar(2) NOT NULL,
  `currency` varchar(3) NOT NULL,
  `page_body` mediumtext NOT NULL,
  `cached_time` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `url, language, currency` (`url`,`language`,`currency`) USING BTREE,
  KEY `cached_time` (`cached_time`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Any ideas?
Many thanks


来源: stackexchange

问:
SNMP agent in c#
I am looking for various solutions for creating SNMP agent in c#. I found several companies that offer some products, but most of them use their own server. However, I found one solution that uses an agent extension.

Two questions:

Does anyone know other solutions in c# that use the framework of the SNMP service and create an extension agent?

Does someone knows about a tool that convert mib files to C# classes?

答:
If you plan to write extension to Microsoft SNMP agent, it may not support C# assemblies,

CodeProject article on this

If in fact you try to extend another SNMP agent, of course you should go to its vendor for assistance. Only the MIB to C# convertor provided by this vendor can be used to develop extensions for that agent.

ContentLicense: CC BY-SA 2.5

Title: SNMP agent in c#


问:
"as string" versus toString()
I am writing some unit tests using jasmine. If I use:

```<code>let arg0 : string = http.put.calls.argsFor(0) as string;
if(arg0.search(...
</code>```

then I get the error arg0.search is not a function. Intellisense shows that arg0 is an array and not a string as expected. If I instead use:

```<code>let arg0 : string = http.put.calls.argsFor(0).toString();
if(arg0.search(...
</code>```

it works. Intellisense shows that the argsFor function signature has any as the return type. When called it returns an array.

Why does the "as string" version not work and why am I not getting a compile error given arg0 in that case ends up holding an array instead of a string?

答:
as string is a TypeScript construct, as it is removed when compiled so javascript doesn't even know about it.

toString() is a JavaScript method that actually takes what is returned in the previous method and converts it to a string. This isn't removed at compile time.

ContentLicense: CC BY-SA 3.0

Title: "as string" versus toString()

Body:
I am writing some unit tests using jasmine. If I use:

let arg0 : string = http.put.calls.argsFor(0) as string;
if(arg0.search(...

then I get the error arg0.search is not a function. Intellisense shows that arg0 is an array and not a string as expected. If I instead use:

let arg0 : string = http.put.calls.argsFor(0).toString();
if(arg0.search(...

it works. Intellisense shows that the argsFor function signature has any as the return type. When called it returns an array.

Why does the "as string" version not work and why am I not getting a compile error given arg0 in that case ends up holding an array instead of a string?


问:
Does Google Pub/Sub feature have some of capability to notify a Google App Engine endpoint directly after an upload?
I am looking at the documentation for Google Pub/Sub ( https://cloud.google.com/storage/docs/pubsub-notifications ) and I don't see a way for Pub/Sub to make a RESTful call to a Google App Engine endpoint when a new file has been uploaded to a bucket.

Is this correct, or did I miss something?

It says in the documentation that there is an older way to probably accomplish this : https://cloud.google.com/storage/docs/object-change-notification . But I am not sure if it is a good idea to use something that might be deprecated down the line?

Thanks

答:
GCS's Cloud Pub/Sub support works well for this case.

First, create a Cloud Pub/Sub topic and configure your GCS bucket to send it OBJECT_FINALIZE messages. You can do so like this:

```<code>$> gsutil notification create -f json \
       -t newTopicName \
       -e OBJECT_FINALIZE \
       gs://bucketName
</code>```

Next, add a Cloud Pub/Sub subscription to your Cloud Pub/Sub topic which pushes notifications to your App Engine endpoint. You can do this in the UI, or you can run a command like this:

```<code>$> gcloud alpha pubsub subscriptions create subscriptionName \
        --topic newTopicName \
        --push-endpoint https://myapp.appspot.com/_ah/push_handlers/myHandler
</code>```

Finally, configure your app engine app to handle incoming push events at that URL. You can read more about this approach in Cloud Pub/Sub's documentation: https://cloud.google.com/pubsub/docs/push#app-engine-standard-endpoints

Body:
GCS's Cloud Pub/Sub support works well for this case.

First, create a Cloud Pub/Sub topic and configure your GCS bucket to send it OBJECT_FINALIZE messages. You can do so like this:

$> gsutil notification create -f json \
       -t newTopicName \
       -e OBJECT_FINALIZE \
       gs://bucketName

Next, add a Cloud Pub/Sub subscription to your Cloud Pub/Sub topic which pushes notifications to your App Engine endpoint. You can do this in the UI, or you can run a command like this:

$> gcloud alpha pubsub subscriptions create subscriptionName \
        --topic newTopicName \
        --push-endpoint https://myapp.appspot.com/_ah/push_handlers/myHandler

Finally, configure your app engine app to handle incoming push events at that URL. You can read more about this approach in Cloud Pub/Sub's documentation: https://cloud.google.com/pubsub/docs/push#app-engine-standard-endpoints


问:
Azure machine learning webservice deployment failed
Deployment error to ACS - BadRequestFormat. How do I get past this? This is my nth attempt to make the tutorial work end to end https://learn.microsoft.com/en-us/azure/machine-learning/preview/tutorial-classifying-iris-part-1.

az ml env setup -n gopenv --location westcentralus -c

Subscription set to Visual Studio Premium with MSDN

Continue with this subscription (Y/n)? y

Resource group gopenvrg already exists, skipping creation.

creating service principal.........done

Created a service principal: %s 96f6dd9e-c9d6-4856-9f8b-5426c7a757ea

waiting for AAD role to propagate.done

Provisioning compute resources...

BadRequestFormat: The request format was invalid. Details: Updating clusters with cluster type Local is not supported

答:
I got the same error when I ran the command again after it had already run successfully once. Considering that your output says, "Resource group gopenvrg already exists", it looks like that might be true for you too.

If you change "-n gopenv" to something else like "-n gopenv2", it might work for you. It did for me.

You can see if you already have any deployment environments by running "az ml env list".


问:
Database update using wpDataTables plugin
I am creating a database application containing information about all the banks in Germany. I'm using phpmyadmin for the back end and wordpress for the front end. I am planning to install wpDataTables plugin to be able to display tables from my MySQL database on my web page. Is it possible to insert into/update my database from the front end using this plugin? Is it possible to make the entires in the table clickable (so that on clicking the entry, it goes to another page containing details about that entry)?
P.S. I am new to web development and wordpress and it would be great to get some help to solve this problem. Thank you. </p>

答:
It is possible to make wpDataTables created from MySQL query editable. You can take a look at their documentation page at this link. There is a limitation if you are using JOIN in MySQL query and tables like this can't be editable.

Only one MySQL table can be edited at a time. Queries from multiple tables with joins cannot be used for editable feature, since SQL UPDATE and INSERT statements are generated automatically, and for now there is no way to update multiple tables – but we are working on this.

With built-in features it is not possible to create clickable rows. Something like that would probably require some custom coding.


问:
BMI in Python with file input
I have an assignment which I can't get through. I'm a beginner at programming and I want to understand it better for my course. Can someone help me? I really don't understand it.

This is the assignment:

The BMI is defined as weight/length2. A BMI between 18,5 and 25 as ideal and considers people with such a BMI healthy.
The program receives input consisting of two persons with their name, sex, length and weight.

```<code>    Jack Johnson M 1.78 83
    Maria Miller V 1.69 60
</code>```

Process this input into structured data. To achieve this, use an useful class with useful methods to enhance the structure of the program. Use this structured data to print for each person: an appropriate style of address, surname, the BMI and a statement whether this is considered healthy or not.

Example:

```<code>    Mr. Johnson’s BMI is 26.2 and is unhealthy.
    Mrs. Miller’s BMI is 21.0 and is healthy.
</code>```

This is what I have:

```<code>    class Person(object):
        def __init__(self):
            self.first_name = first_name
            self.last_name = last_name
            self.sex = sex
            self.length = length    #m
            self.weight = weight    #kg

        def bmi(self):
            return self.weight / self.length ** 2

        def healthy(self):
            if BODYMASSINDEX <25 and BODYMASSINDEX>18.5:
                person = healthy
            else:
                person = unhealthy
            return person
</code>```

```<code>    from person import Person

    file = open("BMIInput.txt")
    invoer = file.read().splitlines()
    details_person1 = invoer[0].split()
    details_person2 = invoer[1].split()

    person1 = Person(details_person1)
    person2 = Person(details_person2)

    print "%s's BMI is %.1f and is %s" %(person1.name, person1.bmi, person1.healthy)
</code>```

The BMI Input is:

```<code>    Jack Johnson    M   1.78    83
    Maria Miller    V   1.69    60
</code>```

答:
Add the arguments to the init

```<code>    class Person(object):
        def __init__(self, first_name, last_name, sex, length, weight):
            self.first_name = first_name
            self.last_name = last_name
            self.sex = sex
            self.length = length    #m
            self.weight = weight    #kg

        def bmi(self):
            return self.weight / self.length ** 2

        def healthy(self):
            if BODYMASSINDEX <25 and BODYMASSINDEX>18.5:
                person = healthy
            else:
                person = unhealthy
            return person
</code>```

Then unpack the list:

```<code>from person import Person

file = open("BMIInput.txt")
invoer = file.read().splitlines()
details_person1 = invoer[0].split()
details_person2 = invoer[1].split()

person1 = Person(*details_person1)
person2 = Person(*details_person2)

print "%s's BMI is %.1f and is %s" %(person1.name, person1.bmi, person1.healthy)
</code>```

Comment question about int, float is more what you need:

Just to solve the issue this is not clean nor the right way but it will work:
Inside the init

```<code>self.length = float(length) if type(length) != float else length
self.weight = float(weight) if type(weight) != float else weight
</code>```

What I'd do is :

```<code>details_person1 = invoer[0].split()
details_person1[3] = float(details_person1[3])
details_person1[4] = float(details_person1[4])
</code>```

The same thing with details_person2

Title: BMI in Python with file input

Body:
I have an assignment which I can't get through. I'm a beginner at programming and I want to understand it better for my course. Can someone help me? I really don't understand it.

This is the assignment:

The BMI is defined as weight/length2. A BMI between 18,5 and 25 as ideal and considers people with such a BMI healthy.
The program receives input consisting of two persons with their name, sex, length and weight.

    Jack Johnson M 1.78 83
    Maria Miller V 1.69 60

Process this input into structured data. To achieve this, use an useful class with useful methods to enhance the structure of the program. Use this structured data to print for each person: an appropriate style of address, surname, the BMI and a statement whether this is considered healthy or not.

Example:

    Mr. Johnson’s BMI is 26.2 and is unhealthy.
    Mrs. Miller’s BMI is 21.0 and is healthy.

This is what I have:

    class Person(object):
        def __init__(self):
            self.first_name = first_name
            self.last_name = last_name
            self.sex = sex
            self.length = length    #m
            self.weight = weight    #kg

        def bmi(self):
            return self.weight / self.length ** 2

        def healthy(self):
            if BODYMASSINDEX <25 and BODYMASSINDEX>18.5:
                person = healthy
            else:
                person = unhealthy
            return person

    from person import Person

    file = open("BMIInput.txt")
    invoer = file.read().splitlines()
    details_person1 = invoer[0].split()
    details_person2 = invoer[1].split()

    person1 = Person(details_person1)
    person2 = Person(details_person2)

    print "%s's BMI is %.1f and is %s" %(person1.name, person1.bmi, person1.healthy)

The BMI Input is:

    Jack Johnson    M   1.78    83
    Maria Miller    V   1.69    60

Body:
Add the arguments to the init

    class Person(object):
        def __init__(self, first_name, last_name, sex, length, weight):
            self.first_name = first_name
            self.last_name = last_name
            self.sex = sex
            self.length = length    #m
            self.weight = weight    #kg

        def bmi(self):
            return self.weight / self.length ** 2

        def healthy(self):
            if BODYMASSINDEX <25 and BODYMASSINDEX>18.5:
                person = healthy
            else:
                person = unhealthy
            return person

Then unpack the list:

from person import Person

file = open("BMIInput.txt")
invoer = file.read().splitlines()
details_person1 = invoer[0].split()
details_person2 = invoer[1].split()

person1 = Person(*details_person1)
person2 = Person(*details_person2)

print "%s's BMI is %.1f and is %s" %(person1.name, person1.bmi, person1.healthy)

Comment question about int, float is more what you need:

Just to solve the issue this is not clean nor the right way but it will work:
Inside the init

self.length = float(length) if type(length) != float else length
self.weight = float(weight) if type(weight) != float else weight

What I'd do is :

details_person1 = invoer[0].split()
details_person1[3] = float(details_person1[3])
details_person1[4] = float(details_person1[4])

The same thing with details_person2


问:
Python: Writing Values to Table In MSSQL Server
I currently have a connection successfully established with a Database in MSSQL Server.

Below is my code (login credentials removed).

```<code>import pypyodbc

    connection = pypyodbc.connect('Driver={XXX};'
                                  'Server=XXX;'
                                  'Database=XXX;'
                                  'uid=XXX;'
                                  'pwd=XXX')

    cursor = connection.cursor()
</code>```

Below is what I'm trying to insert into SQL table:

```<code>cursor.execute("INSERT INTO MODREPORT(rowid, location) VALUES (?,?)", (3, 'fleet'))
connection.commit

connection.close()
</code>```

After running the execute code the following appears:

```<code><bound method Connection.commit of <pypyodbc.Connection object at 0x0000000009CB88D0>>
</code>```

BUT nothing is written into the SQL table

答:
You need to call connection.commit() as a function, not just reference the bound method.

```<code>cursor.execute("INSERT INTO MODREPORT(rowid, location) VALUES (?,?)", (3, 'fleet'))
connection.commit()
connection.close()
</code>```

Body:
I currently have a connection successfully established with a Database in MSSQL Server.

Below is my code (login credentials removed).

import pypyodbc

    connection = pypyodbc.connect('Driver={XXX};'
                                  'Server=XXX;'
                                  'Database=XXX;'
                                  'uid=XXX;'
                                  'pwd=XXX')

    cursor = connection.cursor()

Below is what I'm trying to insert into SQL table:

cursor.execute("INSERT INTO MODREPORT(rowid, location) VALUES (?,?)", (3, 'fleet'))
connection.commit

connection.close()

After running the execute code the following appears:

<bound method Connection.commit of <pypyodbc.Connection object at 0x0000000009CB88D0>>

BUT nothing is written into the SQL table

Body:
You need to call connection.commit() as a function, not just reference the bound method.

cursor.execute("INSERT INTO MODREPORT(rowid, location) VALUES (?,?)", (3, 'fleet'))
connection.commit()
connection.close()


问:
Spatial nearest neighbor assignment in R

I am working on a study that is trying to assign particulate matter exposure to specific individuals based on their addresses. I have two data sets with longitude and latitude coordinates. One if for individuals and one if for pm exposure blocks. I want to assign each subject with a pm exposure block based on the block that is closest.

```<code>library(sp)
library(raster)
library(tidyverse)

#subject level data
subjectID<-c("A1","A2","A3","A4")

subjects<-data.frame(tribble(
~lon,~lat,
-70.9821391,    42.3769511,
-61.8668537,    45.5267133,
-70.9344039,    41.6220337,
-70.7283830,    41.7123494
))

row.names(subjects)<-subjectID

#PM Block Locations
blockID<-c("B1","B2","B3","B4","B5")

blocks<-data.frame(tribble(
~lon,~lat,
-70.9824591,    42.3769451,
-61.8664537,    45.5267453,
-70.9344539,    41.6220457,
-70.7284530,    41.7123454,
-70.7284430,    41.7193454
))

row.names(blocks)<-blockID

#Creating distance matrix
dis_matrix<-pointDistance(blocks,subjects,lonlat = TRUE)

###The above code doesnt preserve the row names. Is there a way to to do
that?

###I'm unsure about the below code
colnames(dis_matrix)<-row.names(subjects)
row.names(dis_matrix)<-row.names(blocks)

dis_data<-data.frame(dis_matrix)

###Finding nearst neighbor and coercing to usable format
getname <-function(x) {
row.names(dis_data[which.min(x),])
}

nn<-data.frame(lapply(dis_data,getname)) %>%
gather(key=subject,value=neighbor)
</code>```

This code gives me output that makes sense but I'm unsure of the validity and efficiency. Any suggestion on how to improve and fix this code are appreciated. I also receive the error message:

```<code>Warning message:
attributes are not identical across measure variables;
they will be dropped
</code>```

Which I can't determine the origin of.

Thanks for taking a look!

答:
Here is, with some example data, how you can use pointDistance:

```<code>library(raster)

#subject level data
subjectID <- c("A1","A2","A3","A4")
subxy <- matrix(c(-65, 42, -60, 4.5, -70, 20, -75, 41 ), ncol=2, byrow=TRUE)
#PM Block Locations
blockID <- c("B1","B2","B3","B4","B5")
blockxy <- matrix(c(-68, 22, -61, 25, -70, 31, -65, 11,-63, 21), ncol=2, byrow=TRUE)

# distance of all subxy to all blockxy points
d <- pointDistance(subxy, blockxy, lonlat=TRUE)

# get the blockxy record nearest to each subxy record
r <- apply(d, 1, which.min)
r
#[1] 3 4 1 3
</code>```

So the pairs are:

```<code>p <- data.frame(subject=subjectID, block=blockID[r])
p

#  subject block
#1      A1    B3
#2      A2    B4
#3      A3    B1
#4      A4    B3
</code>```

Illustrate that it works:

```<code>plot(rbind(blockxy, subxy), ylim=c(0,45), xlab='longitude', ylab='latitude')
points(blockxy, col="red", pch=20, cex=2)
points(subxy, col="blue", pch=20, cex=2)
text(subxy, subjectID, pos=1)
text(blockxy, blockID, pos=1)
for (i in 1:nrow(subxy)) {
    arrows(subxy[i,1], subxy[i,2], blockxy[r[i],1], blockxy[r[i],2])
}
</code>```

Body:
I am working on a study that is trying to assign particulate matter exposure to specific individuals based on their addresses. I have two data sets with longitude and latitude coordinates. One if for individuals and one if for pm exposure blocks. I want to assign each subject with a pm exposure block based on the block that is closest.

library(sp)
library(raster)
library(tidyverse)

#subject level data
subjectID<-c("A1","A2","A3","A4")

subjects<-data.frame(tribble(
~lon,~lat,
-70.9821391,    42.3769511,
-61.8668537,    45.5267133,
-70.9344039,    41.6220337,
-70.7283830,    41.7123494
))

row.names(subjects)<-subjectID

#PM Block Locations
blockID<-c("B1","B2","B3","B4","B5")

blocks<-data.frame(tribble(
~lon,~lat,
-70.9824591,    42.3769451,
-61.8664537,    45.5267453,
-70.9344539,    41.6220457,
-70.7284530,    41.7123454,
-70.7284430,    41.7193454
))

row.names(blocks)<-blockID

#Creating distance matrix
dis_matrix<-pointDistance(blocks,subjects,lonlat = TRUE)

###The above code doesnt preserve the row names. Is there a way to to do
that?

###I'm unsure about the below code
colnames(dis_matrix)<-row.names(subjects)
row.names(dis_matrix)<-row.names(blocks)

dis_data<-data.frame(dis_matrix)

###Finding nearst neighbor and coercing to usable format
getname <-function(x) {
row.names(dis_data[which.min(x),])
}

nn<-data.frame(lapply(dis_data,getname)) %>%
gather(key=subject,value=neighbor)

This code gives me output that makes sense but I'm unsure of the validity and efficiency. Any suggestion on how to improve and fix this code are appreciated. I also receive the error message:

Warning message:
attributes are not identical across measure variables;
they will be dropped

Which I can't determine the origin of.

Thanks for taking a look!

Body:
Here is, with some example data, how you can use pointDistance:

library(raster)

#subject level data
subjectID <- c("A1","A2","A3","A4")
subxy <- matrix(c(-65, 42, -60, 4.5, -70, 20, -75, 41 ), ncol=2, byrow=TRUE)
#PM Block Locations
blockID <- c("B1","B2","B3","B4","B5")
blockxy <- matrix(c(-68, 22, -61, 25, -70, 31, -65, 11,-63, 21), ncol=2, byrow=TRUE)

# distance of all subxy to all blockxy points
d <- pointDistance(subxy, blockxy, lonlat=TRUE)

# get the blockxy record nearest to each subxy record
r <- apply(d, 1, which.min)
r
#[1] 3 4 1 3

So the pairs are:

p <- data.frame(subject=subjectID, block=blockID[r])
p

#  subject block
#1      A1    B3
#2      A2    B4
#3      A3    B1
#4      A4    B3

Illustrate that it works:

plot(rbind(blockxy, subxy), ylim=c(0,45), xlab='longitude', ylab='latitude')
points(blockxy, col="red", pch=20, cex=2)
points(subxy, col="blue", pch=20, cex=2)
text(subxy, subjectID, pos=1)
text(blockxy, blockID, pos=1)
for (i in 1:nrow(subxy)) {
    arrows(subxy[i,1], subxy[i,2], blockxy[r[i],1], blockxy[r[i],2])
}


问:
How to check in Z3py whether the expression contains a conditional (=>)
i'm using Z3py to traverse a Boolean formula. How to check whether the    formula contains a conditional. I have checked the z3.py source code and it contains is_and(), is_or(), is_not(),.. but nothing related to is_implies(). Any idea ? Thanks.

答:
You can use the function "is_app_of" to determine the built-in function of an expression. Thus,

```<code>def is_and(a):
    return is_app_of(a, Z3_OP_AND)
</code>```

as already implemented in the z3.py file, and similarly

```<code>def is_implies(a):
    return is_app_of(a, Z3_OP_IMPLIES)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can use the function "is_app_of" to determine the built-in function of an expression. Thus,

def is_and(a):
    return is_app_of(a, Z3_OP_AND)

as already implemented in the z3.py file, and similarly

def is_implies(a):
    return is_app_of(a, Z3_OP_IMPLIES)


问:
How to change locale to use Latin Serbian (instead of Cyrillic Serbian)
The Serbian language has Latin and Cyrillic alphabets. In Android's Date and Time Picker widgets, the displayed alphabet for Serbian locales seems to be Cyrillic, as seen here.

I wanted to change the locale so that the android widgets are using the Latin Serbian alphabet.

The current language/country code (yielding Cyrillic) are sr and RS respectively. Therefore, my setLocale function is called as

```<code>setLocale("sr", "RS");
</code>```

This is the part im not sure about - according to localeplanet.com, the local code for latin serbian is sr_Latn_RS. However, I tried both

```<code>setLocale("sr_Latn", "RS");
//and
setLocale("sr_Latn_RS", "RS");
</code>```

neither of which work (no change occurs, default to english). According to the Android documentation, it looks like setLocale expects two letter codes.

The language codes are two-letter lowercase ISO language codes (such
  as "en") as defined by ISO 639-1. The country codes are two-letter
  uppercase ISO country codes (such as "US") as defined by ISO 3166-1.
  The variant codes are unspecified.

So how do I specify a Latin serbian locale code? Or does it not exist?

答:
The previous answer works well if you only support Lollipop or above. However, if you're coding in Serbian a lot of your user base probably won't have it. Here's a solution that works for old and new versions.</p>

```<code>private static Locale serbianLatinLocale(){

    Locale locale = null;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        for (Locale checkLocale : Locale.getAvailableLocales()) {
            if (checkLocale.getISO3Language().equals("srp") && checkLocale.getCountry().equals("LATN") && checkLocale.getVariant().equals("")) {
                locale = checkLocale;
            }
        }
    } else {
        locale = new Locale.Builder().setLanguage("sr").setRegion("RS").setScript("Latn").build();
    }

    return locale;
}
</code>```

Body:
The Serbian language has Latin and Cyrillic alphabets. In Android's Date and Time Picker widgets, the displayed alphabet for Serbian locales seems to be Cyrillic, as seen here.

I wanted to change the locale so that the android widgets are using the Latin Serbian alphabet.

The current language/country code (yielding Cyrillic) are sr and RS respectively. Therefore, my setLocale function is called as

setLocale("sr", "RS");

This is the part im not sure about - according to localeplanet.com, the local code for latin serbian is sr_Latn_RS. However, I tried both

setLocale("sr_Latn", "RS");
//and
setLocale("sr_Latn_RS", "RS");

neither of which work (no change occurs, default to english). According to the Android documentation, it looks like setLocale expects two letter codes.

The language codes are two-letter lowercase ISO language codes (such
  as "en") as defined by ISO 639-1. The country codes are two-letter
  uppercase ISO country codes (such as "US") as defined by ISO 3166-1.
  The variant codes are unspecified.

So how do I specify a Latin serbian locale code? Or does it not exist?

Body:
The previous answer works well if you only support Lollipop or above. However, if you're coding in Serbian a lot of your user base probably won't have it. Here's a solution that works for old and new versions.

private static Locale serbianLatinLocale(){

    Locale locale = null;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        for (Locale checkLocale : Locale.getAvailableLocales()) {
            if (checkLocale.getISO3Language().equals("srp") && checkLocale.getCountry().equals("LATN") && checkLocale.getVariant().equals("")) {
                locale = checkLocale;
            }
        }
    } else {
        locale = new Locale.Builder().setLanguage("sr").setRegion("RS").setScript("Latn").build();
    }

    return locale;
}


问:
Simple python script is not printing output
This code doesn't print an output:

```<code>x = 1500000
y = 0

while (x>0):
    x=(x * 1.1) - 20000
    y = y+1
else:
    print (y)
</code>```

How would one fix this problem?

答:
See this lovely debug blog for help.  Most of all, learn to use a print to trace the problem, or desk-check the program (simulate with paper & pencil).

Look at your very first iteration:

```<code>x = 1500000
y = 0

while (x>0):
    x=(x * 1.1) - 20000
</code>```

Evaluate this line:

```<code>x = (1500000 * 1.1) - 20000
x = 1650000 - 20000
x = 1630000
</code>```

x is now larger than before.  It will continue to escalate without bound.  You never reach your while's exit condition, so you never reach the print statement.

Body:
This code doesn't print an output:

x = 1500000
y = 0

while (x>0):
    x=(x * 1.1) - 20000
    y = y+1
else:
    print (y)

How would one fix this problem?

Body:
See this lovely debug blog for help.  Most of all, learn to use a print to trace the problem, or desk-check the program (simulate with paper & pencil).

Look at your very first iteration:

x = 1500000
y = 0

while (x>0):
    x=(x * 1.1) - 20000

Evaluate this line:

x = (1500000 * 1.1) - 20000
x = 1650000 - 20000
x = 1630000

x is now larger than before.  It will continue to escalate without bound.  You never reach your while's exit condition, so you never reach the print statement.


问:
Session Hijacking in Django 1.7.7 and python3
I have developed a small application for submitting some data to database server(Oracle 11g). When we are reviewing security of this small application, we observed as follows:

```<code>1. We have deployed django with https and all secure configurations like Secure Cookie and Secure Session, No Cache, etc.
2. Using BURP tool for this sample review
3. We have created two different user in this system say Normal User and Admin User
4. Opened 2 browsers(Mozilla and IE 11), On mozilla we login with Admin user and captured session id using burp tool.
5. On second browser we login with Normal user and replaced session id Normal User with Admin User.
6. whoila......On second browser, I got Admin user access by just changing the session id
</code>```

I have used default session backend for this application.

I would like to know whether this is flaw in django and how to resolve this issue..

Thanks in advance

答:
This is an inherent risk of using session-based identification. It's called session hijacking, and if you search for that term you will find lots of information.

Mitigations generally have one of two goals: making it harder to steal the token, or making the damage less severe if it is stolen. In the former camp are techniques like using HTTPS and SESSION_COOKIE_HTTPONLY. In the latter are things like limiting the length of a valid session (SESSION_COOKIE_AGE). In the end, though, it's difficult or impossible to stop someone from impersonating another user if they get their token, since that's the very thing that establishes identity.

Body:
I have developed a small application for submitting some data to database server(Oracle 11g). When we are reviewing security of this small application, we observed as follows:

1. We have deployed django with https and all secure configurations like Secure Cookie and Secure Session, No Cache, etc.
2. Using BURP tool for this sample review
3. We have created two different user in this system say Normal User and Admin User
4. Opened 2 browsers(Mozilla and IE 11), On mozilla we login with Admin user and captured session id using burp tool.
5. On second browser we login with Normal user and replaced session id Normal User with Admin User.
6. whoila......On second browser, I got Admin user access by just changing the session id

I have used default session backend for this application.

I would like to know whether this is flaw in django and how to resolve this issue..

Thanks in advance


问:
Which Job inserted this record / row into the table?
I have dozens of different SQL Jobs calling different Sprocs, which insert rows into a common table.

Is there any way, given a row in the table, to retrieve the job which triggered the insert?

Input: Row ID, TableName, DBName

Output: Job ID which inserted Row

答: Not generally, as far as I'm aware.  You could have the insert query include that data.  Or you could get it from a log, maybe based on the primary key or another unique key, if your inserts are unique.  You might be able to turn on some SQL server equivalent of the general log; but that's devastating to high volume performance and you'd still have to pull it from a log file.  I recommend you consider whether you can diagnose your components from their logs in addition to their effects in the database.</p>


问:
HTML inside PHP file not loading external CSS file
I haven't coded for a long time and my skills are basic.
I got a php file. It's a section file from a wordpress theme i am customizing.

My problem is. Made the code to link to an external css file to customize the social media icons, but it's not loading the CSS!

Here's the code:

```<code><!DOCTYPE html>
<html lang = "en-US">
 <head>
 <meta charset = "UTF-8">
<link rel="stylesheet" type="text/css" href="D:\xampp\htdocs\alfasteel.pt\wp-content\themes\onetone\css\socialmedia.css" />
 </head>
 <body>

          <div class="footer-social-icons">
    <h4 class="_14">Follow us on</h4>
    <ul class="social-icons">
        <li><a href="" class="social-icon"> <i class="fa fa-facebook"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-twitter"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-rss"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-youtube"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-linkedin"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-google-plus"></i></a></li>
    </ul>
</div>
</code>```

Here's the whole file code in case you need it:

```<code><!DOCTYPE html>
<html lang = "en-US">
 <head>
 <meta charset = "UTF-8">
<link rel="stylesheet" type="text/css" href="D:\xampp\htdocs\alfasteel.pt\wp-content\themes\onetone\css\socialmedia.css" />
 </head>
 <body>

<?php
 global $onetone_animated, $onetone_section_id, $allowedposttags;
 $i                   = $onetone_section_id ;
 $section_title       = onetone_option( 'section_title_'.$i );
 $section_menu        = onetone_option( 'menu_title_'.$i );
 $section_content     = onetone_option( 'section_content_'.$i );
 $content_model       = onetone_option( 'section_content_model_'.$i);
 $section_subtitle    = onetone_option( 'section_subtitle_'.$i );
 $left_content        = onetone_option( 'section_left_content_'.$i );
 $right_content       = onetone_option( 'section_right_content_'.$i );

 if( !isset($section_content) || $section_content=="" )
    $section_content = onetone_option( 'sction_content_'.$i );

        if( $content_model == '0' || $content_model == ''  ):
        ?>

         <?php if( $section_title != '' || (function_exists('is_customize_preview') && is_customize_preview()) ):?>
       <?php
           $section_title_class = '';
           if( $section_subtitle == '' && !(function_exists('is_customize_preview') && is_customize_preview()))
           $section_title_class = 'no-subtitle';
        ?>
       <h2 class="section-title <?php echo esc_attr($section_title_class); ?> <?php echo 'section_title_'.$i;?>"><?php echo wp_kses($section_title, $allowedposttags);?></h2>
        <?php endif;?>
        <?php if( $section_subtitle != '' || (function_exists('is_customize_preview') && is_customize_preview()) ):?>
        <div class="section-subtitle <?php echo 'section_subtitle_'.$i;?>"><?php echo do_shortcode(wp_kses($section_subtitle, $allowedposttags));?></div>
         <?php endif;?>
         <div class="home-section-content">

          <div class="footer-social-icons">
    <h4 class="_14">Follow us on</h4>
    <ul class="social-icons">
        <li><a href="" class="social-icon"> <i class="fa fa-facebook"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-twitter"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-rss"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-youtube"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-linkedin"></i></a></li>
        <li><a href="" class="social-icon"> <i class="fa fa-google-plus"></i></a></li>
    </ul>
</div>

         <div class="row">
         <div class="col-md-8"><div class="<?php echo $onetone_animated;?> <?php echo 'section_left_content_'.$i;?>" data-animationduration="0.9" data-animationtype="fadeInLeft" data-imageanimation="no"><?php echo do_shortcode($left_content);?></div></div>
         <div class="col-md-4"><div class="<?php echo $onetone_animated;?> <?php echo 'section_right_content_'.$i;?>" data-animationduration="0.9" data-animationtype="fadeInRight" data-imageanimation="no"><?php echo do_shortcode($right_content);?></div></div>
         </div>
          </div>
           <?php
        else:
        ?>
        <?php if( $section_title != '' || (function_exists('is_customize_preview') && is_customize_preview()) ):?>
        <div class="section-title <?php echo 'section_title_'.$i;?>"><?php echo esc_attr($section_title);?></div>
        <?php endif;?>

            <div class="home-section-content <?php echo 'section_content_'.$i;?>">
            <?php
            if(function_exists('Form_maker_fornt_end_main'))
             {
                 $section_content = Form_maker_fornt_end_main($section_content);
              }
             echo do_shortcode(wp_kses($section_content, $allowedposttags));
            ?>
            </div>
              <?php
        endif;
        ?>

 </body>
</html>
</code>```

答:
As @Itay Moav -Malimovka suggested

It was the path that wasn't the right way!

This works!

```<code><link rel="stylesheet" type="text/css" href="http://localhost/alfasteel.pt/wp-content/themes/onetone/css/socialmedia.css" />
</code>```

Thanks a lot for your help guys!

Body:
I haven't coded for a long time and my skills are basic.
I got a php file. It's a section file from a wordpress theme i am customizing.

My problem is. Made the code to link to an external css file to customize the social media icons, but it's not loading the CSS!

Here's the code:

<!DOCTYPE html>

 <meta charset = "UTF-8">
<link rel="stylesheet" type="text/css" href="D:\xampp\htdocs\alfasteel.pt\wp-content\themes\onetone\css\socialmedia.css" />

Follow us on

Here's the whole file code in case you need it:

<!DOCTYPE html>

 <meta charset = "UTF-8">
<link rel="stylesheet" type="text/css" href="D:\xampp\htdocs\alfasteel.pt\wp-content\themes\onetone\css\socialmedia.css" />

<?php
 global $onetone_animated, $onetone_section_id, $allowedposttags;
 $i                   = $onetone_section_id ;
 $section_title       = onetone_option( 'section_title_'.$i );
 $section_menu        = onetone_option( 'menu_title_'.$i );
 $section_content     = onetone_option( 'section_content_'.$i );
 $content_model       = onetone_option( 'section_content_model_'.$i);
 $section_subtitle    = onetone_option( 'section_subtitle_'.$i );
 $left_content        = onetone_option( 'section_left_content_'.$i );
 $right_content       = onetone_option( 'section_right_content_'.$i );

 if( !isset($section_content) || $section_content=="" )
    $section_content = onetone_option( 'sction_content_'.$i );

        if( $content_model == '0' || $content_model == ''  ):
        ?>

         <?php if( $section_title != '' || (function_exists('is_customize_preview') && is_customize_preview()) ):?>
       <?php
           $section_title_class = '';
           if( $section_subtitle == '' && !(function_exists('is_customize_preview') && is_customize_preview()))
           $section_title_class = 'no-subtitle';
        ?>
       <h2 class="section-title <?php echo esc_attr($section_title_class); ?> <?php echo 'section_title_'.$i;?>"><?php echo wp_kses($section_title, $allowedposttags);?>

        <?php endif;?>
        <?php if( $section_subtitle != '' || (function_exists('is_customize_preview') && is_customize_preview()) ):?>
        <div class="section-subtitle <?php echo 'section_subtitle_'.$i;?>"><?php echo do_shortcode(wp_kses($section_subtitle, $allowedposttags));?>

         <?php endif;?>

Follow us on

<div class="<?php echo $onetone_animated;?> <?php echo 'section_left_content_'.$i;?>" data-animationduration="0.9" data-animationtype="fadeInLeft" data-imageanimation="no"><?php echo do_shortcode($left_content);?>

<div class="<?php echo $onetone_animated;?> <?php echo 'section_right_content_'.$i;?>" data-animationduration="0.9" data-animationtype="fadeInRight" data-imageanimation="no"><?php echo do_shortcode($right_content);?>

           <?php
        else:
        ?>
        <?php if( $section_title != '' || (function_exists('is_customize_preview') && is_customize_preview()) ):?>
        <div class="section-title <?php echo 'section_title_'.$i;?>"><?php echo esc_attr($section_title);?>

        <?php endif;?>

            <div class="home-section-content <?php echo 'section_content_'.$i;?>">
            <?php
            if(function_exists('Form_maker_fornt_end_main'))
             {
                 $section_content = Form_maker_fornt_end_main($section_content);
              }
             echo do_shortcode(wp_kses($section_content, $allowedposttags));
            ?>

              <?php
        endif;
        ?>

Body:
As @Itay Moav -Malimovka suggested

It was the path that wasn't the right way!

This works!

<link rel="stylesheet" type="text/css" href="http://localhost/alfasteel.pt/wp-content/themes/onetone/css/socialmedia.css" />

Thanks a lot for your help guys!


问:
Display HTML content in UILabel
How to display html content in label.
Bellow link is how my label display html content.

https://i.stack.imgur.com/j1TKP.png

I also try using this code.

```<code>NSString * htmlString = @"<html><body> Some html string </body></html>";

NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}documentAttributes:nil error:nil];

UILabel * myLabel = [[UILabel alloc] init];
myLabel.attributedText = attrStr;
</code>```

答:
I tried your html string which was in image.I got the solution

ViewController.m

```<code>-(void)viewDidLoad
{
  [super viewDidLoad];
  // Do any additional setup after loading the view.

  NSString * htmlString = @"Description: The popular Mini Pashili holds your daily essentials. With signature side zip-pleats,this style is often worn fanned-open and cross body via detachable shoulder strap.Just pinch to open the push-lock padlock.<ul><li>100%Full Grain Leather</li><li>6.5”H x 8.5”W x 3”D</li><li>16.5”-22” Adjustable Shoulder Starp</li><li>Fully Lined</li><li>Dust Bag included</li><li>Imported</li><li>AE17-0226SKC</li></ul>";
  NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
  UILabel * myLabel = [[UILabel alloc] init];
  myLabel.frame = CGRectMake(200, 200, 350, 300);
  myLabel.numberOfLines = 4;
  myLabel.attributedText = attrStr;
  [self.view addSubview:myLabel];
}
</code>```

Now the solution is

Title: Display HTML content in UILabel

Body:
How to display html content in label.
Bellow link is how my label display html content.

https://i.stack.imgur.com/j1TKP.png

I also try using this code.

NSString * htmlString = @" Some html string ";

NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData: [htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}documentAttributes:nil error:nil];

UILabel * myLabel = [[UILabel alloc] init];
myLabel.attributedText = attrStr;

Body:
I tried your html string which was in image.I got the solution

ViewController.m

-(void)viewDidLoad
{
  [super viewDidLoad];
  // Do any additional setup after loading the view.

  NSString * htmlString = @"Description: The popular Mini Pashili holds your daily essentials. With signature side zip-pleats,this style is often worn fanned-open and cross body via detachable shoulder strap.Just pinch to open the push-lock padlock.<ul><li>100%Full Grain Leather</li><li>6.5”H x 8.5”W x 3”D</li><li>16.5”-22” Adjustable Shoulder Starp</li><li>Fully Lined</li><li>Dust Bag included</li><li>Imported</li><li>AE17-0226SKC</li></ul>";
  NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
  UILabel * myLabel = [[UILabel alloc] init];
  myLabel.frame = CGRectMake(200, 200, 350, 300);
  myLabel.numberOfLines = 4;
  myLabel.attributedText = attrStr;
  [self.view addSubview:myLabel];
}

Now the solution is


答:
Completely different things.

as String

This is a type assertion

More https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html

toString()

This is a function call

More https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

Title: "as string" versus toString()

Body:
I am writing some unit tests using jasmine. If I use:

let arg0 : string = http.put.calls.argsFor(0) as string;
if(arg0.search(...

then I get the error arg0.search is not a function. Intellisense shows that arg0 is an array and not a string as expected. If I instead use:

let arg0 : string = http.put.calls.argsFor(0).toString();
if(arg0.search(...

it works. Intellisense shows that the argsFor function signature has any as the return type. When called it returns an array.

Why does the "as string" version not work and why am I not getting a compile error given arg0 in that case ends up holding an array instead of a string?


问:
Programming Language for Berkeley Overmind Starcraft AI competition
Does anyone know which programming language the Berkeley Overmind submission to the Starcraft AI competition this past year was?</p>

答:
Given no information but the below quote, I estimate C++:</p>

```<code>The Brood War Application Programming Interface (BWAPI) is a free and open source C++ framework for creating AI modules for Starcraft: Broodwar.
</code>```

Body:
Given no information but the below quote, I estimate C++:

The Brood War Application Programming Interface (BWAPI) is a free and open source C++ framework for creating AI modules for Starcraft: Broodwar.


问:
Move and expand image to fill viewport transition
I'm building a transition where I want to scale up a thumbnail to fill the viewport on click.

Currently I got the calculations right on finding the right scale ratio based on the viewport and it's size, but I'm having problems on centring the image in the viewport after it's scaled/expanded.

I only have the problem when I'm using transform-origin: center center; and the image is centered in a fixed full screen container. Here is a jsfiddle showing my problem.

I've also made a jsfiddle showing how it is without the centering. This is close to what I want, except I want to be able to transition the image from other positions rather than the top left corner.

Here is the code I have so far

```<code>// Helper fucntions
const getWindowWidth = () => {
    return Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
}

const getWindowHeight = () => {
    return Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
}

// Get element
const El = document.getElementById('test');

// Add listener
El.addEventListener('click', () => {
    // Viewport size
    const viewH = getWindowHeight();
    const viewW = getWindowWidth();

    // El size
    const elHeight = El.offsetHeight;
    const elWidth = El.offsetWidth;

    // Scale ratio
    let scale = 1;

    // Get how much element need to scale
    // to fill viewport
    // Based on https://stackoverflow.com/a/28475234/1719789
    if ((viewW / viewH) > (elWidth / elHeight)) {
        scale = viewW / elWidth;
    } else {
        scale = viewH / elHeight;
    }

    // Center element
    const x = ((viewW - ((elWidth) * scale)) / 2);
    const y = ((viewH - ((elHeight) * scale)) / 2);

    // matrix(scaleX(),skewY(),skewX(),scaleY(),translateX(),translateY())
    El.style.transform = 'matrix(' + scale + ', 0, 0, ' + scale + ', ' + x + ', ' + y + ')';
});
</code>```

And some css:

```<code>.Container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

#El {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 50%;
  transform-origin: center center;
  transform: translate(-50%, -50%);
  transition: transform .3s ease-in-out;
}
</code>```

The best solution would be getting the current position of the clicked thumbnail (not always centered) and from that scale it to fill the screen. But I'm not really sure where to start to be able to do that.

答:
Is this the effect you are looking for?

CSS:

```<code>.Container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

#test {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 50%;
  transform: translate(-50%, -50%);
  transition: all 3.3s ease-in-out;
}

#test.rdy{
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
</code>```

JS:

```<code>// Helper fucntions
const getWindowWidth = () => {
    return Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
}
const getWindowHeight = () => {
    return Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
}

const El = document.getElementById('test');
El.addEventListener('click', () => {
    const viewH = getWindowHeight();
    const viewW = getWindowWidth();
    const elHeight = El.offsetHeight;
    const elWidth = El.offsetWidth;

    let scale = 1;

    if ((viewW / viewH) > (elWidth / elHeight)) {
        scale = viewW / elWidth;
    } else {
        scale = viewH / elHeight;
    }

    El.style.width = elWidth * scale + 'px';
    El.style.height = elHeight * scale + 'px';

    //Add .rdy class in case that position needs resetting :)
    document.getElementById('test').className += ' rdy';
});

//A hack to make height transition work :)
window.onload = function(){
    El.style.height = El.offsetHeight + 'px';
};
</code>```

Body:
I'm building a transition where I want to scale up a thumbnail to fill the viewport on click.

Currently I got the calculations right on finding the right scale ratio based on the viewport and it's size, but I'm having problems on centring the image in the viewport after it's scaled/expanded.

I only have the problem when I'm using transform-origin: center center; and the image is centered in a fixed full screen container. Here is a jsfiddle showing my problem.

I've also made a jsfiddle showing how it is without the centering. This is close to what I want, except I want to be able to transition the image from other positions rather than the top left corner.

Here is the code I have so far

// Helper fucntions
const getWindowWidth = () => {
    return Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
}

const getWindowHeight = () => {
    return Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
}

// Get element
const El = document.getElementById('test');

// Add listener
El.addEventListener('click', () => {
    // Viewport size
    const viewH = getWindowHeight();
    const viewW = getWindowWidth();

    // El size
    const elHeight = El.offsetHeight;
    const elWidth = El.offsetWidth;

    // Scale ratio
    let scale = 1;

    // Get how much element need to scale
    // to fill viewport
    // Based on https://stackoverflow.com/a/28475234/1719789
    if ((viewW / viewH) > (elWidth / elHeight)) {
        scale = viewW / elWidth;
    } else {
        scale = viewH / elHeight;
    }

    // Center element
    const x = ((viewW - ((elWidth) * scale)) / 2);
    const y = ((viewH - ((elHeight) * scale)) / 2);

    // matrix(scaleX(),skewY(),skewX(),scaleY(),translateX(),translateY())
    El.style.transform = 'matrix(' + scale + ', 0, 0, ' + scale + ', ' + x + ', ' + y + ')';
});

And some css:

.Container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

#El {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 50%;
  transform-origin: center center;
  transform: translate(-50%, -50%);
  transition: transform .3s ease-in-out;
}

The best solution would be getting the current position of the clicked thumbnail (not always centered) and from that scale it to fill the screen. But I'm not really sure where to start to be able to do that.

Body:
Is this the effect you are looking for?

CSS:

.Container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

#test {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 50%;
  transform: translate(-50%, -50%);
  transition: all 3.3s ease-in-out;
}

#test.rdy{
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

JS:

// Helper fucntions
const getWindowWidth = () => {
    return Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
}
const getWindowHeight = () => {
    return Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
}

const El = document.getElementById('test');
El.addEventListener('click', () => {
    const viewH = getWindowHeight();
    const viewW = getWindowWidth();
    const elHeight = El.offsetHeight;
    const elWidth = El.offsetWidth;

    let scale = 1;

    if ((viewW / viewH) > (elWidth / elHeight)) {
        scale = viewW / elWidth;
    } else {
        scale = viewH / elHeight;
    }

    El.style.width = elWidth * scale + 'px';
    El.style.height = elHeight * scale + 'px';

    //Add .rdy class in case that position needs resetting :)
    document.getElementById('test').className += ' rdy';
});

//A hack to make height transition work :)
window.onload = function(){
    El.style.height = El.offsetHeight + 'px';
};


问:
Can I require a user to have a True Depth camera to download my app from the App Store?
An app I want to make only makes sense with a TrueDepth camera for ARKit and augmented reality face tracking capability. Can I require a user to have a True Depth camera(iPhone X only right now) to download my app from the App Store?</p>

答:
No.

Apple's mechanism for segregating App Store listings by device capabilities does include a front-depth-camera key. However, that key is not enabled for use by third-party apps, and Apple doesn't include it in the list of device capabilities that third-party apps can use to limit App Store availability of an app. If you include that key in your app's Info.plist, it has no effect on the App Store — your app will still be offered to devices without a TrueDepth camera.

Unless/until that changes, you can't really make an app that absolutely requires the TrueDepth camera. App Store guidelines require that baseline app functionality is the same across supported devices.

Instead, treat features based on the depth camera as secondary or supplementary to your app's core feature set — for example, if you have an app that adds visual effects to selfie-cam imagery, offer ARKit-based effects on devices that support face tracking and simpler effects on devices that don't. (Check ARFaceTrackingConfiguration.isSupported to see if you're running on the right hardware.)


问:
javascript output not showing in html
I’m trying to write code that removes some special characters from any string URL and then displays the cleaned string via html.

The JavaScript works but I can’t get the result to show in the browser.

The whole point of the code is to have someone put in input and then the input is then cleaned up and the result is then inserted in “result1” and/or “result2”

So when the page loads and the user types something in “myTextarea” and clicks the button, cleanupurl(x) is supposed to run.

pls help ;(

code so far

```<code><!DOCTYPE html>
    <html>
    <head>
        <title>Clean Strings</title>
    </head>
        <body>
            <div id="display-area" >
                <textarea placeholder="insert URL here :)" id="myTextarea">.
                </textarea>
                <button class = 'btn btn-default' id="demo" onclick=“cleanupurl(myTextarea.text())> Cleanup URL</button>
            </div>

            <div id ="result1">
                <p></p>
            </div>

            <div id ="result2">
                <p></p>
            </div>
        </body>
    </html>
   <script>
    var splitstring = [''];
    var finaloutput = ''; var i = 0;

    function cleanupurl(urlstring) {

        //==========================================//
        urlstring = urlstring.replace(/%21/gi, '!');
        urlstring = urlstring.replace(/%23/gi, '#');
        urlstring = urlstring.replace(/%24/gi, '$');
        urlstring = urlstring.replace(/%26/gi, '&');

        //==========================================//
        splitstring = urlstring.split('http://');
        document.getElementById("result1").innerHTML =  cleanurloutput1();
        //return
    }

    function cleanurloutput1(){
    return splitstring[1];
        }

    function cleanurloutput2(){
    return splitstring[2];
        }

        //document.getElementById("result1").innerHTML = cleanurloutput1();

        var x = document.getElementById("myTextarea").value;
        cleanupurl(x);

    </script>
</code>```

答:
so the first problem I encountered when I ran your code in my browser using the debug tool was:

I found that you had included illegal character which was ths character ( “ ) it looks like a double quote but I am sure it has a different ASCII value. I found it at this point
“cleanupurl(myTextarea.text())

I completely rewrote that line to appear like this:

<button class = 'btn btn-default' id="demo" onclick="cleanupurl();"> Cleanup URL</button>```
</div>
</div>
</p>

<p>Then I made this change to your javascript.... And <b>Viola</b> Your code works</p>

```    function cleanupurl() {

    var urlstring = document.getElementById('myTextarea').value;
```

Title: javascript output not showing in html

Body:
I’m trying to write code that removes some special characters from any string URL and then displays the cleaned string via html.

The JavaScript works but I can’t get the result to show in the browser.

The whole point of the code is to have someone put in input and then the input is then cleaned up and the result is then inserted in “result1” and/or “result2”

So when the page loads and the user types something in “myTextarea” and clicks the button, cleanupurl(x) is supposed to run.

pls help ;(

code so far

<!DOCTYPE html>

        <title>Clean Strings</title>

                <textarea placeholder="insert URL here :)" id="myTextarea">.
                </textarea>
                <button class = 'btn btn-default' id="demo" onclick=“cleanupurl(myTextarea.text())> Cleanup URL</button>

Body:
so the first problem I encountered when I ran your code in my browser using the debug tool was:

I found that you had included illegal character which was ths character ( “ ) it looks like a double quote but I am sure it has a different ASCII value. I found it at this point
“cleanupurl(myTextarea.text())

I completely rewrote that line to appear like this:

<button class = 'btn btn-default' id="demo" onclick="cleanupurl();"> Cleanup URL</button>

Then I made this change to your javascript.... And Viola Your code works

    function cleanupurl() {

    var urlstring = document.getElementById('myTextarea').value;


问:
Node localhost not returning date
I have the following index.js file:

```<code>var express = require('express');
var app = express();

app.use('/',(req,res) => {

console.log(req.get('Date'));
console.log(req.get('User-Agent'));
console.log(req.url);

var name = req.query.name;
res.status(200).type('html');

res.write('Hello World! <br>');
if (name) {
   res.write('Hi, ' + name + " it's nice to see you.");
}else{
   res.write('Welcome, guest!');
}

res.end();
});

app.listen(3001, () => {
console.log('Listening on port 3001');

});
</code>```

Why is date undefined?

答:
because the browser you are using is not sending the date in the headers...

you could use local server date....

Title: Node localhost not returning date

Body:
I have the following index.js file:

var express = require('express');
var app = express();

app.use('/',(req,res) => {

console.log(req.get('Date'));
console.log(req.get('User-Agent'));
console.log(req.url);

var name = req.query.name;
res.status(200).type('html');

res.write('Hello World!
');
if (name) {
   res.write('Hi, ' + name + " it's nice to see you.");
}else{
   res.write('Welcome, guest!');
}

res.end();
});

app.listen(3001, () => {
console.log('Listening on port 3001');

});

Why is date undefined?


问:
Symfony2 DBAL Update method returning 0
I'm getting a strange result, where an update method (http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/data-retrieval-and-manipulation.html#update) call that activates/deactivates site users accounts in my mySQL database sometimes are not updated and returns a 0.  Here is the code:

```<code>$user_id = '198';
$sqlSetStmnt= [ 'activation_code' => NULL, 'active' => 0 ];
$conn = $this->get( 'database_connection' );

try {

  $result = $conn->update( 'users', $sqlSetStmnt,[ 'id' => (int)$user_id ] );

}
catch( Exception $e ) {

  $error = $e->getMessage();
  throw new \Exception( 'update user account data function -- ' .
                        'error: ' . $error . ' - ' .
                        'unable to update your account!' );

} // End of catch( Exception ) block.

if( ( $result === FALSE ) || ( $result !== 1 ) ) {

  throw new \Exception( 'update user account data function -- ' .
                        'update return value: ' . $result . ' - ' .
                        'unable to update your account!' );

} // if( ( $result === FALSE ) || ( $result !== 1 ) ) ...
</code>```

The users table has an id int(11) column which is the primary key, an active tinyint(1) column, and activation_code varchar(40) NULL column.

Please note the $user_id variable contains a string value of '198', but it is cast to an int when creating the $sqlSetStmnt value.

Inspecting the users table confirms that there was a row in the users table with the id column value of 198 at the time of the update call.

The account used when running the update call has enough privileges to change the row active and activation_code column values.

There are no other users in the system or accessing the database, so there aren't any locks on the row.

I inspected the code using x-debug, and the values of the $user_id and $sqlSetStmnt variables were properly set to the values that I expected, that $result was set to 0 by the update method, and that no exceptions were thrown by the update method call.

By the way, there is no need to using variable binding because the values in the $user_id and $sqlSetStmnt variables are not input by an user, so no possibility of SQL-Injection, or Buffer-Overrun.

Is there some way to get information from DBAL about why the update method returned 0?

Thank you.

答:
Before solving this issue I switched from:

```<code>$result = $conn->update( 'users', $sqlSetStmnt, [ 'id' => (int)$user_id ] );
</code>```

to:

```<code>$sqlUpdateStmnt = 'UPDATE `users` SET field = value ' .
                   'WHERE `id` = ' . $user_id;
$result = $conn->executeUpdate( $sqlUpdateStmnt );
</code>```

and got exactly the same result, where some updates would return 0 rows when there definitely was a row in the users table with an id matching the value of $user_id.

I got around this problem by fetching the existing row and then only updating the row when the fields in the set-clause were different than the same columns from the table.

This tells me that the 0 return value wasn't that there were no matching rows, but that the updated didn't have any effect on any rows.

So this issue isn't a bug, so much as a misunderstanding of the result.  However, the problem still exists when using the update() method of how to determine when the update failed due to no matching rows and when no changes were made.

The solution that I ended up solves this at the cost of a pre-fetch to verify that the update would affect a row.  In my case, with a multi-user database application, pre-fetching isn't actually a problem because the row that is to be updated could have been deleted by another user before the update tries to make its change.  But, it would be nice if both update methods explained this more clearly, and returned different values: 0 for no affected rows and FALSE for no rows found.

Title: Symfony2 DBAL Update method returning 0

Body:
I'm getting a strange result, where an update method (http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/data-retrieval-and-manipulation.html#update) call that activates/deactivates site users accounts in my mySQL database sometimes are not updated and returns a 0.  Here is the code:

$user_id = '198';
$sqlSetStmnt= [ 'activation_code' => NULL, 'active' => 0 ];
$conn = $this->get( 'database_connection' );

try {

  $result = $conn->update( 'users', $sqlSetStmnt,[ 'id' => (int)$user_id ] );

}
catch( Exception $e ) {

  $error = $e->getMessage();
  throw new \Exception( 'update user account data function -- ' .
                        'error: ' . $error . ' - ' .
                        'unable to update your account!' );

} // End of catch( Exception ) block.

if( ( $result === FALSE ) || ( $result !== 1 ) ) {

  throw new \Exception( 'update user account data function -- ' .
                        'update return value: ' . $result . ' - ' .
                        'unable to update your account!' );

} // if( ( $result === FALSE ) || ( $result !== 1 ) ) ...

The users table has an id int(11) column which is the primary key, an active tinyint(1) column, and activation_code varchar(40) NULL column.

Please note the $user_id variable contains a string value of '198', but it is cast to an int when creating the $sqlSetStmnt value.

Inspecting the users table confirms that there was a row in the users table with the id column value of 198 at the time of the update call.

The account used when running the update call has enough privileges to change the row active and activation_code column values.

There are no other users in the system or accessing the database, so there aren't any locks on the row.

I inspected the code using x-debug, and the values of the $user_id and $sqlSetStmnt variables were properly set to the values that I expected, that $result was set to 0 by the update method, and that no exceptions were thrown by the update method call.

By the way, there is no need to using variable binding because the values in the $user_id and $sqlSetStmnt variables are not input by an user, so no possibility of SQL-Injection, or Buffer-Overrun.

Is there some way to get information from DBAL about why the update method returned 0?

Thank you.

Body:
Before solving this issue I switched from:

$result = $conn->update( 'users', $sqlSetStmnt, [ 'id' => (int)$user_id ] );

to:

$sqlUpdateStmnt = 'UPDATE `users` SET field = value ' .
                   'WHERE `id` = ' . $user_id;
$result = $conn->executeUpdate( $sqlUpdateStmnt );

and got exactly the same result, where some updates would return 0 rows when there definitely was a row in the users table with an id matching the value of $user_id.

I got around this problem by fetching the existing row and then only updating the row when the fields in the set-clause were different than the same columns from the table.

This tells me that the 0 return value wasn't that there were no matching rows, but that the updated didn't have any effect on any rows.

So this issue isn't a bug, so much as a misunderstanding of the result.  However, the problem still exists when using the update() method of how to determine when the update failed due to no matching rows and when no changes were made.

The solution that I ended up solves this at the cost of a pre-fetch to verify that the update would affect a row.  In my case, with a multi-user database application, pre-fetching isn't actually a problem because the row that is to be updated could have been deleted by another user before the update tries to make its change.  But, it would be nice if both update methods explained this more clearly, and returned different values: 0 for no affected rows and FALSE for no rows found.


答:
Your condition x>0 it will never be false because your x always will increase.

Ex:
* start code:
x = 1500000
y = 0

first iteration:
x = 1630000
y = 1

second iteration:
x = 1773000
y = 2

3th iteration:
x = 1930300
y = 3

So your code never into in else.

Title: Simple python script is not printing output


问:
How to add many functions in ONE ng-click?
I've be looking for how to execute this but I can't find anything related so far, :(
I could nest both functions yes but I'm just wondering if this is possible?
I'd like to do this literally:

```<code><td><button class="btn" ng-click="edit($index) open()">Open me!</button></td>
</code>```

My JS code at the moment:

```<code>$scope.open = function () {
  $scope.shouldBeOpen = true;
};

$scope.edit = function(index){

  var content_1, content_2;
      content_1 = $scope.people[index].name;
      content_2 = $scope.people[index].age;

  console.log(content_1);
};
</code>```

I'd like to call two functions with just one click, how can I do this in angularJS?
I thought it'd be straight forward like in CSS when you add multiple classes...but it's not :(

答:
Try this:

Make a collection of functions

Make a function that loops through and executes all the functions in the collection.

Add the function to the html

```<code>array = [
    function() {},
    function() {},
    function() {}
]

function loop() {
    array.forEach(item) {
        item()
    }
}

ng - click = "loop()"
</code>```

Body:
I've be looking for how to execute this but I can't find anything related so far, :(
I could nest both functions yes but I'm just wondering if this is possible?
I'd like to do this literally:

<button class="btn" ng-click="edit($index) open()">Open me!</button>

My JS code at the moment:

$scope.open = function () {
  $scope.shouldBeOpen = true;
};

$scope.edit = function(index){

  var content_1, content_2;
      content_1 = $scope.people[index].name;
      content_2 = $scope.people[index].age;

  console.log(content_1);
};

I'd like to call two functions with just one click, how can I do this in angularJS?
I thought it'd be straight forward like in CSS when you add multiple classes...but it's not :(

Body:
Try this:

Make a collection of functions

Make a function that loops through and executes all the functions in the collection.

Add the function to the html

array = [
    function() {},
    function() {},
    function() {}
]

function loop() {
    array.forEach(item) {
        item()
    }
}

ng - click = "loop()"


问:
Many to many to many relationship query
I got 3 main table.

Table A
Table B
Table C

Table A has many to many relationships with Table B
so they have a pivot table ab

Table B has also many to many relationships with Table C
so they also have a pivot table bc

So because of this Table A has many to many through, relationship with Table C.

So what is the MySQL query if I wanted to get all rows of Table C that is related to Table A?

答: If you set the models well, A->Bs->Cs; should do the trick.

Title: Many to many to many relationship query


问:
Extracting Spot Value from Thermal Image
I have a FLIR Image from which I want to extract "spot value". The spot value is printed on the image. I found the Thermimage package that I use in R.

This is what I get when I run this:

```<code>library(Thermimage)
flirsettings("FLIR8655.jpg", exiftoolpath = "installed", camvals = "")

$Info
$Info$ExifToolVersionNumber
[1] 10.62

$Info$FileName
[1] 8655

$Info$Directory
[1] "357-2517"

$Info$FileSize
[1] 74

$Info$FilePermissions
[1] ""

$Info$FileType
[1] ""

$Info$FileTypeExtension
[1] ""

$Info$MIMEType
[1] ""

$Info$JFIFVersion
[1] 1.01

$Info$ExifByteOrder
[1] "-"

$Info$Make
[1] ""

$Info$CameraModelName
[1] 3

$Info$Orientation
[1] ""

$Info$XResolution
[1] 72

$Info$YResolution
[1] 72

$Info$ResolutionUnit
[1] ""

$Info$Software
[1] "3.6.0"

$Info$YCbCrPositioning
[1] ""

$Info$ExposureTime
[1] 150

$Info$ExifVersion
[1] 220

$Info$ComponentsConfiguration
[1] "-"

$Info$SubjectDistance
[1] 1

$Info$FocalLength
[1] 1.8

$Info$ImageTemperatureMax
[1] 311

$Info$ImageTemperatureMin
[1] 296

$Info$FlashpixVersion
[1] 100

$Info$ColorSpace
[1] ""

$Info$ExifImageWidth
[1] 320

$Info$ExifImageHeight
[1] 240

$Info$DigitalZoomRatio
[1] 1

$Info$ImageUniqueID
[1] 7.415218e+19

$Info$Compression
[1] "-"

$Info$ThumbnailOffset
[1] 1894

$Info$ThumbnailLength
[1] 2474

$Info$CreatorSoftware
[1] NA

$Info$Emissivity
[1] 0.95

$Info$ObjectDistance
[1] 1

$Info$ReflectedApparentTemperature
[1] 20

$Info$AtmosphericTemperature
[1] 20

$Info$IRWindowTemperature
[1] 20

$Info$IRWindowTransmission
[1] 1

$Info$RelativeHumidity
[1] 50

$Info$PlanckR1
[1] 11326.43

$Info$PlanckB
[1] 1316.8

$Info$PlanckF
[1] 1.65

$Info$AtmosphericTransAlpha1
[1] 0.006569

$Info$AtmosphericTransAlpha2
[1] 0.01262

$Info$AtmosphericTransBeta1
[1] -0.002276

$Info$AtmosphericTransBeta2
[1] -0.00667

$Info$AtmosphericTransX
[1] 1.9

$Info$CameraTemperatureRangeMax
[1] 150

$Info$CameraTemperatureRangeMin
[1] -10

$Info$CameraTemperatureMaxClip
[1] 180

$Info$CameraTemperatureMinClip
[1] -40

$Info$CameraTemperatureMaxWarn
[1] 150

$Info$CameraTemperatureMinWarn
[1] -10

$Info$CameraTemperatureMaxSaturated
[1] 180

$Info$CameraTemperatureMinSaturated
[1] -60

$Info$CameraModel
[1] 3

$Info$CameraPartNumber
[1] "72003-0303"

$Info$CameraSerialNumber
[1] 720071224

$Info$CameraSoftware
[1] "34.0.0"

$Info$LensModel
[1] 2

$Info$LensPartNumber
[1] NA

$Info$LensSerialNumber
[1] NA

$Info$Isotherm1Color
[1] 100128128

$Info$Isotherm2Color
[1] 100110240

$Info$PaletteMethod
[1] 0

$Info$PaletteStretch
[1] 2

$Info$PaletteFileName
[1] "."

$Info$PaletteName
[1] ""

$Info$Palette
[1] "672-"

$Info$RawThermalImageWidth
[1] 80

$Info$RawThermalImageHeight
[1] 60

$Info$RawThermalImageType
[1] "PNG"

$Info$RawThermalImage
[1] "6352-"

$Info$Real2IR
[1] 1.389537

$Info$OffsetX
[1] -1

$Info$OffsetY
[1] 8

$Info$PiPX1
[1] 0

$Info$PiPX2
[1] 80

$Info$PiPY1
[1] 0

$Info$PiPY2
[1] 60

$Info$EmbeddedImageWidth
[1] 640

$Info$EmbeddedImageHeight
[1] 480

$Info$EmbeddedImageType
[1] ""

$Info$EmbeddedImage
[1] "38325-"

$Info$ImageWidth
[1] 320

$Info$ImageHeight
[1] 240

$Info$EncodingProcess
[1] ""

$Info$BitsPerSample
[1] 8

$Info$ColorComponents
[1] 3

$Info$YCbCrSubSampling
[1] "4:2:022"

$Info$ImageSize
[1] 320240

$Info$Megapixels
[1] 0.077

$Info$PeakSpectralSensitivity
[1] 10.9

$Info$ShutterSpeed
[1] 150

$Info$ThumbnailImage
[1] "2474-"

$Info$FocalLength
[1] 1.8

$Dates
$Dates$FileModificationDateTime
[1] "2017-08-21 14:20:46"

$Dates$FileAccessDateTime
[1] "2017-10-04 02:36:24"

$Dates$FileInodeChangeDateTime
[1] "2017-09-10 18:41:44"

$Dates$ModifyDate
[1] "2017-08-21 08:20:46"

$Dates$CreateDate
[1] "2017-08-21 08:20:46"

$Dates$DateTimeOriginal
[1] "2017-08-21 16:20:46"
</code>```

Is there a way to get the measurement i.e. spot value from the image? Or can I use exiftool to extract this value from the image and how can I do that?

答:
I would try using exiftool on the command line rather than from the R package, Thermimage, since the R package does not report on all text output from exiftool.  Try this in a terminal window:

```<code>exiftool FLIR8655.jpg
</code>```

which might yield something like this for your image:

```<code>...
Meas 1 Type                     : Spot
Meas 1 Params                   : 320 240
Meas 1 Label                    : 1
Meas 2 Type                     : Area
Meas 2 Params                   : 213 160 213 160
Meas 2 Label                    : 1
</code>```

But I cannot find any output for the spot temperature (Meas 1 above) in the normal exiftool output.  You could export the raw thermal binary data with exiftool and extract the wth x hth data point corresponding to the spot position.

Body:
I have a FLIR Image from which I want to extract "spot value". The spot value is printed on the image. I found the Thermimage package that I use in R.

This is what I get when I run this:

library(Thermimage)
flirsettings("FLIR8655.jpg", exiftoolpath = "installed", camvals = "")

$Info
$Info$ExifToolVersionNumber
[1] 10.62

$Info$FileName
[1] 8655

$Info$Directory
[1] "357-2517"

$Info$FileSize
[1] 74

$Info$FilePermissions
[1] ""

$Info$FileType
[1] ""

$Info$FileTypeExtension
[1] ""

$Info$MIMEType
[1] ""

$Info$JFIFVersion
[1] 1.01

$Info$ExifByteOrder
[1] "-"

$Info$Make
[1] ""

$Info$CameraModelName
[1] 3

$Info$Orientation
[1] ""

$Info$XResolution
[1] 72

$Info$YResolution
[1] 72

$Info$ResolutionUnit
[1] ""

$Info$Software
[1] "3.6.0"

$Info$YCbCrPositioning
[1] ""

$Info$ExposureTime
[1] 150

$Info$ExifVersion
[1] 220

$Info$ComponentsConfiguration
[1] "-"

$Info$SubjectDistance
[1] 1

$Info$FocalLength
[1] 1.8

$Info$ImageTemperatureMax
[1] 311

$Info$ImageTemperatureMin
[1] 296

$Info$FlashpixVersion
[1] 100

$Info$ColorSpace
[1] ""

$Info$ExifImageWidth
[1] 320

$Info$ExifImageHeight
[1] 240

$Info$DigitalZoomRatio
[1] 1

$Info$ImageUniqueID
[1] 7.415218e+19

$Info$Compression
[1] "-"

$Info$ThumbnailOffset
[1] 1894

$Info$ThumbnailLength
[1] 2474

$Info$CreatorSoftware
[1] NA

$Info$Emissivity
[1] 0.95

$Info$ObjectDistance
[1] 1

$Info$ReflectedApparentTemperature
[1] 20

$Info$AtmosphericTemperature
[1] 20

$Info$IRWindowTemperature
[1] 20

$Info$IRWindowTransmission
[1] 1

$Info$RelativeHumidity
[1] 50

$Info$PlanckR1
[1] 11326.43

$Info$PlanckB
[1] 1316.8

$Info$PlanckF
[1] 1.65

$Info$AtmosphericTransAlpha1
[1] 0.006569

$Info$AtmosphericTransAlpha2
[1] 0.01262

$Info$AtmosphericTransBeta1
[1] -0.002276

$Info$AtmosphericTransBeta2
[1] -0.00667

$Info$AtmosphericTransX
[1] 1.9

$Info$CameraTemperatureRangeMax
[1] 150

$Info$CameraTemperatureRangeMin
[1] -10

$Info$CameraTemperatureMaxClip
[1] 180

$Info$CameraTemperatureMinClip
[1] -40

$Info$CameraTemperatureMaxWarn
[1] 150

$Info$CameraTemperatureMinWarn
[1] -10

$Info$CameraTemperatureMaxSaturated
[1] 180

$Info$CameraTemperatureMinSaturated
[1] -60

$Info$CameraModel
[1] 3

$Info$CameraPartNumber
[1] "72003-0303"

$Info$CameraSerialNumber
[1] 720071224

$Info$CameraSoftware
[1] "34.0.0"

$Info$LensModel
[1] 2

$Info$LensPartNumber
[1] NA

$Info$LensSerialNumber
[1] NA

$Info$Isotherm1Color
[1] 100128128

$Info$Isotherm2Color
[1] 100110240

$Info$PaletteMethod
[1] 0

$Info$PaletteStretch
[1] 2

$Info$PaletteFileName
[1] "."

$Info$PaletteName
[1] ""

$Info$Palette
[1] "672-"

$Info$RawThermalImageWidth
[1] 80

$Info$RawThermalImageHeight
[1] 60

$Info$RawThermalImageType
[1] "PNG"

$Info$RawThermalImage
[1] "6352-"

$Info$Real2IR
[1] 1.389537

$Info$OffsetX
[1] -1

$Info$OffsetY
[1] 8

$Info$PiPX1
[1] 0

$Info$PiPX2
[1] 80

$Info$PiPY1
[1] 0

$Info$PiPY2
[1] 60

$Info$EmbeddedImageWidth
[1] 640

$Info$EmbeddedImageHeight
[1] 480

$Info$EmbeddedImageType
[1] ""

$Info$EmbeddedImage
[1] "38325-"

$Info$ImageWidth
[1] 320

$Info$ImageHeight
[1] 240

$Info$EncodingProcess
[1] ""

$Info$BitsPerSample
[1] 8

$Info$ColorComponents
[1] 3

$Info$YCbCrSubSampling
[1] "4:2:022"

$Info$ImageSize
[1] 320240

$Info$Megapixels
[1] 0.077

$Info$PeakSpectralSensitivity
[1] 10.9

$Info$ShutterSpeed
[1] 150

$Info$ThumbnailImage
[1] "2474-"

$Info$FocalLength
[1] 1.8

$Dates
$Dates$FileModificationDateTime
[1] "2017-08-21 14:20:46"

$Dates$FileAccessDateTime
[1] "2017-10-04 02:36:24"

$Dates$FileInodeChangeDateTime
[1] "2017-09-10 18:41:44"

$Dates$ModifyDate
[1] "2017-08-21 08:20:46"

$Dates$CreateDate
[1] "2017-08-21 08:20:46"

$Dates$DateTimeOriginal
[1] "2017-08-21 16:20:46"

Is there a way to get the measurement i.e. spot value from the image? Or can I use exiftool to extract this value from the image and how can I do that?

Body:
I would try using exiftool on the command line rather than from the R package, Thermimage, since the R package does not report on all text output from exiftool.  Try this in a terminal window:

exiftool FLIR8655.jpg

which might yield something like this for your image:

...
Meas 1 Type                     : Spot
Meas 1 Params                   : 320 240
Meas 1 Label                    : 1
Meas 2 Type                     : Area
Meas 2 Params                   : 213 160 213 160
Meas 2 Label                    : 1

But I cannot find any output for the spot temperature (Meas 1 above) in the normal exiftool output.  You could export the raw thermal binary data with exiftool and extract the wth x hth data point corresponding to the spot position.


问:
Read remote file beginning with "smb://" using R
To read a file in R, I'd normally do something like the following:

```<code>read.csv('/Users/myusername/myfilename.csv')
</code>```

But, I'm trying to read a file located on a remote server (Windows SMB/CIFS share) which I access on my Mac via the Finder → Go → Connect to Server menu item.

When I view that file's properties, the file path is different than what I'm used to. Instead of beginning with: /Users/myusername/..., it is smb://server.msu.edu/.../myfilename.csv.

Trying to read the file, I tried the following:

```<code>read.csv('smb://server.msu.edu/.../myfilename.csv')
</code>```

But, this didn't work.

Instead of the usual "No such file or directory" error, this returned:

smb://server.msu.edu/.../myfilename.csv does not exist in current working directory

I imagine the file path needs a different format, but I can't figure what.

How can you read this type of file in R?

答:
Below I've shown a way that I've used from time to time to read data from an SMB network drive. In the code below, I've used the R system function to do everything from within R, but you can also mount the drive from the OSX command line or from within Finder with Command-K (connect to server):

If you don't already have one, create a directory on your local drive where the share will be located (this isn't necessary, as you can mount the drive in an existing location):

```<code>system("mkdir /Users/eipi10/temp_share/")
</code>```

or

```<code>dir.create("/Users/eipi10/temp_share/")
</code>```

Mount the network drive to the folder you just created. In the code below, //username@domain.address.edu/home/u/eipi10 is your user name and the address of the SMB share.

```<code>system("mount_smbfs //username@domain.address.edu/home/u/eipi10 /Users/eipi10/temp_share")
</code>```

If there's password authentication, then the password can be included as well:

```<code>system("mount_smbfs //username:password@domain.address.edu/home/u/eipi10 /Users/eipi10/temp_share")
</code>```

Read the data:

```<code>dat = read.csv("/Users/eipi10/temp_share/fileToRead.csv")
</code>```

From within R, you can also programmatically select files to read:

```<code>data.list = lapply(list.files(pattern="csv$", "/Users/eipi10/temp_share/", full.names=TRUE), read.csv)
</code>```

Body:
To read a file in R, I'd normally do something like the following:

read.csv('/Users/myusername/myfilename.csv')

But, I'm trying to read a file located on a remote server (Windows SMB/CIFS share) which I access on my Mac via the Finder → Go → Connect to Server menu item.

When I view that file's properties, the file path is different than what I'm used to. Instead of beginning with: /Users/myusername/..., it is smb://server.msu.edu/.../myfilename.csv.

Trying to read the file, I tried the following:

read.csv('smb://server.msu.edu/.../myfilename.csv')

But, this didn't work.

Instead of the usual "No such file or directory" error, this returned:

smb://server.msu.edu/.../myfilename.csv does not exist in current working directory

I imagine the file path needs a different format, but I can't figure what.

How can you read this type of file in R?

Body:
Below I've shown a way that I've used from time to time to read data from an SMB network drive. In the code below, I've used the R system function to do everything from within R, but you can also mount the drive from the OSX command line or from within Finder with Command-K (connect to server):

If you don't already have one, create a directory on your local drive where the share will be located (this isn't necessary, as you can mount the drive in an existing location):

system("mkdir /Users/eipi10/temp_share/")

or

dir.create("/Users/eipi10/temp_share/")

Mount the network drive to the folder you just created. In the code below, //username@domain.address.edu/home/u/eipi10 is your user name and the address of the SMB share.

system("mount_smbfs //username@domain.address.edu/home/u/eipi10 /Users/eipi10/temp_share")

If there's password authentication, then the password can be included as well:

system("mount_smbfs //username:password@domain.address.edu/home/u/eipi10 /Users/eipi10/temp_share")

Read the data:

dat = read.csv("/Users/eipi10/temp_share/fileToRead.csv")

From within R, you can also programmatically select files to read:

data.list = lapply(list.files(pattern="csv$", "/Users/eipi10/temp_share/", full.names=TRUE), read.csv)


问:
Split string on a number, preserving the number
I have a string which will always be at least a number, but can also contain letters before and/or after the number:

```<code>"4"
"Section 2"
"4 Section"
"Section 5 Aisle"
</code>```

I need to split the string like this:

```<code>"4" becomes "4"
"Section 2" becomes "Section ","2"
"4 Aisle" becomes "4"," Aisle"
"Section 5 Aisle" becomes "Section ","5"," Aisle"
</code>```

How can I do this with Ruby 1.9.2?

答:
In case you didn't really want the whitespace in the separators, and you did want to have a consistent handle on the before/after, use this:

```<code>test = [
  "4",
  "Section 2",
  "4 Section",
  "Section 5 Aisle",
]

require 'pp'
pp test.map{ |str| str.split(/\s*(\d+)\s*/,-1) }
#=> [["", "4", ""],
#=>  ["Section", "2", ""],
#=>  ["", "4", "Section"],
#=>  ["Section", "5", "Aisle"]]
</code>```

Thus you could always do:

```<code>prefix, digits, suffix = str.split(/\s*(\d+)\s*/,-1)
if prefix.empty?
  ...
end
</code>```

...instead of testing the length of your matches or some such.

Body:
I have a string which will always be at least a number, but can also contain letters before and/or after the number:

"4"
"Section 2"
"4 Section"
"Section 5 Aisle"

I need to split the string like this:

"4" becomes "4"
"Section 2" becomes "Section ","2"
"4 Aisle" becomes "4"," Aisle"
"Section 5 Aisle" becomes "Section ","5"," Aisle"

How can I do this with Ruby 1.9.2?

Body:
In case you didn't really want the whitespace in the separators, and you did want to have a consistent handle on the before/after, use this:

test = [
  "4",
  "Section 2",
  "4 Section",
  "Section 5 Aisle",
]

require 'pp'
pp test.map{ |str| str.split(/\s*(\d+)\s*/,-1) }
#=> [["", "4", ""],
#=>  ["Section", "2", ""],
#=>  ["", "4", "Section"],
#=>  ["Section", "5", "Aisle"]]

Thus you could always do:

prefix, digits, suffix = str.split(/\s*(\d+)\s*/,-1)
if prefix.empty?
  ...
end

...instead of testing the length of your matches or some such.


问:
typescript ignore cannot instantiate abstract class error
The TS compiler complains that I cannot instantiate MeteorCollection at the line return new this

```<code>abstract class MeteorCollection {
    static $collection: Collection<any>

    static findOne(selector: Selector = {}, options: FindOneOptions = {}) {
        let item = this.$collection.findOne(selector, options)
        return new this(item)
    }
}
</code>```

How can I tell it that it is ok, since this refers to the constructor of a class that will extend MeteorCollection and not to MeteorCollection itself.

答:
No need to ignore the error. I assume you intend to invoke the method from a reference to a subclass so use a this type annotation.

```<code>abstract class MeteorCollection {
  static $collection: Collection<any>;

  static findOne<T extends MeteorCollection>(
    this: typeof MeteorCollection & (new (arg: any, ...args: any[]) => T),
    selector: Selector = {},
    options: FindOneOptions = {}
  ) {
    const item = this.$collection.findOne(selector, options);
    return new this(item);
  }
}
</code>```

Body:
The TS compiler complains that I cannot instantiate MeteorCollection at the line return new this

abstract class MeteorCollection {
    static $collection: Collection<any>

    static findOne(selector: Selector = {}, options: FindOneOptions = {}) {
        let item = this.$collection.findOne(selector, options)
        return new this(item)
    }
}

How can I tell it that it is ok, since this refers to the constructor of a class that will extend MeteorCollection and not to MeteorCollection itself.

Body:
No need to ignore the error. I assume you intend to invoke the method from a reference to a subclass so use a this type annotation.

abstract class MeteorCollection {
  static $collection: Collection<any>;

  static findOne<T extends MeteorCollection>(
    this: typeof MeteorCollection & (new (arg: any, ...args: any[]) => T),
    selector: Selector = {},
    options: FindOneOptions = {}
  ) {
    const item = this.$collection.findOne(selector, options);
    return new this(item);
  }
}


问:
currval has not yet been defined this session, how to get multi-session sequences?
My objective is to get a primary key field automatically inserted when inserting new row in the table.

How to get a sequence going from session to session in PostgreSQL?

```<code> doubleemploi@hanbei:/home/yves$ psql -d test
 Mot de passe :
 psql (8.4.13)
 Saisissez « help » pour l''aide.

 test=> create sequence test001 start 10;
 CREATE SEQUENCE
 test=> select currval('test001');
 ERREUR:  la valeur courante (currval) de la séquence « test00 » n''est pas encore définie dans cette session
 --- current value not yet defined this session (???)
 test=> select setval('test001', 10);
 setval
 --------
      10
 (1 ligne)

 test=> select currval('test00');
  currval
 ---------
       10
 (1 ligne)

 test=> \q
 test@hanbei:/home/yves$ psql -d test
 Mot de passe :
 psql (8.4.13)
 Saisissez « help » pour l''aide.

 test=> select currval('test001');
 ERREUR:  la valeur courante (currval) de la séquence « test00 » n''est pas encore définie dans cette session
</code>```

答:
I will give a practical answer for this matter.
My database server is used by my programs and my psql terminal; so there are multiple sessions. currently I am in my psql terminal:

```<code>fooserver=> select currval('fusion_id_seq');
ERROR:  currval of sequence "fusion_id_seq" is not yet defined in this session
fooserver=> select nextval('fusion_id_seq');
 nextval
---------
  320032
(1 row)

fooserver=> select currval('fusion_id_seq');
 currval
---------
  320032
(1 row)
</code>```

It looks that you can only see the values in your own session. This will also affect the currval of another session.  This is probably related to multi-threading of the server to isolate different session.  The counter (serial in psql) is a shared object. In my opinion, this session should be able to get the current value of the counter as long as the counter is properly locked to ensure only a single thread (session) can increment it (atomic operation).  But I could be wrong here (not an expert on database server writer).

Body:
My objective is to get a primary key field automatically inserted when inserting new row in the table.

How to get a sequence going from session to session in PostgreSQL?

 doubleemploi@hanbei:/home/yves$ psql -d test
 Mot de passe :
 psql (8.4.13)
 Saisissez « help » pour l''aide.

 test=> create sequence test001 start 10;
 CREATE SEQUENCE
 test=> select currval('test001');
 ERREUR:  la valeur courante (currval) de la séquence « test00 » n''est pas encore définie dans cette session
 --- current value not yet defined this session (???)
 test=> select setval('test001', 10);
 setval
 --------
      10
 (1 ligne)

 test=> select currval('test00');
  currval
 ---------
       10
 (1 ligne)

 test=> \q
 test@hanbei:/home/yves$ psql -d test
 Mot de passe :
 psql (8.4.13)
 Saisissez « help » pour l''aide.

 test=> select currval('test001');
 ERREUR:  la valeur courante (currval) de la séquence « test00 » n''est pas encore définie dans cette session

Body:
I will give a practical answer for this matter.
My database server is used by my programs and my psql terminal; so there are multiple sessions. currently I am in my psql terminal:

fooserver=> select currval('fusion_id_seq');
ERROR:  currval of sequence "fusion_id_seq" is not yet defined in this session
fooserver=> select nextval('fusion_id_seq');
 nextval
---------
  320032
(1 row)

fooserver=> select currval('fusion_id_seq');
 currval
---------
  320032
(1 row)

It looks that you can only see the values in your own session. This will also affect the currval of another session.  This is probably related to multi-threading of the server to isolate different session.  The counter (serial in psql) is a shared object. In my opinion, this session should be able to get the current value of the counter as long as the counter is properly locked to ensure only a single thread (session) can increment it (atomic operation).  But I could be wrong here (not an expert on database server writer).