问:
Find pair of matches between an numpy array Python
I have a numpy array in Python which contains labels for a classification problem. The array derived after the concatentation of two initial identical arrays.

```<code>labels = np.concatenate((labels1, labels2)) #labels1 and labels2 are identical
</code>```

I want to generate positive/negative pairs which will contain all the indexes from labels (from which labels1 and labels2 are equal) and also the pairs with the negative ones. For example if my input is the following:

```<code>labels = {1, 1, 2, 2, 3, 1, 1, 2, 2, 3} # labels1 = labels2 = {1, 1, 2, 2, 3}
</code>```

Then I want to return as positive pairs:

```<code>positive_pairs = {{1, 6}, {1, 7}, {2, 6}, {2, 7}, {3, 8}, {3, 9}, {4, 8}, {4, 9}, {5, 10}} # i dont want to have {1,2} or {3, 4} in within the positives
negative_pairs = {{1, 8}, {1, 9}, ...}
</code>```

How can I do so in python?

EDIT: What in the case that labels1 and labels2 are not equal?

答:
Here's a solution for positive_pairs:

```<code>labels1 = np.array([1, 1, 2, 2, 3])
length1 = len(labels1)
positive_pairs = []
for ii, label in enumerate(labels1, 1):
    for other in np.where(labels1 == label)[0] + length1 + 1:
        positive_pairs.append((ii, other))
</code>```

negative_pairs is left as an exercise.

Body:
I have a numpy array in Python which contains labels for a classification problem. The array derived after the concatentation of two initial identical arrays.

labels = np.concatenate((labels1, labels2)) #labels1 and labels2 are identical

I want to generate positive/negative pairs which will contain all the indexes from labels (from which labels1 and labels2 are equal) and also the pairs with the negative ones. For example if my input is the following:

labels = {1, 1, 2, 2, 3, 1, 1, 2, 2, 3} # labels1 = labels2 = {1, 1, 2, 2, 3}

Then I want to return as positive pairs:

positive_pairs = {{1, 6}, {1, 7}, {2, 6}, {2, 7}, {3, 8}, {3, 9}, {4, 8}, {4, 9}, {5, 10}} # i dont want to have {1,2} or {3, 4} in within the positives
negative_pairs = {{1, 8}, {1, 9}, ...}

How can I do so in python?

EDIT: What in the case that labels1 and labels2 are not equal?

Body:
Here's a solution for positive_pairs:

labels1 = np.array([1, 1, 2, 2, 3])
length1 = len(labels1)
positive_pairs = []
for ii, label in enumerate(labels1, 1):
    for other in np.where(labels1 == label)[0] + length1 + 1:
        positive_pairs.append((ii, other))

negative_pairs is left as an exercise.


来源: stackexchange

问:
Handle text Colour in WooCommerce variations?
Have one problem that don t know how to resolve. Have product (XS variation) that is "non in stock" but have selected "Allow but notify customer" So want to make that variation in yellow color, like is shown in image bellow.

Have this function for that:

```<code>add_filter( 'woocommerce_variation_is_active',
'grey_out_variations_when_is_backorder', 10, 2 );
function grey_out_variations_when_is_backorder( $grey_out, $variation ) {

if ( ! $variation->is_in_stock() && $variation-
 >backorders_require_notification() )
$grey_out = false; // Here text variation need to be yellow.

return $grey_out;
}
</code>```

but dont resolved nothing, because grayout can get only 2 values, true or false. So i used this CSS:

```<code>.sbOptions li span.sbDisabled {
 color:red!important;
 }
.sbOptions li a {
color:green!important;
}
</code>```

so can control gray in and gray out variations only. No possiblity for third option that i want to make.  Want variations that is: “out of stock” + “allow, backorder but notify” = yellow background & can be selected. Currently that variations is in green colour, because i dont found a way how to handle colour for that variations. Thanks

答:
I don't have your code, but you can test this?
Use sub class, or check your class if they are affected or not in element inspector

.content {
background:gray;
padding:5px;
margin:5px 0;
}

.content div {
  margin:5px 0;
}

.content div.blue {
  color:blue;
}

.content div.red {
  color:red;
}

.content.test div {
  color:yellow !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
  <div class="red">Test</div>
  <div class="blue">Test</div>
  <div>Test</div>
</div>

<div class="content test">
  <div class="red">Test</div>
  <div class="blue">Test</div>
  <div>Test</div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
Have one problem that don t know how to resolve. Have product (XS variation) that is "non in stock" but have selected "Allow but notify customer" So want to make that variation in yellow color, like is shown in image bellow.

Have this function for that:

add_filter( 'woocommerce_variation_is_active',
'grey_out_variations_when_is_backorder', 10, 2 );
function grey_out_variations_when_is_backorder( $grey_out, $variation ) {

if ( ! $variation->is_in_stock() && $variation-
 >backorders_require_notification() )
$grey_out = false; // Here text variation need to be yellow.

return $grey_out;
}

but dont resolved nothing, because grayout can get only 2 values, true or false. So i used this CSS:

.sbOptions li span.sbDisabled {
 color:red!important;
 }
.sbOptions li a {
color:green!important;
}

so can control gray in and gray out variations only. No possiblity for third option that i want to make.  Want variations that is: “out of stock” + “allow, backorder but notify” = yellow background & can be selected. Currently that variations is in green colour, because i dont found a way how to handle colour for that variations. Thanks

Body:
I don't have your code, but you can test this?
Use sub class, or check your class if they are affected or not in element inspector

.content {
background:gray;
padding:5px;
margin:5px 0;
}

.content div {
  margin:5px 0;
}

.content div.blue {
  color:blue;
}

.content div.red {
  color:red;
}

.content.test div {
  color:yellow !important;
}

<div class="content">
  <div class="red">Test</div>
  <div class="blue">Test</div>
  <div>Test</div>
</div>

<div class="content test">
  <div class="red">Test</div>
  <div class="blue">Test</div>
  <div>Test</div>
</div>


问:
using sudo inside jupyter notebook's cell
I'm trying to make a tutorial for a platform inside a jupyter notebook

at some point I need to run a linux command inside a cell like this :

```<code>!sudo apt-get install blah
</code>```

but cant figure out how to enter the sudo pass , and I dont want to run jupyter notebook with sudo, any idea how to do this ?

答:
Update: I checked all the methods, all of them are working.

1:

Request password using getpass module which essentially hides input by user and then run sudo command in python.

```<code> import getpass
 import os

 password = getpass.getpass()
 command = "sudo -S apt-get update" #can be any command but don't forget -S as it enables input from stdin
 os.system('echo %s | %s' % (password, command))
</code>```

2:

```<code> import getpass
 import os

 password = getpass.getpass()
 command = "sudo -S apt-get update" # can be any command but don't forget -S as it enables input from stdin
 os.popen(command, 'w').write(password+'\n') # newline char is important otherwise prompt will wait for you to manually perform newline
</code>```

NOTE for above methods:

The field where you enter the password may not appear in the ipython
  notebook. It appears in the terminal window on a mac, and I imagine it
  will appear in a command shell on a PC. Even the result details would appear in the terminal.

3:

You can store your password in mypasswordfile file and just type in cell :

!sudo -S apt-get install blah < /pathto/mypasswordfile # again -S is important here

I would prefer this method if I want to view output of the command in jupyter notebook itself.

References:

Requesting password in IPython notebook

https://docs.python.org/3.1/library/getpass.html

Using sudo with Python script

Body:
I'm trying to make a tutorial for a platform inside a jupyter notebook

at some point I need to run a linux command inside a cell like this :

!sudo apt-get install blah

but cant figure out how to enter the sudo pass , and I dont want to run jupyter notebook with sudo, any idea how to do this ?

Body:
Update: I checked all the methods, all of them are working.

1:

Request password using getpass module which essentially hides input by user and then run sudo command in python.

 import getpass
 import os

 password = getpass.getpass()
 command = "sudo -S apt-get update" #can be any command but don't forget -S as it enables input from stdin
 os.system('echo %s | %s' % (password, command))

2:

 import getpass
 import os

 password = getpass.getpass()
 command = "sudo -S apt-get update" # can be any command but don't forget -S as it enables input from stdin
 os.popen(command, 'w').write(password+'\n') # newline char is important otherwise prompt will wait for you to manually perform newline

NOTE for above methods:

The field where you enter the password may not appear in the ipython
  notebook. It appears in the terminal window on a mac, and I imagine it
  will appear in a command shell on a PC. Even the result details would appear in the terminal.

3:

You can store your password in mypasswordfile file and just type in cell :

!sudo -S apt-get install blah < /pathto/mypasswordfile # again -S is important here

I would prefer this method if I want to view output of the command in jupyter notebook itself.

References:

Requesting password in IPython notebook

https://docs.python.org/3.1/library/getpass.html

Using sudo with Python script


问:
Should defined numbers be stored in a table within the database?
Imagine you have a table - lets contrive an example where this is Orders - which has a field named type, which may be only one of a few fixed values (lets say 0 or 1, for Quotation and Order).

Should all the possible values of type be represented by another table in the database (with just typeID and typeName columns?), and Orders made to reference the new table?

Or is it normal to leave these numbers as-is and have them documented outside the database?

If this is a "it depends" situation: What are the important implications of both options?

I have used the first option in a recent University assignement, but without really thinking about why - and looking back at the design now I'm wondering whether this is important.

I never once queried the reference table as part of my application - because I didn't "need" to - does this indicate the reference table is unneeded, or is this a flaw in my application because it should be checking the ref table (what for?)?

答:
I think the biggest difference is that when you include the reference tables with the "lookup" data in the database (even tho they will never be used by the application), it can serve well later to other developers when they work on the system. The advantage over the "document it in the documentations somewhere" is that keeping it in database forces you to update the reference tables when new values are used in the application. Written documentation tends to get out of sync over time.

Another point is that keeping the reference data in database might help in situations when some other team needs to hook up to your application on the database level (i.e. for some data mining, reporting etc).

ContentLicense: CC BY-SA 2.5


问:
how do I get images to flow as they do on google photos album view
I find it extremely difficult to believe the megabytes of css and javascript are required.

I have written a python program to read a yaml file with images for thumbnails and links to my google photo albums because they did away with picasaweb.google.com but kept all the albums.

I would be content to have four images per line scaling by %.  I can't even figure out why these images are stacked vertically and offset.

It would be nice to have this responsive and show different number of album covers depending on width, but scaling is fine.

           Why the indent

Why the indent

Nepal

The lake</figcaption

Chitwan, wild tigers and elephants</figcaption

Elephant Abuse</figcaption

    ```

答:
Figure is an element that has display: block property - so it fit one at each line. Try switching to div with h2 instead - that givers you more flexibility and better code understanding for web browsers and SEO.

Btw. you're not even closing </figcaption in snippet above.


问:
Failed to Autowire beans in a Java thread in Spring Boot
I successfully autowired beans and sent emails in my previous code. The code is as follow:

```<code>public class HomeController{
    @Autowired
    private MailConstructor mailConstructor;

    @Autowired
    private JavaMailSender mailSender;

    ...
    String token = UUID.randomUUID().toString();
    String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    SimpleMailMessage newEmail = mailConstructor.constructResetTokenEmail(appUrl, request.getLocale(), token, user);

    mailSender.send(newEmail);
    ...
}
</code>```

Now I want to send the email in a new thread and I wrote my code referring to this link:Why does Autowiring not function in a thread?
My new code is as follow:

```<code>public class EmailUtility {
@Autowired
private JavaMailSender mailSender;

public static SimpleMailMessage constructNormalEmail(String text, String subject, String toAddress, String fromAddr) {
    SimpleMailMessage email = new SimpleMailMessage();
    email.setTo(toAddress);
    email.setSubject(subject);
    email.setText(text);
    email.setFrom(fromAddr);
    return email;
}

public class SendEmail implements Runnable{
    private String subject;
    private String text;
    private String toAddr;
    private String fromAddr;

    public SendEmail(String subject, String text, String toAddr, String fromAddr){
        this.subject = subject;
        this.text = text;
        this.toAddr = toAddr;
        this.fromAddr = fromAddr;
    }

    @Override
    public void run() {
        SimpleMailMessage email = constructNormalEmail(text, subject, toAddr, fromAddr);
        mailSender.send(email);
    }
}
}
</code>```

But I got the following error:

```<code>exception in thread "Thread-5" java.lang.NullPointerException
</code>```

Both this error and the message presented by IntelliJ Could not autowire. No beans of 'JavaMailSender' type found indicates that the autowire fails.

What may be the cause of this error and how can I autowire a bean in a thread? Any suggestion will be appreciated.

=============================UPDATE=====================================
Solved this problem with the help of these guys. The problem is that I create the EmailUtility myself.
MY previous code is as follow:

```<code>//Wrong Version
Thread sendEmailThread = new Thread(new EmailUtility().new SendEmail(subject, text, toAddress, fromAddress));
</code>```

If I let Spring autowires the EmailUtility, then the code works:

```<code>//Correct Version
@Component
public class EmailUtility {
......
}

public class HomeController{

     @Autowired
     private EmailUtility emailUtility;
     ...
     Thread sendEmailThread = new Thread(emailUtility.new SendEmail(subject, text, toAddress));
     ...
}
</code>```

答:
EmailUtility most probably is not created by Spring, since it is not marked as @Service, @Component, @Controller, @Inject, etc. thats why Spring framework has no chance to inject (autowire) your implementation of JavaMailSender into EmailUtility instance.

Spring does some magic with classes named by a certain pattern, therefore your *Controller classes might be recognized by Spring as beans, but not *Utility class.

Body:
I successfully autowired beans and sent emails in my previous code. The code is as follow:

public class HomeController{
    @Autowired
    private MailConstructor mailConstructor;

    @Autowired
    private JavaMailSender mailSender;

    ...
    String token = UUID.randomUUID().toString();
    String appUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    SimpleMailMessage newEmail = mailConstructor.constructResetTokenEmail(appUrl, request.getLocale(), token, user);

    mailSender.send(newEmail);
    ...
}

Now I want to send the email in a new thread and I wrote my code referring to this link:Why does Autowiring not function in a thread?
My new code is as follow:

public class EmailUtility {
@Autowired
private JavaMailSender mailSender;

public static SimpleMailMessage constructNormalEmail(String text, String subject, String toAddress, String fromAddr) {
    SimpleMailMessage email = new SimpleMailMessage();
    email.setTo(toAddress);
    email.setSubject(subject);
    email.setText(text);
    email.setFrom(fromAddr);
    return email;
}

public class SendEmail implements Runnable{
    private String subject;
    private String text;
    private String toAddr;
    private String fromAddr;

    public SendEmail(String subject, String text, String toAddr, String fromAddr){
        this.subject = subject;
        this.text = text;
        this.toAddr = toAddr;
        this.fromAddr = fromAddr;
    }

    @Override
    public void run() {
        SimpleMailMessage email = constructNormalEmail(text, subject, toAddr, fromAddr);
        mailSender.send(email);
    }
}
}

But I got the following error:

exception in thread "Thread-5" java.lang.NullPointerException

Both this error and the message presented by IntelliJ Could not autowire. No beans of 'JavaMailSender' type found indicates that the autowire fails.

What may be the cause of this error and how can I autowire a bean in a thread? Any suggestion will be appreciated.

=============================UPDATE=====================================
Solved this problem with the help of these guys. The problem is that I create the EmailUtility myself.
MY previous code is as follow:

//Wrong Version
Thread sendEmailThread = new Thread(new EmailUtility().new SendEmail(subject, text, toAddress, fromAddress));

If I let Spring autowires the EmailUtility, then the code works:

//Correct Version
@Component
public class EmailUtility {
......
}

public class HomeController{

     @Autowired
     private EmailUtility emailUtility;
     ...
     Thread sendEmailThread = new Thread(emailUtility.new SendEmail(subject, text, toAddress));
     ...
}


问:
Find the issues of SQL
I got a questions from a test, it seems an concept question or logic question, so no data at all. Please read:

Assuming there's no syntax error and the column names and table names are correct, what's wrong with the MySQL query below?

-- FOR EVERY USER WE HAVE, this is supposed to return the number of messages they sent

```<code>select u.user_id, sum(case when um.message_id is not null then 1 else 0 end) as number_of_messages_sent
from users u left join
     users_messages um
     on um.user_id = u.user_id
where um.status = 'sent'
group by u.user_id;
</code>```

If anyone have any ideas, please help me.

答:
What Went Wrong:

your query supposes to get EVERY user we have but it is only returning user who has sent messages. This is because your WHERE clause filtered out the users who didn't send any messages. Let me illustrate this with an example.

Example:

I made some sample table with data using this code:

```<code>CREATE TABLE userz (
  user_id int,
) ;

INSERT INTO userz (user_id)
VALUES
(1),(2),(3)

CREATE TABLE userz_messages(
  message_id int,
  user_id int,
  status varchar(10)
)

INSERT INTO userz_messages (message_id,user_id,status)
VALUES
(1,1,'sent'),
(2,2,'sent'),
(3,3,'sent'),
(4,4,'notsend'),
(5,1,'sent'),
(6,2,'sent')
</code>```

userz_table:

```<code>user_id
-----------
1
2
3
</code>```

userz_message table:

```<code>message_id  user_id     status
----------- ----------- ----------
1           1           sent
2           2           sent
3           3           sent
4           4           notsend
5           1           sent
6           2           sent
</code>```

when we perform your query we get this as the result:

```<code>user_id      number_of_messages_sent
----------- -----------------------
1           2
2           2
3           1
</code>```

Notice user with user_id 4 is not in the result set? This is what's wrong with the query. It is not getting EVERY user.

Hope my example helps you get a better understanding of your problem

Title: Find the issues of SQL

Body:
I got a questions from a test, it seems an concept question or logic question, so no data at all. Please read:

Assuming there's no syntax error and the column names and table names are correct, what's wrong with the MySQL query below?

-- FOR EVERY USER WE HAVE, this is supposed to return the number of messages they sent

select u.user_id, sum(case when um.message_id is not null then 1 else 0 end) as number_of_messages_sent
from users u left join
     users_messages um
     on um.user_id = u.user_id
where um.status = 'sent'
group by u.user_id;

If anyone have any ideas, please help me.

Body:
What Went Wrong:

your query supposes to get EVERY user we have but it is only returning user who has sent messages. This is because your WHERE clause filtered out the users who didn't send any messages. Let me illustrate this with an example.

Example:

I made some sample table with data using this code:

CREATE TABLE userz (
  user_id int,
) ;

INSERT INTO userz (user_id)
VALUES
(1),(2),(3)

CREATE TABLE userz_messages(
  message_id int,
  user_id int,
  status varchar(10)
)

INSERT INTO userz_messages (message_id,user_id,status)
VALUES
(1,1,'sent'),
(2,2,'sent'),
(3,3,'sent'),
(4,4,'notsend'),
(5,1,'sent'),
(6,2,'sent')

userz_table:

user_id
-----------
1
2
3

userz_message table:

message_id  user_id     status
----------- ----------- ----------
1           1           sent
2           2           sent
3           3           sent
4           4           notsend
5           1           sent
6           2           sent

when we perform your query we get this as the result:

user_id      number_of_messages_sent
----------- -----------------------
1           2
2           2
3           1

Notice user with user_id 4 is not in the result set? This is what's wrong with the query. It is not getting EVERY user.

Hope my example helps you get a better understanding of your problem


答:
You can accomplish it like this

```<code>labels_1 = np.array([1,1,2,2,3])
labels_2 = np.array([1,1,2,2,3])
n = len(labels_1)
positive_pairs = [(i1+1, i2+n+1) for i1, l in enumerate(labels_1)
                                 for i2 in np.where(labels_2 == l)[0]]
</code>```

[(1,6),(1,7),(2,6),(2,7),...]

```<code>negative_pairs = [(i1+1, i2+n+1) for i1, l in enumerate(labels_1)
                                 for i2 in np.where(labels_2 != l)[0]]
</code>```

[(1,8),(1,9),(1,10),(2,8),...]

Though, I am not sure this is the most efficient way.

Title: Find pair of matches between an numpy array Python

Body:
You can accomplish it like this

labels_1 = np.array([1,1,2,2,3])
labels_2 = np.array([1,1,2,2,3])
n = len(labels_1)
positive_pairs = [(i1+1, i2+n+1) for i1, l in enumerate(labels_1)
                                 for i2 in np.where(labels_2 == l)[0]]

[(1,6),(1,7),(2,6),(2,7),...]

negative_pairs = [(i1+1, i2+n+1) for i1, l in enumerate(labels_1)
                                 for i2 in np.where(labels_2 != l)[0]]

[(1,8),(1,9),(1,10),(2,8),...]

Though, I am not sure this is the most efficient way.


问:
How to hide jTable at jFrame
How to hide jTable at jFrame in java GUI, not just hide the column, but entire jTable?

I was try to use table.setVisible(false), but just hide a column not entire table

答:
You cannot hide the table, but you can hide your panel containing the table
instead.

yourPanel.setVisible(false);

Whenever you want to show the table do yourPanel.setVisible(true);

Title: How to hide jTable at jFrame


问:
CSS - Background images
Probably very silly question, but since I am trying to put my website online using my domaine which I have recently purchased, the background image doesn't seem to load at all.

Any idea?

body {
  margin: 0;
  background-image: url("homepage1.jpg");
  background-size: cover;
  font-family: 'Parisienne', cursive;
  background-repeat: no-repeat;
}

.navbar {
  background-color: none;
  width: 100%;
  height: 30px;
  padding-top: 0;
  text-align: center;
}

.navbar a {
  padding: 20px;
  font-size: 2.0em;
  color: black;
  text-decoration: none;
}

.navbar a:hover:not(.active) {
  color: #B22222;
}

.homepage {
  padding-top: 15px;
}

#welcome {
  color: black;
  font-size: 30px;
  text-align: center;
}

#welcome h1 {
  font-size: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="homepage">
  <div class="navbar">
    Home
    Schedule
    Accommodations
    Travel
    Activities
    Contact
  </div>
  <div id="welcome">
    <h1>Tracey & Jonathan's Wedding</h1>
    <p>16 / 08 / 2018</p>
  </div>
</div></code>```

答:
Check out the css file location !
If it does't work, then press F12 And select Console After that take a screenshot and put it here.

Title: CSS - Background images

Body:
Probably very silly question, but since I am trying to put my website online using my domaine which I have recently purchased, the background image doesn't seem to load at all.

Any idea?

body {
  margin: 0;
  background-image: url("homepage1.jpg");
  background-size: cover;
  font-family: 'Parisienne', cursive;
  background-repeat: no-repeat;
}

.navbar {
  background-color: none;
  width: 100%;
  height: 30px;
  padding-top: 0;
  text-align: center;
}

.navbar a {
  padding: 20px;
  font-size: 2.0em;
  color: black;
  text-decoration: none;
}

.navbar a:hover:not(.active) {
  color: #B22222;
}

.homepage {
  padding-top: 15px;
}

#welcome {
  color: black;
  font-size: 30px;
  text-align: center;
}

#welcome h1 {
  font-size: 50px;
}

    Home
    Schedule
    Accommodations
    Travel
    Activities
    Contact

Tracey & Jonathan's Wedding

16 / 08 / 2018


问:
Shouldn't my nhibernate mapping take care of this? Error: not-null property reference a null or transient value
I have a database with 3 tables:

Project

Sponsor

ProjectSponsor

In my domain objects, i have an object Project which has a child property called Sponsors which is a list of ProjectSponsor objects, like this:

```<code> IList<ProjectSponsor> Sponsors;
</code>```

here is the Nhibernate Mapping code:

ProductMap:

```<code>HasMany(x => x.Sponsors).AsBag().Inverse().Cascade.AllDeleteOrphan();
</code>```

ProductSponsorMap:

```<code>References(x => x.Project).Not.Nullable();
References(x => x.Sponsor).Not.Nullable();
</code>```

here is my Domain Objects:

```<code>public class Project
{
    public virtual IList<ProjectSponsor> Sponsors { get; set; }
}

 public class ProjectSponsor
{
    public virtual Project Project { get; set; }
    public virtual Sponsor Sponsor { get; set; }
}
</code>```

ok . . now to my issue, when i try to add new Projects (with their associated projectsponsor) into the database.

Here is my code:

```<code>    foreach (Project project in newProjects)
   {
      Repository.Save(project);
      foreach (ProjectSponsor projectSponsor in project.Sponsors)
      {
           Repository.Save(projectSponsor);
      }
   }
</code>```

I am getting an exception on this line:

```<code>     Repository.Save(projectSponsor);
</code>```

saying that not-null property reference a null or transient value is trying to be saved:

projectSponsor.Project is the property that its complaining about.  I would have thought that would be set by default based on the nhibernate mapping.

do i really need to have an explicit piece of code that have this code:

```<code>projectSponsor.Project = project
</code>```

or is there anything wrong with my mapping files ?

答:
If you haven't set the projectSponsor.Project property (and no code here says you have) then it will have the default value of null which will violate the mapping condition you've placed.

NHibernate is just going to reflect the state of the objects and the state of the objects is - for want of a better word - broken as is. You could remove the Project property on the ProjectSponsor map and all would be well but you're losing functionality to do so because obviously the directionality of relationships in OO is the reverse of RDBM directionality.

I would expect something like:

```<code>public class ProjectSponsor
{
    // This is how you instantiate me!
    public ProjectSponsor(Project project, Sponsor sponsor)
    {
        this.Project = project;
        this.Sponsor = sponsor;
    }

    protected ProjectSponsor()
    {
        // I exist for NHibernates benefit only!
    }

    public virtual Project Project { get; set; }

    public virtual Sponsor Sponsor { get; set; }
}
</code>```

Body:
I have a database with 3 tables:

Project

Sponsor

ProjectSponsor

In my domain objects, i have an object Project which has a child property called Sponsors which is a list of ProjectSponsor objects, like this:

 IList<ProjectSponsor> Sponsors;

here is the Nhibernate Mapping code:

ProductMap:

HasMany(x => x.Sponsors).AsBag().Inverse().Cascade.AllDeleteOrphan();

ProductSponsorMap:

References(x => x.Project).Not.Nullable();
References(x => x.Sponsor).Not.Nullable();

here is my Domain Objects:

public class Project
{
    public virtual IList<ProjectSponsor> Sponsors { get; set; }
}

 public class ProjectSponsor
{
    public virtual Project Project { get; set; }
    public virtual Sponsor Sponsor { get; set; }
}

ok . . now to my issue, when i try to add new Projects (with their associated projectsponsor) into the database.

Here is my code:

    foreach (Project project in newProjects)
   {
      Repository.Save(project);
      foreach (ProjectSponsor projectSponsor in project.Sponsors)
      {
           Repository.Save(projectSponsor);
      }
   }

I am getting an exception on this line:

     Repository.Save(projectSponsor);

saying that not-null property reference a null or transient value is trying to be saved:

projectSponsor.Project is the property that its complaining about.  I would have thought that would be set by default based on the nhibernate mapping.

do i really need to have an explicit piece of code that have this code:

projectSponsor.Project = project

or is there anything wrong with my mapping files ?

Body:
If you haven't set the projectSponsor.Project property (and no code here says you have) then it will have the default value of null which will violate the mapping condition you've placed.

NHibernate is just going to reflect the state of the objects and the state of the objects is - for want of a better word - broken as is. You could remove the Project property on the ProjectSponsor map and all would be well but you're losing functionality to do so because obviously the directionality of relationships in OO is the reverse of RDBM directionality.

I would expect something like:

public class ProjectSponsor
{
    // This is how you instantiate me!
    public ProjectSponsor(Project project, Sponsor sponsor)
    {
        this.Project = project;
        this.Sponsor = sponsor;
    }

    protected ProjectSponsor()
    {
        // I exist for NHibernates benefit only!
    }

    public virtual Project Project { get; set; }

    public virtual Sponsor Sponsor { get; set; }
}


问:
How can I redirect a custom subdomain to a github-pages project when the domain itself is set to S3?
I have read several questions about custom domains pointing to a github-pages website. However, I could not find the answer for my case.

I have an apex domain (e.g. http://example.com) pointing to an S3
bucket.

I have a www redirection to this apex domain.

I have an existing organization project website on github pages that
I can access using an url like this:
http://ORGANIZATION.github.io/blog

I want to access that github-page hosted website using a subdomain, like blog.example.com while keeping my apex set to my S3 bucket.

Most of the answers I found were to redirect the domain apex to http://ORGANIZATION.github.io/ and access to the blog using "www.example.com/blog". It is not what I want.

Since ORGANIZATION.github.io/blog. is not a valid CNAME record, I can no use it as value for my sub domain CNAME record.

Is there a way to use a github pages organization project website with a custom subdomain?

答:
Since it can be complicated to figure this out when not familiar with domain names management, I will try to explain what can be and what cannot be done.

Every domain name has an apex, i.e. the domain name without subdomain.

Exemple: http://example.com

Note that www is a sub domain (http://www.example.com) that you can redirect to your apex.

With Github-Pages, with an organization account, you can only link the apex or a subdomain to a repo with a name formated as follow: orgname.github.io. You also need to set the domain in the repo settings.

If you have a repo with a different name (i.e. blog), it can be only available with an URL like this: http://example.com/blog

This is not what I want. So what I did was to create one organization per subdomain. I hope that it is not considered as an abuse to github-pages terms.

For example, I create a myorg_blog organization with a repo called myorg_blog.github.io that point to my subdomain blog.example.com. Same thing for the portfolio: another organization with a single repo.

Then I keep the apex pointing to S3, no changes to make on this part.


问:
NSGradient drawInBezierPath iOS equivalent
Is there an iOS equivalent to - (void)drawInBezierPath:(NSBezierPath *)path angle:(CGFloat)angle?

I need to draw a gradient inside a UIBezierPath and cannot get it to work. The gradient draws all over the screen.

答:
This example creates a gradient inside a UIBezierPath in Swift 3. It draws a slanting line with a green/white gradient.</p>

```<code>import UIKit

class DrawingView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.isOpaque = false
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func draw(_ rect: CGRect) {
        let startPoint = CGPoint(x:100, y:100)
        let endPoint = CGPoint(x: 300, y:400)

        let context = UIGraphicsGetCurrentContext()!
        context.setStrokeColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0);
        // create a line
        context.move(to: startPoint)
        context.addLine(to: endPoint)
        context.setLineWidth(4)
        // use the line created above as a clipping mask
        context.replacePathWithStrokedPath()
        context.clip()

        // create a gradient
        let locations: [CGFloat] = [ 0.0, 0.5 ]

        let colors = [UIColor.green.cgColor,
                      UIColor.white.cgColor]

        let colorspace = CGColorSpaceCreateDeviceRGB()

        let gradient = CGGradient(colorsSpace: colorspace,
                                  colors: colors as CFArray, locations: locations)

        let gradientStartPoint = CGPoint(x: rect.midX, y: rect.minY)
        let gradientEndPoint = CGPoint(x: rect.midX, y: rect.maxY)

        context.drawLinearGradient(gradient!,
                                    start: gradientStartPoint, end: gradientEndPoint,
                                    options: .drawsBeforeStartLocation)
        UIGraphicsEndImageContext()
    }

}
</code>```

Body:
This example creates a gradient inside a UIBezierPath in Swift 3. It draws a slanting line with a green/white gradient.

import UIKit

class DrawingView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.isOpaque = false
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func draw(_ rect: CGRect) {
        let startPoint = CGPoint(x:100, y:100)
        let endPoint = CGPoint(x: 300, y:400)

        let context = UIGraphicsGetCurrentContext()!
        context.setStrokeColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0);
        // create a line
        context.move(to: startPoint)
        context.addLine(to: endPoint)
        context.setLineWidth(4)
        // use the line created above as a clipping mask
        context.replacePathWithStrokedPath()
        context.clip()

        // create a gradient
        let locations: [CGFloat] = [ 0.0, 0.5 ]

        let colors = [UIColor.green.cgColor,
                      UIColor.white.cgColor]

        let colorspace = CGColorSpaceCreateDeviceRGB()

        let gradient = CGGradient(colorsSpace: colorspace,
                                  colors: colors as CFArray, locations: locations)

        let gradientStartPoint = CGPoint(x: rect.midX, y: rect.minY)
        let gradientEndPoint = CGPoint(x: rect.midX, y: rect.maxY)

        context.drawLinearGradient(gradient!,
                                    start: gradientStartPoint, end: gradientEndPoint,
                                    options: .drawsBeforeStartLocation)
        UIGraphicsEndImageContext()
    }

}


问:
Explanation of the Function that Defines strlen
I'm learning about pointers in c++.

I have researched and found the manual function that defines strlen to be something like this.

```<code>int strlen(const char *a){
    const char *b;
    for (b=a;*b;++b);
    return b-a;
}
</code>```

Would anyone be able to explain this block of code in plain english? In particular, why is *b set as the terminating condition in the for loop?

This is not an answer to homework. It's just a question that arose while I was researching. Thanks.

答:
This is a particularly terse piece of C code, with a for loop that does not have a body.

The idea is to set pointer b to the beginning of the string a, and keep advancing it until you hit character '\0', which indicates the end of the stirng (i.e. serves as null terminator). Nothing else needs to be done in that loop, hence its body is empty.

Once the loop is over, subtracting a from b yields the number of characters between the initial character of the string and its null terminator, i.e. the length of the string.

Here is a more readable way to write the same loop:

```<code>for (b=a ; *b != '\0' ; ++b) // Use explicit comparison to zero
    ;                        // Put semicolon on a separate line
</code>```

When C expression is used in a statement that requires a logical expression, an implicit comparison to zero is applied. Hence, *b != '\0' is the same as *b.

Body:
I'm learning about pointers in c++.

I have researched and found the manual function that defines strlen to be something like this.

int strlen(const char *a){
    const char *b;
    for (b=a;*b;++b);
    return b-a;
}

Would anyone be able to explain this block of code in plain english? In particular, why is *b set as the terminating condition in the for loop?

This is not an answer to homework. It's just a question that arose while I was researching. Thanks.

Body:
This is a particularly terse piece of C code, with a for loop that does not have a body.

The idea is to set pointer b to the beginning of the string a, and keep advancing it until you hit character '\0', which indicates the end of the stirng (i.e. serves as null terminator). Nothing else needs to be done in that loop, hence its body is empty.

Once the loop is over, subtracting a from b yields the number of characters between the initial character of the string and its null terminator, i.e. the length of the string.

Here is a more readable way to write the same loop:

for (b=a ; *b != '\0' ; ++b) // Use explicit comparison to zero
    ;                        // Put semicolon on a separate line

When C expression is used in a statement that requires a logical expression, an implicit comparison to zero is applied. Hence, *b != '\0' is the same as *b.


问:
KOA2+node+ejs Error: Can't set headers after they are sent
Use kOA2 + node js + ajax to grab the web page data and display the result information on the front page:

query.js

```<code>const superagent = require('superagent');
const charset = require('superagent-charset');
const cheerio = require('cheerio');

charset(superagent);

function Rate(from, to, queryNumber) {
    this.from = from;
    this.to = to;
    this.queryNumber = queryNumber;
}

module.exports = Rate;

Rate.query = function query(rate, callback) {
    let URL = 'http://qq.ip138.com/hl.asp?from=' + rate.from + '&to=' + rate.to + '&q=' + rate.queryNumber;
    superagent.get(URL)
       .charset('gbk')
       .end((err, sres)=> {
          if (err) {
              return next(err);
          }
          var $ = cheerio.load(sres.text);
          var queryResult = [];
          queryResult[0] = $(".rate td").eq(4).text();
          queryResult[1] = $(".rate td").eq(5).text();
          callback(null, queryResult);

       })
};
</code>```

index.js

```<code>const index = require('koa-router')();
const Rate = require('../models/query');

index.get('/s*', async (ctx, next) => {
    let rate = new Rate(ctx.query.from, ctx.query.to, ctx.query.queryNumber);
    await Rate.query(rate, (err, queryResult) => {
      if (err) {
         return next(err);
      } else {
         return ctx.render('query', {
                   title: '查询结果',
                   rate: queryResult[0],
                   amount: queryResult[1]
      });
      return next();
      }

    });
</code>```

when visit “/s*” page, appear：(Node: 808) UnhandledPromiseRejectionWarning: Unhandled hate rejection (rejection id: 1): Error: Can not set headers after they are sent. Error, and the page can not jump.

Tried a lot of ways, but still do not know where to return in advance.

Is now known, because after the end of ctx, but also to call render to write data. The The But that is not where to change. Pls Help me.

答:
Please update </p>

```<code>const index = require('koa-router')();
const Rate = require('../models/query');

index.get('/s*', async (ctx, next) => {
    let rate = new Rate(ctx.query.from, ctx.query.to, ctx.query.queryNumber);
    await Rate.query(rate, (err, queryResult) => {
      if (err) {
         return next(err);
      } else {
         return ctx.render('query', {
                   title: '查询结果',
                   rate: queryResult[0],
                   amount: queryResult[1]
      });
      return next();
      }

    });
</code>```

<p>to </p>

```<code>const index = require('koa-router')();
const Rate = require('../models/query');

index.get('/s*', async (ctx, next) => {
    let rate = new Rate(ctx.query.from, ctx.query.to, ctx.query.queryNumber);
    await Rate.query(rate, (err, queryResult) => {
      if (err) {
         return next(err);
      } else {
         return ctx.render('query', {
                   title: '查询结果',
                   rate: queryResult[0],
                   amount: queryResult[1]
      });
      }

    });
</code>```

Body:
Use kOA2 + node js + ajax to grab the web page data and display the result information on the front page:

query.js

const superagent = require('superagent');
const charset = require('superagent-charset');
const cheerio = require('cheerio');

charset(superagent);

function Rate(from, to, queryNumber) {
    this.from = from;
    this.to = to;
    this.queryNumber = queryNumber;
}

module.exports = Rate;

Rate.query = function query(rate, callback) {
    let URL = 'http://qq.ip138.com/hl.asp?from=' + rate.from + '&to=' + rate.to + '&q=' + rate.queryNumber;
    superagent.get(URL)
       .charset('gbk')
       .end((err, sres)=> {
          if (err) {
              return next(err);
          }
          var $ = cheerio.load(sres.text);
          var queryResult = [];
          queryResult[0] = $(".rate td").eq(4).text();
          queryResult[1] = $(".rate td").eq(5).text();
          callback(null, queryResult);

       })
};

index.js

const index = require('koa-router')();
const Rate = require('../models/query');

index.get('/s*', async (ctx, next) => {
    let rate = new Rate(ctx.query.from, ctx.query.to, ctx.query.queryNumber);
    await Rate.query(rate, (err, queryResult) => {
      if (err) {
         return next(err);
      } else {
         return ctx.render('query', {
                   title: '查询结果',
                   rate: queryResult[0],
                   amount: queryResult[1]
      });
      return next();
      }

    });

when visit “/s*” page, appear：(Node: 808) UnhandledPromiseRejectionWarning: Unhandled hate rejection (rejection id: 1): Error: Can not set headers after they are sent. Error, and the page can not jump.

Tried a lot of ways, but still do not know where to return in advance.

Is now known, because after the end of ctx, but also to call render to write data. The The But that is not where to change. Pls Help me.

Body:
Please update

const index = require('koa-router')();
const Rate = require('../models/query');

index.get('/s*', async (ctx, next) => {
    let rate = new Rate(ctx.query.from, ctx.query.to, ctx.query.queryNumber);
    await Rate.query(rate, (err, queryResult) => {
      if (err) {
         return next(err);
      } else {
         return ctx.render('query', {
                   title: '查询结果',
                   rate: queryResult[0],
                   amount: queryResult[1]
      });
      return next();
      }

    });

to

const index = require('koa-router')();
const Rate = require('../models/query');

index.get('/s*', async (ctx, next) => {
    let rate = new Rate(ctx.query.from, ctx.query.to, ctx.query.queryNumber);
    await Rate.query(rate, (err, queryResult) => {
      if (err) {
         return next(err);
      } else {
         return ctx.render('query', {
                   title: '查询结果',
                   rate: queryResult[0],
                   amount: queryResult[1]
      });
      }

    });


问:
How can I include a model association in a JSON response in Rails?
I've looked at similar posts but can't seem to quite figure it out.

I have the following function which works just fine. The Listing model has a foreign key called price_id which maps to the Price model and its price_range column. Price_id is returned as part of the message object in the JSON response.

How can I return the corresponding price_range value from the association instead of the price_id value (as part of the message obj, and keep the other attributes)?

```<code>def update
    @listing = Listing.find(params[:listing][:id])

    #if params were passed in for updating
    if @listing.update_attributes(params[:listing])
    #should we return the whole thing or just what's needed?
        json_response = {
             "success" => @listing.save, #save to DB and assign true/false based on success...
             "message" => @listing.attributes #USE attributes to show output the content of the @message obj, and not another object called "message"
        }

        respond_to do |format|
            #json response
            format.html { render:json => json_response }
            format.xml { render :xml => @listing }

            #normal response. Consider leaving this for now?
            #format.html { render :action => "detail" } #refresh this page, with new data in it. Consider trying to use redirect instead?
            #format.xml  { head :ok }
        end
    end #end if

end
</code>```

答:
If I understand correctly, you want to add @listing.price.price_range value to the "message" ?
If so, try this:

```<code>"message" => @listing.attributes[:price_range] = @listing.price.price_range
</code>```

Body:
I've looked at similar posts but can't seem to quite figure it out.

I have the following function which works just fine. The Listing model has a foreign key called price_id which maps to the Price model and its price_range column. Price_id is returned as part of the message object in the JSON response.

How can I return the corresponding price_range value from the association instead of the price_id value (as part of the message obj, and keep the other attributes)?

def update
    @listing = Listing.find(params[:listing][:id])

    #if params were passed in for updating
    if @listing.update_attributes(params[:listing])
    #should we return the whole thing or just what's needed?
        json_response = {
             "success" => @listing.save, #save to DB and assign true/false based on success...
             "message" => @listing.attributes #USE attributes to show output the content of the @message obj, and not another object called "message"
        }

        respond_to do |format|
            #json response
            format.html { render:json => json_response }
            format.xml { render :xml => @listing }

            #normal response. Consider leaving this for now?
            #format.html { render :action => "detail" } #refresh this page, with new data in it. Consider trying to use redirect instead?
            #format.xml  { head :ok }
        end
    end #end if

end

Body:
If I understand correctly, you want to add @listing.price.price_range value to the "message" ?
If so, try this:

"message" => @listing.attributes[:price_range] = @listing.price.price_range


问:
SQL Server: Can you combine/map 2 columns into 1 via stored procedure in SELECT statement itself?
Can you combine / map 2 columns into 1 via a stored procedure in a SELECT statement itself?

Something akin to:

```<code>SELECT
    (EXEC @TIMESPAN = #CREATE_24HR_TIMESPAN, [open], [closed]) AS TIMESPAN
FROM
    #TEMP
</code>```

To set the scene, I've got a table with a couple of columns with from time and to time with data resembling '7am' '8am'.

I've written a stored procedure to convert the strings to a 24hr clock format with range 0..23.

I call this twice and multiply the from time by 100 and add the to time, so, I'd end up with 708.

I want this because It's going to make it easy to create a Pivot Table later...

I want to know is there a way to include the EXEC inline with a SELECT statement?

I'm familiar with cursors as a solution, but was wondering if the SELECT is plausible.

答:
No, you cannot do what you want.  Stored procedures cannot be used in queries -- with the major exception being storing values into a table using insert.

Instead of a stored procedure, create a user-defined scalar function (see here).  From your description of the stored procedure, it should be easy to turn it into a function.

I mean, even that seems hardly necessary.  You could just do:

```<code>select datepart(hour, [open]) * 100 + datepart(hour, [closed])
</code>```

(assuming they are stored as time).  If they are strings:

```<code>select datepart(hour, convert(time, [open] )) * 100 + datepart(hour, convert(time, [closed]))
</code>```

Body:
Can you combine / map 2 columns into 1 via a stored procedure in a SELECT statement itself?

Something akin to:

SELECT
    (EXEC @TIMESPAN = #CREATE_24HR_TIMESPAN, [open], [closed]) AS TIMESPAN
FROM
    #TEMP

To set the scene, I've got a table with a couple of columns with from time and to time with data resembling '7am' '8am'.

I've written a stored procedure to convert the strings to a 24hr clock format with range 0..23.

I call this twice and multiply the from time by 100 and add the to time, so, I'd end up with 708.

I want this because It's going to make it easy to create a Pivot Table later...

I want to know is there a way to include the EXEC inline with a SELECT statement?

I'm familiar with cursors as a solution, but was wondering if the SELECT is plausible.

Body:
No, you cannot do what you want.  Stored procedures cannot be used in queries -- with the major exception being storing values into a table using insert.

Instead of a stored procedure, create a user-defined scalar function (see here).  From your description of the stored procedure, it should be easy to turn it into a function.

I mean, even that seems hardly necessary.  You could just do:

select datepart(hour, [open]) * 100 + datepart(hour, [closed])

(assuming they are stored as time).  If they are strings:

select datepart(hour, convert(time, [open] )) * 100 + datepart(hour, convert(time, [closed]))


问:
Python Discord BOT. Simple, but annoying error
I just discovered this site, and I wondered if someone could help me. I don't really know if this title is appropriate, but that'll do for the moment.

So, I've got a code that looks like this :

```<code>@client.command(pass_context=True)
async def member(self, *, member: discord.Member = None, role : discord.Role = None):
    if member is None:
        await client.say("You need to tag someone!")
    elif role is None:
        await client.say("You need to tag a role to add!")
    else:
        await client.add_roles(member, role)
        await client.say("Role added!")
</code>```

I think it's "working" quite well, because I do not see any errors when typing the !member @Dude command. The BOT just tells me that I need to tag a role to add. BUT! When I tag a role to add, then it doesn't work. In fact, the problem is, the BOT thinks that the role I tag is part of the name of the member. Maybe it will be better with the error.
The error I told you about is one the last line of this image.

As you can see, it says that the member wasn't found. But the second ID is supposed to be the role's one. What am I doing wrong? I'm really bad with discord.py so if someone could help me, it would be very nice of him! :)

(Also, sorry for my bad english and sorry if this is off-topic, it's just that I'm fed up with these errors, because I always get another when one is solved.)

EDIT : I just fixed this, but now I get the a perms error. "Forbidden: FORBIDDEN (status code: 403) : Missing Permissions"

答:
I just fixed this, but now I get the a perms error. "Forbidden: FORBIDDEN (status code: 403) : Missing Permissions"

Bot must have Manage Roles permission on server, and role to add must be lower then bot's top role

Body:
I just discovered this site, and I wondered if someone could help me. I don't really know if this title is appropriate, but that'll do for the moment.

So, I've got a code that looks like this :

@client.command(pass_context=True)
async def member(self, *, member: discord.Member = None, role : discord.Role = None):
    if member is None:
        await client.say("You need to tag someone!")
    elif role is None:
        await client.say("You need to tag a role to add!")
    else:
        await client.add_roles(member, role)
        await client.say("Role added!")

I think it's "working" quite well, because I do not see any errors when typing the !member @Dude command. The BOT just tells me that I need to tag a role to add. BUT! When I tag a role to add, then it doesn't work. In fact, the problem is, the BOT thinks that the role I tag is part of the name of the member. Maybe it will be better with the error.
The error I told you about is one the last line of this image.

As you can see, it says that the member wasn't found. But the second ID is supposed to be the role's one. What am I doing wrong? I'm really bad with discord.py so if someone could help me, it would be very nice of him! :)

(Also, sorry for my bad english and sorry if this is off-topic, it's just that I'm fed up with these errors, because I always get another when one is solved.)

EDIT : I just fixed this, but now I get the a perms error. "Forbidden: FORBIDDEN (status code: 403) : Missing Permissions"


问:
CSRF Token generate different one each GET method (Laravel 5.3 server & Ionic 2 client)
I'm making an application with Ionic 2 to login to Laravel 5.3 server. When i GET CSRF Token from Postman, I see that the CSRF Token will never change even how many time I GET (unless the session is ended). So I can login from Postman when Post the Token with username and password. But from my Ionic 2 app, each time I GET CSRF Token, the CSRF Token is change to an other one. So the CSRF verification always return error.

You can see the CSRF Token has been changed

My GET returned CSRF Token from Laravel server:

```<code>Route::get('api/csrf', function() {
    return Session::token();
});
</code>```

My GET method I do from Ionic app client:

```<code>token() {
    this._token = this.http.get('http://localhost:8000/api/csrf').map((res:Response) => res.text()).subscribe(data => {
        consoler.log(data);
    });
}
</code>```

I understand that the problem is I didn't save the Token right way or some thing with session cookie. If you guys have any idea, please help me! Thank you for read all ask!

p/s:
  1. My English is not good, so please forgive me if I have some mistake.
  2. I'm developing Cordova app with Ionic (Ionic tabs application, i think so) and API server with Laravel

答:
If you're developing a RESTful API, that authenticates via the Authorization header, then you don't need CSRF protection altogether.

CSRF occurs when another website makes a request to yours, and that website happens to be authenticated due to authentication being based on cookies or something similar

When authentication happens to be on an HTTP header, other websites simply can't make forms to do such a request, they don't have enough privileges to add a header to their request, and thus, requests will be unauthenticated and the user will be safe. If you store your authorization token in localStorage, then they can't access that either.

So basically, authenticate your API via the Authorization header and disable CSRF protection, and then you should be fine.

Body:
I'm making an application with Ionic 2 to login to Laravel 5.3 server. When i GET CSRF Token from Postman, I see that the CSRF Token will never change even how many time I GET (unless the session is ended). So I can login from Postman when Post the Token with username and password. But from my Ionic 2 app, each time I GET CSRF Token, the CSRF Token is change to an other one. So the CSRF verification always return error.

You can see the CSRF Token has been changed

My GET returned CSRF Token from Laravel server:

Route::get('api/csrf', function() {
    return Session::token();
});

My GET method I do from Ionic app client:

token() {
    this._token = this.http.get('http://localhost:8000/api/csrf').map((res:Response) => res.text()).subscribe(data => {
        consoler.log(data);
    });
}

I understand that the problem is I didn't save the Token right way or some thing with session cookie. If you guys have any idea, please help me! Thank you for read all ask!

p/s:
  1. My English is not good, so please forgive me if I have some mistake.
  2. I'm developing Cordova app with Ionic (Ionic tabs application, i think so) and API server with Laravel


问:
Searching unsorted array in perl?
I have an array with... lets say 100 elements. I want to check to see if any of the elements matches a particular string. For example:

@array = ('red','white','blue');

I also want to know if the array contains the string 'white' as one of the elements.
I know how to do this with a foreach loop and comparing each element, but... is there an easier (faster) way than looping through the whole array?

-Thanks

答:
You can use grep as:

```<code>@array = ('red','white','blue');
$key = 'white';
if (grep { $_ eq $key } @array) {
        print $key.' found';
}
</code>```

Title: Searching unsorted array in perl?

Body:
You can use grep as:

@array = ('red','white','blue');
$key = 'white';
if (grep { $_ eq $key } @array) {
        print $key.' found';
}


问:
How to use agents as keys in table of table extension?
I am using the table extension as variable owned by a breed of agents.
The content of this table contains values referred to agents of another agent-set (events).
As table keys, I use e-ids a list with the who numbers of each agent in events breed.
The following procedure initializes the tables:

```<code>to setup-tables
  ask walkers [
      set we-tfound table:make
      set we-interest table:make
      foreach e-ids [ [?] -> table:put we-tfound ? 0
                             table:put we-interest ? 1  ] ]
  ask links [
    set popularity table:make
    foreach e-ids [ [?] -> table:put popularity ? 0 ] ]
end
</code>```

The answer to others posts recommends not to use who numbers and iterate over agents by using, for example, construct ask agents [...].
However, I do not know how could be the best way to iterate over table:keys using agents or someway better than whos ids.

Thank you very much for your help

答:
Since agents can't be used as keys in tables, using who numbers is perfectly reasonable. The danger here is that if a turtle dies, you end up with an entry that doesn't actually correspond to an existing turtle. (This is also the reason agents are not allowed as keys in tables.) You can do is-turtle? turtle key to see if key corresponds to an existing turtle.

To convert table:keys back to an agentset, you can do:

```<code>turtle-set map turtle table:keys my-table
</code>```

Thus, to ask all the turtles that are keys in a table, you do:

```<code>ask turtle-set map turtle table:keys my-table [ do-stuff ]
</code>```

map turtle table:keys converts the list of who numbers to a list of turtles. turtle-set then converts that to an agentset.

Body:
I am using the table extension as variable owned by a breed of agents.
The content of this table contains values referred to agents of another agent-set (events).
As table keys, I use e-ids a list with the who numbers of each agent in events breed.
The following procedure initializes the tables:

to setup-tables
  ask walkers [
      set we-tfound table:make
      set we-interest table:make
      foreach e-ids [ [?] -> table:put we-tfound ? 0
                             table:put we-interest ? 1  ] ]
  ask links [
    set popularity table:make
    foreach e-ids [ [?] -> table:put popularity ? 0 ] ]
end

The answer to others posts recommends not to use who numbers and iterate over agents by using, for example, construct ask agents [...].
However, I do not know how could be the best way to iterate over table:keys using agents or someway better than whos ids.

Thank you very much for your help

Body:
Since agents can't be used as keys in tables, using who numbers is perfectly reasonable. The danger here is that if a turtle dies, you end up with an entry that doesn't actually correspond to an existing turtle. (This is also the reason agents are not allowed as keys in tables.) You can do is-turtle? turtle key to see if key corresponds to an existing turtle.

To convert table:keys back to an agentset, you can do:

turtle-set map turtle table:keys my-table

Thus, to ask all the turtles that are keys in a table, you do:

ask turtle-set map turtle table:keys my-table [ do-stuff ]

map turtle table:keys converts the list of who numbers to a list of turtles. turtle-set then converts that to an agentset.


问:
Python does not import seaborn-package, although installed
I've installed the package using conda install seaborn in my terminal. This stated that the package was already installed.

When I try to import Seaborn into my editor (I'm using Canopy) and run a simple program, I am met with the following error:

ImportError: No module named seaborn.

What is the reason for this and how can I solve it?

答:
Your anaconda-based installation of Python is not the same as the one Canopy uses. Try using Canopy's package manager:</p>

```<code>enpkg seaborn
</code>```

Body:
Your anaconda-based installation of Python is not the same as the one Canopy uses. Try using Canopy's package manager:

enpkg seaborn


问:
Make a custom function return nothing - not 0, not a blank string, but nothing
I have a custom function to be called from inside a spreadsheets' cell, that I want to return nothing in some cases. In other words, I want the cell with my function to be treated exactly like an empty cell (unless the function returns a value).

The closest I can get to doing that is returning an empty string "". Unfortunately a cell with a zero length string is not treated as empty by COUNTA or COUNTBLANK, and breaks mathematical formulas (eg 1 + "" = #VALUE).

Most of my attempts to return nothing cause a 0 to be returned, but this would be interpreted quite differently by the user.

What should I do?

Tried so far:

```<code>Returns 0:
    result = null
    result = VbEmpty
    result = Range("SomeCellKnownToBeEmpty")

Returns error:
    result = Nothing
</code>```

Answer: I'm now reasonably sure that this is not possible, and the best that can be done is to work around it.

Work around options:

Return a string "-blank-" and have a VBA macro delete the contents of any cell with "-blank-". A strange approach, but fits my needs. I'm doing this as one of the steps in preparing my workbook for publishing.

Return empty string and explicitly get other formulas in the sheet to treat "" as blank.

Return and display 0: Return 0 and use custom formatting to hide 0.

答:
You should return an error, like this:

```<code>Function retError()
    ' This function returns an error.
    retError = CVErr(vbValue)
End Function
</code>```

In a cell, it would display as #VALUE!, which has the benefit of propagating through formulae in spreadsheet (make sure user knows there's an error), while it doesn't get counted by some functions like COUNT. Note that COUNTA still counts those cells.

Body:
I have a custom function to be called from inside a spreadsheets' cell, that I want to return nothing in some cases. In other words, I want the cell with my function to be treated exactly like an empty cell (unless the function returns a value).

The closest I can get to doing that is returning an empty string "". Unfortunately a cell with a zero length string is not treated as empty by COUNTA or COUNTBLANK, and breaks mathematical formulas (eg 1 + "" = #VALUE).

Most of my attempts to return nothing cause a 0 to be returned, but this would be interpreted quite differently by the user.

What should I do?

Tried so far:

Returns 0:
    result = null
    result = VbEmpty
    result = Range("SomeCellKnownToBeEmpty")

Returns error:
    result = Nothing

Answer: I'm now reasonably sure that this is not possible, and the best that can be done is to work around it.

Work around options:

Return a string "-blank-" and have a VBA macro delete the contents of any cell with "-blank-". A strange approach, but fits my needs. I'm doing this as one of the steps in preparing my workbook for publishing.

Return empty string and explicitly get other formulas in the sheet to treat "" as blank.

Return and display 0: Return 0 and use custom formatting to hide 0.

Body:
You should return an error, like this:

Function retError()
    ' This function returns an error.
    retError = CVErr(vbValue)
End Function

In a cell, it would display as #VALUE!, which has the benefit of propagating through formulae in spreadsheet (make sure user knows there's an error), while it doesn't get counted by some functions like COUNT. Note that COUNTA still counts those cells.


问:
Travis-CI: Knitr Not Found in loadVignetteBuilder
I've been using travis-ci successfully so far but I'm having trouble when using travis-ci with R 3.4.0 at the vignette building step with the following error in the "building package" section:

```<code>* installing the package to build vignettes
* creating vignettes ... ERROR
Error in loadVignetteBuilder(vigns$pkgdir) :
  vignette builder 'knitr' not found
Calls: <Anonymous> -> loadVignetteBuilder
Execution halted
</code>```

When I run R-CMD-check locally it passes and I don't get any errors

Here's the current .travis.yml

```<code>language: R
sudo: false
install:
  - R -e "0" --args --bootstrap-packrat
cache:
  directories:
    - $TRAVIS_BUILD_DIR/packrat/src
    - $TRAVIS_BUILD_DIR/packrat/lib
  packages: true

r_packages:
    - covr

after_success:
    - Rscript -e 'library(covr); codecov()'
</code>```

DESCRIPTION has the vignette line in it:

```<code>VignetteBuilder: knitr
</code>```

knitr is also in my packrat.lock file and packrat is used for the build in .travis.yml.

I've tried the following to no avail:

added knitr to the r_packages in .travis.yml

added knitr to the Imports in DESCRIPTION

added r_check_args: "--no-vignettes" to travis.yml in the hopes of skipping the vignette building step.

added packrat call in travis.yml from install to before_install

I'm pretty knew to building R packages, never mind travis-ci so I'm not sure if I understand why the vignette builder would not have access to the knitr package.

Repo: https://github.com/cormac85/datakindr

Travis: https://travis-ci.org/cormac85/datakindr

答:
One potential problem involves the 'Imports' and/or 'Suggests' sections in your description file.

dplyr needs to be in your suggests, if not imports.

See Hadley's 2015 O'Reilly book, R Packages:

Common problems:

The vignette builds interactively, but when checking, it fails with an error about a missing package that you know is installed. This means that you’ve forgotten to declare that dependency in the DESCRIPTION (usually it should go in Suggests).

Body:
I've been using travis-ci successfully so far but I'm having trouble when using travis-ci with R 3.4.0 at the vignette building step with the following error in the "building package" section:

* installing the package to build vignettes
* creating vignettes ... ERROR
Error in loadVignetteBuilder(vigns$pkgdir) :
  vignette builder 'knitr' not found
Calls: <Anonymous> -> loadVignetteBuilder
Execution halted

When I run R-CMD-check locally it passes and I don't get any errors

Here's the current .travis.yml

language: R
sudo: false
install:
  - R -e "0" --args --bootstrap-packrat
cache:
  directories:
    - $TRAVIS_BUILD_DIR/packrat/src
    - $TRAVIS_BUILD_DIR/packrat/lib
  packages: true

r_packages:
    - covr

after_success:
    - Rscript -e 'library(covr); codecov()'

DESCRIPTION has the vignette line in it:

VignetteBuilder: knitr

knitr is also in my packrat.lock file and packrat is used for the build in .travis.yml.

I've tried the following to no avail:

added knitr to the r_packages in .travis.yml

added knitr to the Imports in DESCRIPTION

added r_check_args: "--no-vignettes" to travis.yml in the hopes of skipping the vignette building step.

added packrat call in travis.yml from install to before_install

I'm pretty knew to building R packages, never mind travis-ci so I'm not sure if I understand why the vignette builder would not have access to the knitr package.

Repo: https://github.com/cormac85/datakindr

Travis: https://travis-ci.org/cormac85/datakindr


问:
Run Batch File in VS2008
Is it possible to run a batch file as a menu item in studio 2008?</p>

答:
Run batch files in VS Solution Explorer directly

This is much better than having external tool since you can execute a batch file simply by double clicking on it in solution explorer just as if you were opening a code file. I've written a blog post about it that will help you lots to configure it and of course use it.

A sidenote

You've asked this question 2 years ago, but I see that nobody mentioned this technique so I'm providing this answer for any future reference. I hope it gets upvoted, so it will be near the top for readers to see.

OwnerDisplayName: Chane

Title: Run Batch File in VS2008

LastEditorDisplayName: Nath


问:
How to properly set width of a div within li
I'm trying to give my div inside a li a width value and the div's border has the width I want, but the text I have in that div is ignoring that width and it seems to be inheriting the container width. It's just the text that is doing that, though.

I don't usually work with li tags, so I don't really know what the problem is.

This is basically the HTML I'm working with:

           ...

```

<p>This is the CSS:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
    margin:0 auto;
    width: 900px;
    height: 500px;
    box-sizing:border-box;
    position:relative;
    right: 160px;
    -webkit-user-select: none;
    user-select:none;
}

#container div.inner {
    position:relative;
    overflow:hidden;
    padding:0;
    margin:0;
}

#container div.inner ul {
    white-space:nowrap;
    position:relative;
    left:0; top:0;
    list-style:none;
    font-size:0;
    padding:0;
    margin:0;
    float:left!important;
    width:auto!important;
    height:auto!important;
}

#container ul li {
    display:inline-block;
    margin-top:20px;
    margin-bottom:200px;
    margin-left:-45px; margin-right:-30px;
    -webkit-transform:scale(0.6);
    transform:scale(0.6);
    -webkit-transition:-webkit-transform 0.5s;
    transition:transform 0.5s;
    box-sizing:content-box;
    text-align:center;
    vertical-align:middle;
    padding:0;
    position:relative;
    list-style:none;
    backface-visibility:hidden;

}

#container ul li.active {
    -webkit-transform:scale(1);
    transform:scale(1);
    background-color:transparent;
}

      #container ul li.active .desc {
      display: block;
}

      .desc {
    display: none;
    width: 310px!important;
    height: 200px;
    border: 1px solid #fff;
    position: relative;
    right: 350px;
    top: 275px;
    color: #fff;
    font-family: Arial;
    font-size: 11px;
    padding: 15px;
    text-align: justify;
      }

#container .img {
    width: 200px;
    height: 320px;
    background-size:contain;
    background-repeat:no-repeat;
    background-position:center center;
    display:block;
    position:absolute;
    font-size:0;
    cursor:inherit;
    transition:all linear 0.4s;
}</code>```

答:
There seems to be a lot of CSS here that is conflicting. Are you sure you need to use '!important' in so many places?

It's hard to tell what's happening but my feeling is that using position:absolute and float is breaking things.

Also, your div inside the li ("desc") is set to display:block at some point.
Try changing it to inline or inline-block depending on what you need it to look like.

```<code>#container ul li.active .desc {
      display: block;
}
</code>```

Then after this you are trying to set a width when it is display:none...

```<code>.desc {
     display: none;
     width: 310px!important;
     ...
</code>```

This is probably not showing up because if the display:block taking precedence, because you have been more specific with your selectors. Try doing the same for the .desc section:

```<code>#container ul li .desc {
     display: none;
     width: 310px!important;
     ...
</code>```

If you can supply a working Jsfiddle or code snippet so we can see what you are trying to achieve that would help.

I'd also like to rewrite this for you so that you can see there is probably a much easier way to accomplish your layout without all of the conflicts.

Body:
I'm trying to give my div inside a li a width value and the div's border has the width I want, but the text I have in that div is ignoring that width and it seems to be inheriting the container width. It's just the text that is doing that, though.

I don't usually work with li tags, so I don't really know what the problem is.

This is basically the HTML I'm working with:

           ...

This is the CSS:

#container {
    margin:0 auto;
    width: 900px;
    height: 500px;
    box-sizing:border-box;
    position:relative;
    right: 160px;
    -webkit-user-select: none;
    user-select:none;
}

#container div.inner {
    position:relative;
    overflow:hidden;
    padding:0;
    margin:0;
}

#container div.inner ul {
    white-space:nowrap;
    position:relative;
    left:0; top:0;
    list-style:none;
    font-size:0;
    padding:0;
    margin:0;
    float:left!important;
    width:auto!important;
    height:auto!important;
}

#container ul li {
    display:inline-block;
    margin-top:20px;
    margin-bottom:200px;
    margin-left:-45px; margin-right:-30px;
    -webkit-transform:scale(0.6);
    transform:scale(0.6);
    -webkit-transition:-webkit-transform 0.5s;
    transition:transform 0.5s;
    box-sizing:content-box;
    text-align:center;
    vertical-align:middle;
    padding:0;
    position:relative;
    list-style:none;
    backface-visibility:hidden;

}

#container ul li.active {
    -webkit-transform:scale(1);
    transform:scale(1);
    background-color:transparent;
}

      #container ul li.active .desc {
      display: block;
}

      .desc {
    display: none;
    width: 310px!important;
    height: 200px;
    border: 1px solid #fff;
    position: relative;
    right: 350px;
    top: 275px;
    color: #fff;
    font-family: Arial;
    font-size: 11px;
    padding: 15px;
    text-align: justify;
      }

#container .img {
    width: 200px;
    height: 320px;
    background-size:contain;
    background-repeat:no-repeat;
    background-position:center center;
    display:block;
    position:absolute;
    font-size:0;
    cursor:inherit;
    transition:all linear 0.4s;
}

Body:
There seems to be a lot of CSS here that is conflicting. Are you sure you need to use '!important' in so many places?

It's hard to tell what's happening but my feeling is that using position:absolute and float is breaking things.

Also, your div inside the li ("desc") is set to display:block at some point.
Try changing it to inline or inline-block depending on what you need it to look like.

#container ul li.active .desc {
      display: block;
}

Then after this you are trying to set a width when it is display:none...

.desc {
     display: none;
     width: 310px!important;
     ...

This is probably not showing up because if the display:block taking precedence, because you have been more specific with your selectors. Try doing the same for the .desc section:

#container ul li .desc {
     display: none;
     width: 310px!important;
     ...

If you can supply a working Jsfiddle or code snippet so we can see what you are trying to achieve that would help.

I'd also like to rewrite this for you so that you can see there is probably a much easier way to accomplish your layout without all of the conflicts.


问:
Firebase event in different class
I'm building simple Android app to learn Java coding. Because app is pretty good I want to publish it on Google Play and track what users do inside of it. But I stuck on Firebase event integration. I have MainActivity.java where I call with this:

```<code>mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
mFirebaseAnalytics.setAnalyticsCollectionEnabled(true);
</code>```

Now I have buttons which I want to track in different class, Buttons.java

```<code>        Play.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {

            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                if (MusicPlayer.playerStatus) {
                    mediaPlayer.stop();
                    MainActivity.getStartOrStopBtn().setImageResource(R.drawable.play);
                } else if (LoadingAnimation.hasEnded()) {
                    try {
                        MusicList.next(0, mainListLocation, mainRadioName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return true;
        }
    });
</code>```

Here I must include code below but I can not figure out how to:

```<code>Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, id);
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, name);
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT,
bundle);
</code>```

Can someone explain me on beginner level how to include this Firebase event tracking on that specific button which is in different class?

Thanks in advance!

答:
You can just get the instance again in the second class:</p>

```<code>mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, id);
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, name);
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
</code>```

Title: Firebase event in different class

Body:
I'm building simple Android app to learn Java coding. Because app is pretty good I want to publish it on Google Play and track what users do inside of it. But I stuck on Firebase event integration. I have MainActivity.java where I call with this:

mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
mFirebaseAnalytics.setAnalyticsCollectionEnabled(true);

Now I have buttons which I want to track in different class, Buttons.java

        Play.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {

            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                if (MusicPlayer.playerStatus) {
                    mediaPlayer.stop();
                    MainActivity.getStartOrStopBtn().setImageResource(R.drawable.play);
                } else if (LoadingAnimation.hasEnded()) {
                    try {
                        MusicList.next(0, mainListLocation, mainRadioName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return true;
        }
    });

Here I must include code below but I can not figure out how to:

Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, id);
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, name);
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT,
bundle);

Can someone explain me on beginner level how to include this Firebase event tracking on that specific button which is in different class?

Thanks in advance!

Body:
You can just get the instance again in the second class:

mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, id);
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, name);
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);


问:
Periodic reload of data from server in Angular 2/4
I want to create an efficient mechanism for reloading data from server, for my Angular 4 app.

My service:

```<code>@Injectable()
export class MyService {
    getData(): Observable<string> {
        // return observable for fetching data from server
    }
}
</code>```

My component:

```<code>@Component({
    selector: 'my-component',
    templateUrl: './mytemplate.html'
})
export class MyComponent {
    myString$: Observable<string>;

    constructor(private service: MyService) {
        this.myString$ = service.getData();
    }
}
</code>```

My template:

```<code><div>
    <p>{{myString$ | aysnc}}</p>
</div>
</code>```

myString$ is an observable for a string that is loaded from the server.

MyComponent can be loaded as multiple different instances (myComponent1, myComponent2...).

As I understood, by doing myString$ | aysnc, my component is technically subscribed to myString$ opn component initializtion, and unsubscribed when component is destroyed.

I want to be able to reload data from the server periodically and emit it to multiple subscribers (components). Since I do not know how much time a request to the server might take, Observable.interval() isn't good for me, as if the interval is less time than the time for the request to return, then I'll have a problem of sending a new request before the previous has returned.
I guess I want to block the emission of another request until the previous one "resolved".

What should getData() return so that I can achieve that?

Another requirement I have is to not send requests when there are no subscribers, and restart the periodic requests when a new subscriber subscribes - is it possible using .share()?

Thanks!

答:
If I understood correctly, a solution to your problem would be to wait for the request to finish and then do the new ones? If that's the case you can use concatMap. With concatMap every emission will have to wait for the delayed previous emission to complete before the next one.

Here's an example:

```<code>let a = Rx.Observable.from(["data1","data2","data3","data4"]);
let b = Rx.Observable.fromEvent(document, 'click').map(x=>"asyncData");
let c = b.merge(a).concatMap(val => Rx.Observable.of(val).delay(1000))

c.subscribe(x=>console.log(x));
</code>```

Here you have a stream of data being emitted every second, and every time you click you get new data. This new data will be added at the end of the stream every second.

So you would get something like this:

second1 --> "data1"

second2 --> "data2"

(mouse click event)

second3 --> "data3"

second4 --> "data4"

second5 --> "asyncData"

Did that help?

Body:
I want to create an efficient mechanism for reloading data from server, for my Angular 4 app.

My service:

@Injectable()
export class MyService {
    getData(): Observable<string> {
        // return observable for fetching data from server
    }
}

My component:

@Component({
    selector: 'my-component',
    templateUrl: './mytemplate.html'
})
export class MyComponent {
    myString$: Observable<string>;

    constructor(private service: MyService) {
        this.myString$ = service.getData();
    }
}

My template:

{{myString$ | aysnc}}

myString$ is an observable for a string that is loaded from the server.

MyComponent can be loaded as multiple different instances (myComponent1, myComponent2...).

As I understood, by doing myString$ | aysnc, my component is technically subscribed to myString$ opn component initializtion, and unsubscribed when component is destroyed.

I want to be able to reload data from the server periodically and emit it to multiple subscribers (components). Since I do not know how much time a request to the server might take, Observable.interval() isn't good for me, as if the interval is less time than the time for the request to return, then I'll have a problem of sending a new request before the previous has returned.
I guess I want to block the emission of another request until the previous one "resolved".

What should getData() return so that I can achieve that?

Another requirement I have is to not send requests when there are no subscribers, and restart the periodic requests when a new subscriber subscribes - is it possible using .share()?

Thanks!

Body:
If I understood correctly, a solution to your problem would be to wait for the request to finish and then do the new ones? If that's the case you can use concatMap. With concatMap every emission will have to wait for the delayed previous emission to complete before the next one.

Here's an example:

let a = Rx.Observable.from(["data1","data2","data3","data4"]);
let b = Rx.Observable.fromEvent(document, 'click').map(x=>"asyncData");
let c = b.merge(a).concatMap(val => Rx.Observable.of(val).delay(1000))

c.subscribe(x=>console.log(x));

Here you have a stream of data being emitted every second, and every time you click you get new data. This new data will be added at the end of the stream every second.

So you would get something like this:

second1 --> "data1"

second2 --> "data2"

(mouse click event)

second3 --> "data3"

second4 --> "data4"

second5 --> "asyncData"

Did that help?


问:
Get text between two integers Javascript
```<code>var string = "454 blah bah 78";
</code>```

How can I get the text between 454 and 78 when those two numbers are random? Like

```<code>var string = "randnumber blah bah randnumber2";
</code>```

Note those numbers will always be integers and 2-3 characters long.

答:
Check this following code:</p>

```<code>var reg = /^\d{2,3}([^\d]+)\d{2,3}$/
var a = "454 blah bah 78";
var txt = reg.exec(a)[1];
console.log(txt);
</code>```

Body:
var string = "454 blah bah 78";

How can I get the text between 454 and 78 when those two numbers are random? Like

var string = "randnumber blah bah randnumber2";

Note those numbers will always be integers and 2-3 characters long.

Body:
Check this following code:

var reg = /^\d{2,3}([^\d]+)\d{2,3}$/
var a = "454 blah bah 78";
var txt = reg.exec(a)[1];
console.log(txt);


答:
You can try the below code</p>

```<code>var temp = someString.split(' ');
var output = '';
if(temp.length > 2){ // min must have 1 word in between any 2 numbers...
    var number1 = parseInt(temp[0]);
    for(var i = 1; i < temp.length -1; i++){
        if(i > 1) output += ' ';
        output += temp[i];
    }
    var number2 = parseInt(temp[temp.length-1]);
}
console.log('String in between: '+output);
console.log('Number 1: '+number1);
console.log('Number 2: '+number2);
</code>```

Title: Get text between two integers Javascript

Body:
You can try the below code

var temp = someString.split(' ');
var output = '';
if(temp.length > 2){ // min must have 1 word in between any 2 numbers...
    var number1 = parseInt(temp[0]);
    for(var i = 1; i < temp.length -1; i++){
        if(i > 1) output += ' ';
        output += temp[i];
    }
    var number2 = parseInt(temp[temp.length-1]);
}
console.log('String in between: '+output);
console.log('Number 1: '+number1);
console.log('Number 2: '+number2);


问:
Export is not defined
I'm getting this error:

Uncaught ReferenceError: exports is not defined

It seems like this question has been asked and answered several times. This is an example of this question being asked.

The only problem I'm having is that I can't find the tsconfig.ts file people keep mentioning in their answers. There's no such file in VS solution.

I'm using Visual Studio 2017 Enterprise Edition.

EDIT

I define all the common types in a file called CommonTypes.ts

```<code>class ddlData {
    ctrId: string;
    id: string;
}

interface ISelectedIdsObj {
    facilityId: number;
    AllCk: boolean;
    AllSelected: boolean;
    Ids: number[];
    totalItems: number;
}

//More classes and intefaces here...

export { ddlData, ISelectedIdsObj, IPaginationData, IHeaderColumn, ISelectedListItem }
</code>```

This is how I call it

```<code>/// <reference path="../typings/jquery/jquery.d.ts" />

//import { ddlData, ISelectedIdsObj, IPaginationData, IHeaderColumn, ISelectedListItem } from '../Commons/CommonTypes'
</code>```

I'm getting the Uncaught ReferenceError: exports is not defined at line 3.

EDIT 2

I've created 2 typescript files: test1 and test2.

This is test2:

```<code>export const x = 1;
</code>```

and this is test1:

```<code>/// <reference path="../typings/jquery/jquery.d.ts" />

import { x } from './Test2'

$(function () {
   alert(x);
});
</code>```

I'm still getting the same error: Uncaught ReferenceError: exports is not defined at Test1.js:3

答:
Since you have clarified that the issue is occurring in browser, it is easy to fix.
As you don't have created tsconfig.json file in your solution, your project is compiled with default configuration in VS. i.e. it will use CommonJS for as target module. More info about tsconfig.json can be read here.

This is the actual reason behind the error. Web browsers don't support CommonJS by default. The same issue will occur with require(...) also. You will need to use either module loaders such as RequireJS or amd or you can use packaging tools such as webpack or browserify which does this for you. Webpack is easy to configure and diverse packaging tool that has gained lot of popularity.

See SO answer

Title: Export is not defined

Body:
I'm getting this error:

Uncaught ReferenceError: exports is not defined

It seems like this question has been asked and answered several times. This is an example of this question being asked.

The only problem I'm having is that I can't find the tsconfig.ts file people keep mentioning in their answers. There's no such file in VS solution.

I'm using Visual Studio 2017 Enterprise Edition.

EDIT

I define all the common types in a file called CommonTypes.ts

class ddlData {
    ctrId: string;
    id: string;
}

interface ISelectedIdsObj {
    facilityId: number;
    AllCk: boolean;
    AllSelected: boolean;
    Ids: number[];
    totalItems: number;
}

//More classes and intefaces here...

export { ddlData, ISelectedIdsObj, IPaginationData, IHeaderColumn, ISelectedListItem }

This is how I call it

/// <reference path="../typings/jquery/jquery.d.ts" />

//import { ddlData, ISelectedIdsObj, IPaginationData, IHeaderColumn, ISelectedListItem } from '../Commons/CommonTypes'

I'm getting the Uncaught ReferenceError: exports is not defined at line 3.

EDIT 2

I've created 2 typescript files: test1 and test2.

This is test2:

export const x = 1;

and this is test1:

/// <reference path="../typings/jquery/jquery.d.ts" />

import { x } from './Test2'

$(function () {
   alert(x);
});

I'm still getting the same error: Uncaught ReferenceError: exports is not defined at Test1.js:3


答:
I don't know about conda but it probably installed Seaborn in a directory other than Python's directory. Try installing it with pip instead.

pip install Seaborn

Title: Python does not import seaborn-package, although installed

Body:
I've installed the package using conda install seaborn in my terminal. This stated that the package was already installed.

When I try to import Seaborn into my editor (I'm using Canopy) and run a simple program, I am met with the following error:

ImportError: No module named seaborn.

What is the reason for this and how can I solve it?