问:
Does anyone have a better way to do this? Im just learning how to play around with CSS
The image is the goal. I need to position each color correctly within the box. It must also be in the center of the browser. The result I got is exactly what the image is just with words. I'm really looking for a better way to do this because I kind of had to guess the left and bottom pixels. I also know it could have been done better and would really love to learn how.

.border{
  border: 2px solid black;
  width: 500px;
  height: 700px;
  margin:25px 450px;
  padding: 1px;
}

#one {
  background: red;
  height:100px;
}

#two{
 background: yellow;
 height:600px;
 width:100px;
}

#three {
  background: blue;
  height:550px;
  width:300px;
  position: relative;
  left: 100px;
  bottom: 600px;
}

#four{
  background: yellow;
  height: 600px;
  width:100px;
  position: relative;
  left:400px;
  bottom: 1150px;
}

#five{
  background: green;
  height:50px;
  width:300px;
  position: relative;
  left: 100px;
  bottom: 1200px;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>   <div class="border">
    <div id="one">One</div>
    <div id="two">Two</div>
    <div id="three">Three</div>
    <div id="four">Four</div>
    <div id="five">Five</div>
   </div></code>```

答:
Personally I'd opt for using percentage-based measurements, so that you only need to update the width and height on .border itself. For the .border, I've gone with vw and vh units for the width and height respectively, so that the size of the table adjusts based on the size of the viewport.

Note that you'll also probably want to make use of classes instead of IDs so you can have more than one table. I've used classes in my example, and also replaced the names to make the location identifiers more obvious.

I'd also opt for creating a container for the #middle and #bottom elements, considering them to be a single 'column'. This way, you can make use of float to align the #left, #middle_container and #right columns next to each other, without having to worry about the width of #bottom.

You can center the entire thing by adding margin: 0 auto to .border, which is shorthand for stating that there shouldn't be any vertical margins, and that the horizontal margins should be automatically calculated (which horizontally centers the element in question).

This can be seen in the following:

.border {
  border: 2px solid black;
  width: 50vw;
  height: 100vh;
  padding: 1px;
  margin: 0 auto;
}

.top {
  background: red;
  width: 100%;
  height: 20%;
}

.left,
.middle_container,
.right {
  float: left;
}

.left {
  background: yellow;
  width: 20%;
  height: 80%;
}

.middle_container {
  width: 60%;
  height: 80%;
}

.middle {
  background: blue;
  height: 80%;
}

.bottom {
  background: green;
  height: 20%;
  bottom: 0;
}

.right {
  background: yellow;
  width: 20%;
  height: 80%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="border">
    <div class="top">Top</div>
    <div class="left">Left</div>
    <div class="middle_container">
      <div class="middle">Middle</div>
      <div class="bottom">Bottom</div>
    </div>
    <div class="right">Right</div>
  </div>
</body></code>```

Hope this helps! :)

Body:
The image is the goal. I need to position each color correctly within the box. It must also be in the center of the browser. The result I got is exactly what the image is just with words. I'm really looking for a better way to do this because I kind of had to guess the left and bottom pixels. I also know it could have been done better and would really love to learn how.

.border{
  border: 2px solid black;
  width: 500px;
  height: 700px;
  margin:25px 450px;
  padding: 1px;
}

#one {
  background: red;
  height:100px;
}

#two{
 background: yellow;
 height:600px;
 width:100px;
}

#three {
  background: blue;
  height:550px;
  width:300px;
  position: relative;
  left: 100px;
  bottom: 600px;
}

#four{
  background: yellow;
  height: 600px;
  width:100px;
  position: relative;
  left:400px;
  bottom: 1150px;
}

#five{
  background: green;
  height:50px;
  width:300px;
  position: relative;
  left: 100px;
  bottom: 1200px;
 }

One

Two

Three

Four

Five

Body:
Personally I'd opt for using percentage-based measurements, so that you only need to update the width and height on .border itself. For the .border, I've gone with vw and vh units for the width and height respectively, so that the size of the table adjusts based on the size of the viewport.

Note that you'll also probably want to make use of classes instead of IDs so you can have more than one table. I've used classes in my example, and also replaced the names to make the location identifiers more obvious.

I'd also opt for creating a container for the #middle and #bottom elements, considering them to be a single 'column'. This way, you can make use of float to align the #left, #middle_container and #right columns next to each other, without having to worry about the width of #bottom.

You can center the entire thing by adding margin: 0 auto to .border, which is shorthand for stating that there shouldn't be any vertical margins, and that the horizontal margins should be automatically calculated (which horizontally centers the element in question).

This can be seen in the following:

.border {
  border: 2px solid black;
  width: 50vw;
  height: 100vh;
  padding: 1px;
  margin: 0 auto;
}

.top {
  background: red;
  width: 100%;
  height: 20%;
}

.left,
.middle_container,
.right {
  float: left;
}

.left {
  background: yellow;
  width: 20%;
  height: 80%;
}

.middle_container {
  width: 60%;
  height: 80%;
}

.middle {
  background: blue;
  height: 80%;
}

.bottom {
  background: green;
  height: 20%;
  bottom: 0;
}

.right {
  background: yellow;
  width: 20%;
  height: 80%;
}

<body>
  <div class="border">
    <div class="top">Top</div>
    <div class="left">Left</div>
    <div class="middle_container">
      <div class="middle">Middle</div>
      <div class="bottom">Bottom</div>
    </div>
    <div class="right">Right</div>
  </div>
</body>

Hope this helps! :)


来源: stackexchange

问:
calling a getter method from multiple methods in a different class than the getter
I'm in the process of learning Java and trying to use OOP style programming. The problem I'm having is that when I attempt to call a getter method in one class, for another class, it only works within the method that I create an object in and I'm calling from. My question is: Is it possible to call a getter from multiple methods in a different class than the getter method class? If so, how do I go about it?

Thanks!

答:
if I am not mistake you wanna try call different methods from different classes right?

```<code>public class A {
    public void getMethodFromClassA(){
       ....
    }
}

public class B {
   public void getMethodFromClassB(){
     ........
   }
}
</code>```

call the method

```<code>public class C {

    A a = new A();
    B b = new B();

   private void methodCaller(){

      a.getMethodFromClassA();
      b.getMethodFromClassB();
   }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
if I am not mistake you wanna try call different methods from different classes right?

public class A {
    public void getMethodFromClassA(){
       ....
    }
}

public class B {
   public void getMethodFromClassB(){
     ........
   }
}

call the method

public class C {

    A a = new A();
    B b = new B();

   private void methodCaller(){

      a.getMethodFromClassA();
      b.getMethodFromClassB();
   }
}


问:
matlab command obtain best fit of form $y(t)=a_1+a_2*t+a_3*sin(t) $
Is there a matlab command obtain best fit of form y(t)=a_1+a_2*t+a_3*sin(t) ???

Cannot find a command because of the sine function

thank you!!

答:
```<code>fh = @(a,t) a(1) + a(2) * t + a(3) * sin(t);
a = [2 -1 3];
x = ...;
y = ...;

fit = lsqcurvefit(fh,a,x,y);

figure();
plot(x,y,'ko',x,fh(a,x),'b-');
title('Result');
legend('Data','Fitted');
</code>```

Reference to official documentation with examples:

https://mathworks.com/help/optim/ug/lsqcurvefit.html

Body:
fh = @(a,t) a(1) + a(2) * t + a(3) * sin(t);
a = [2 -1 3];
x = ...;
y = ...;

fit = lsqcurvefit(fh,a,x,y);

figure();
plot(x,y,'ko',x,fh(a,x),'b-');
title('Result');
legend('Data','Fitted');

Reference to official documentation with examples:

https://mathworks.com/help/optim/ug/lsqcurvefit.html


问:
adding two dictionaries of ints
I think I have the right idea of solving this function, but it's not getting the desired result shown in the docstring i test it. Can anyone please help me fix this?</p>

```<code>def add_dicts(d1, d2):
'''(dict, dict) -> dict
Parameters d1 and d2 are dicts where each key is an int and each value is an
int. Return dict d1 with the contents of d2 added to d1. More concisely, if
key k is in d1 and in d2, update d1[k] to be the sum of d1[k] and d2[k]. If
d2 has a key that is not in d1, add the key value pair from d2 to d1.
>>> d1 = {1:1, 2:1, 3:2}
>>> d2 = {1:3, 3:1, 4:1}
>>> d = add_dicts(d1, d2)
>>> d == {1:4, 2:1, 3:3, 4:1}
True
'''
for (key, value) in d1.items():
    if key in d1 and key in d2:
        d1[key] = d1[key] + d2[key]
        if key in d2 and key not in d1:
            d1[key] = {key: value}
return d1
</code>```

答:
You can use the dict.get function to use a default value of 0 when the key is not found in d1:

```<code>for key, val in d2.items():
    d1[key] = d1.get(key, 0) + val
</code>```

Title: adding two dictionaries of ints

Body:
I think I have the right idea of solving this function, but it's not getting the desired result shown in the docstring i test it. Can anyone please help me fix this?

def add_dicts(d1, d2):
'''(dict, dict) -> dict
Parameters d1 and d2 are dicts where each key is an int and each value is an
int. Return dict d1 with the contents of d2 added to d1. More concisely, if
key k is in d1 and in d2, update d1[k] to be the sum of d1[k] and d2[k]. If
d2 has a key that is not in d1, add the key value pair from d2 to d1.
>>> d1 = {1:1, 2:1, 3:2}
>>> d2 = {1:3, 3:1, 4:1}
>>> d = add_dicts(d1, d2)
>>> d == {1:4, 2:1, 3:3, 4:1}
True
'''
for (key, value) in d1.items():
    if key in d1 and key in d2:
        d1[key] = d1[key] + d2[key]
        if key in d2 and key not in d1:
            d1[key] = {key: value}
return d1

Body:
You can use the dict.get function to use a default value of 0 when the key is not found in d1:

for key, val in d2.items():
    d1[key] = d1.get(key, 0) + val


答:
To center your art you will need to add position,top,left,margin-top, and margin-bottom. to .border;

```<code>.border{
      position:fixed; /*or absolute*/
      top:50%; /* add this */
      left:50%; /* add this */
      margin-top:-350px; /*half of your height*/
      margin-left:-250px; /*half of your width*/
      border: 2px solid black;
      width: 500px;
      height: 700px;
      padding: 1px;
}
</code>```

.border{
  position:fixed;
  top:50%;
  left:50%;
  margin-top:-350px;
  margin-left:-250px;
  border: 2px solid black;
  width: 500px;
  height: 700px;
  padding: 1px;
}

#one {
  background: red;
  height:100px;
}

#two{
 background: yellow;
 height:600px;
 width:100px;
}

#three {
  background: blue;
  height:550px;
  width:300px;
  position: relative;
  left: 100px;
  bottom: 600px;
}

#four{
  background: yellow;
  height: 600px;
  width:100px;
  position: relative;
  left:400px;
  bottom: 1150px;
}

#five{
  background: green;
  height:50px;
  width:300px;
  position: relative;
  left: 100px;
  bottom: 1200px;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="border">
    <div id="one">One</div>
    <div id="two">Two</div>
    <div id="three">Three</div>
    <div id="four">Four</div>
    <div id="five">Five</div>
   </div></code>```

Title: Does anyone have a better way to do this? Im just learning how to play around with CSS

Body:
To center your art you will need to add position,top,left,margin-top, and margin-bottom. to .border;

.border{
      position:fixed; /*or absolute*/
      top:50%; /* add this */
      left:50%; /* add this */
      margin-top:-350px; /*half of your height*/
      margin-left:-250px; /*half of your width*/
      border: 2px solid black;
      width: 500px;
      height: 700px;
      padding: 1px;
}

.border{
  position:fixed;
  top:50%;
  left:50%;
  margin-top:-350px;
  margin-left:-250px;
  border: 2px solid black;
  width: 500px;
  height: 700px;
  padding: 1px;
}

#one {
  background: red;
  height:100px;
}

#two{
 background: yellow;
 height:600px;
 width:100px;
}

#three {
  background: blue;
  height:550px;
  width:300px;
  position: relative;
  left: 100px;
  bottom: 600px;
}

#four{
  background: yellow;
  height: 600px;
  width:100px;
  position: relative;
  left:400px;
  bottom: 1150px;
}

#five{
  background: green;
  height:50px;
  width:300px;
  position: relative;
  left: 100px;
  bottom: 1200px;
 }

<div class="border">
    <div id="one">One</div>
    <div id="two">Two</div>
    <div id="three">Three</div>
    <div id="four">Four</div>
    <div id="five">Five</div>
   </div>


问:
Can't add objects to an array after initializing the array
I'm trying to initialize an array of objects with predetermined values but I get "Object reference not set to an instance of an object".

I don't understand the cause of the problem since I'm initializing properly and then I'm adding values to the array.

The main is:

```<code>Sorteo P=new Sorteo();
P.Predetermined();
</code>```

Class Sorteo:

```<code>// Atribute
private ClassA[] A;
int count=0;

// Methods
public Sorteo()
{
    A=new ClassA[2];
}
public void Add(ClassA a)
{
    A[count]=a;
    count++;
}
public void PredeterminedValues()
{
    A[0].Add(new ClassB("SomeString1"));
    A[1].Add(new ClassB("SomeString2"));
}
</code>```

答:
You're dealing with an array of reference types, not a value type.

In the following line:

```<code>    A = new ClassA[2];
    //[0] -> null
    //[1] -> null
</code>```

you have indeed initialized an array which holds reference objects of type ClassA.

In this case it actually holds two variables of type ClassA, but each of them is going to be set to null (since you have't initialized those), and therefore when you try to reference them the exception Object reference not set to an instance of an object is going to be thrown.

Solution?

Add this after initializing your array

```<code>A[0] = new ClassA(); // not null anymore
A[1] = new ClassA(); // not null anymore
</code>```

Body:
I'm trying to initialize an array of objects with predetermined values but I get "Object reference not set to an instance of an object".

I don't understand the cause of the problem since I'm initializing properly and then I'm adding values to the array.

The main is:

Sorteo P=new Sorteo();
P.Predetermined();

Class Sorteo:

// Atribute
private ClassA[] A;
int count=0;

// Methods
public Sorteo()
{
    A=new ClassA[2];
}
public void Add(ClassA a)
{
    A[count]=a;
    count++;
}
public void PredeterminedValues()
{
    A[0].Add(new ClassB("SomeString1"));
    A[1].Add(new ClassB("SomeString2"));
}

Body:
You're dealing with an array of reference types, not a value type.

In the following line:

    A = new ClassA[2];
    //[0] -> null
    //[1] -> null

you have indeed initialized an array which holds reference objects of type ClassA.

In this case it actually holds two variables of type ClassA, but each of them is going to be set to null (since you have't initialized those), and therefore when you try to reference them the exception Object reference not set to an instance of an object is going to be thrown.

Solution?

Add this after initializing your array

A[0] = new ClassA(); // not null anymore
A[1] = new ClassA(); // not null anymore


问:
Create WCF Data Service for use in service host
I have a service application that host several WCF endpoints through different bindings. I want now to host a WCF Data Service in the same service Host. This post makes me believe it's possible. However, every single example on how to create a WCF Data Service creates it from inside an ASP.NET Web project, not a Class Library or Service Application. In fact, the WCF Data Service doesn't even show up in the Add New Item when selected from one of these project types.

My question is how do I create a WCF Data Service inside a Class Library, that will be called by a service host, that's already hosting several other WCF endpoints? The link I already referenced shows me how to host the Data Service after it's created, but since it doesn't show up as an option of the Add New Item, I'm kinna stuck.

答:
Yes, you can host a WCF Data Service in your own assembly - with a few little tricks.

Here's how:

put your data model (EF Data Model) into its own assembly, let's call it DataModel

create a new class library project (call it MyDataServiceHost)

add a few references:

your DataModel assembly with the data layer

System.ServiceModel

System.ServiceModel.Web

System.Data.Services.Client

System.Data.Services - you cannot pick this from the usual Add Reference dialog under the .NET category - you need to browse for the assembly file. Find the directory C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0 (or C:\Program Files (x86)\... on a 64-bit machine) and pick the System.Data.Services.dll inside it

add a new class to that class library and call it e.g. YourDataService.cs - it will look something like this:

```<code>using System.Data.Services;
using System.Data.Services.Common;

using DataModel;

namespace MyDataServiceHost
{
    public class YourDataService : DataService<YourModelEntities>
    {
        // This method is called only once to initialize service-wide policies.
        public static void InitializeService(DataServiceConfiguration config)
        {
            // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
            // Examples:
            config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
        }
    }
}
</code>```

You can name the class anything you like, and it has to derive from DataService<T> where T is the name of your data model; if you're using Entity Framework, it's the name of your object context class - typically something like (database)Entities or whatever you picked when you created the EDM

add another class to your new project, call it MyDataServiceHost.cs and it will look something like this:

```<code>using System;
using System.Data.Services;

using DataModel;

namespace MyDataServiceHost
{
    public class MyDataServiceHost
    {
        public static void LaunchDataService(string baseAddress)
        {
            Uri[] baseAddresses = new Uri[1];
            baseAddresses[0] = new Uri(baseAddress);

            using(DataServiceHost host = new DataServiceHost(typeof(YourDataService), baseAddresses))
            {
                host.Open();
                Console.WriteLine("DataService up and running.....");

                Console.ReadLine();
                host.Close();
            }
        }
    }
}
</code>```

It instantiates a DataServiceHost, which is derived from WebServiceHost (which in turn is derived from ServiceHost) and it will spin up the WCF Data Service runtime for you.

now you can start up your WCF Data Service from any app using:

```<code>MyDataServiceHost.LaunchDataService("http://localhost:4444/YourService");
</code>```

last thing to remember: the app that you use to launch the WCF Data Service must have the connection string (the EDM connection string, if you're using Entity Framework) in its app.config (or web.config) in order for this to work!

ContentLicense: CC BY-SA 2.5

Body:
Yes, you can host a WCF Data Service in your own assembly - with a few little tricks.

Here's how:

put your data model (EF Data Model) into its own assembly, let's call it DataModel

create a new class library project (call it MyDataServiceHost)

add a few references:

your DataModel assembly with the data layer

System.ServiceModel

System.ServiceModel.Web

System.Data.Services.Client

System.Data.Services - you cannot pick this from the usual Add Reference dialog under the .NET category - you need to browse for the assembly file. Find the directory C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0 (or C:\Program Files (x86)\... on a 64-bit machine) and pick the System.Data.Services.dll inside it

add a new class to that class library and call it e.g. YourDataService.cs - it will look something like this:

using System.Data.Services;
using System.Data.Services.Common;

using DataModel;

namespace MyDataServiceHost
{
    public class YourDataService : DataService<YourModelEntities>
    {
        // This method is called only once to initialize service-wide policies.
        public static void InitializeService(DataServiceConfiguration config)
        {
            // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
            // Examples:
            config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
        }
    }
}

You can name the class anything you like, and it has to derive from DataService<T> where T is the name of your data model; if you're using Entity Framework, it's the name of your object context class - typically something like (database)Entities or whatever you picked when you created the EDM

add another class to your new project, call it MyDataServiceHost.cs and it will look something like this:

using System;
using System.Data.Services;

using DataModel;

namespace MyDataServiceHost
{
    public class MyDataServiceHost
    {
        public static void LaunchDataService(string baseAddress)
        {
            Uri[] baseAddresses = new Uri[1];
            baseAddresses[0] = new Uri(baseAddress);

            using(DataServiceHost host = new DataServiceHost(typeof(YourDataService), baseAddresses))
            {
                host.Open();
                Console.WriteLine("DataService up and running.....");

                Console.ReadLine();
                host.Close();
            }
        }
    }
}

It instantiates a DataServiceHost, which is derived from WebServiceHost (which in turn is derived from ServiceHost) and it will spin up the WCF Data Service runtime for you.

now you can start up your WCF Data Service from any app using:

MyDataServiceHost.LaunchDataService("http://localhost:4444/YourService");

last thing to remember: the app that you use to launch the WCF Data Service must have the connection string (the EDM connection string, if you're using Entity Framework) in its app.config (or web.config) in order for this to work!


问:
AWS gives us Amazon MQ but how can I trigger a Lambda?
Superb news about the Amazon MQ service but now the question arises on how I can trigger a Lambda function (Node.js) on a message on a specific Queue?

I was thinking if I somehow can get a SNS topic posted on a message PUT or some other trigger that can fire a Lambda to consume the message from the Queue...

Any suggestions?

答:
There isn't a native way to do this.  Amazon's managed ActiveMQ service is simply a managed deployment of ActiveMQ running in EC2.  It has no integration with other services.

You'd need to write a queue consumer and have it running on a server and listening to the queue on ActiveMQ and publishing those messages to SNS or invoking the Lambda function directly via the Lambda API, etc.

(At least for now.)


问:
SQL Server Percent Difference is Greater than Value
I have the following table structures:

table c_alert:

```<code>|dynamic|symbol|price_usd|
--------------------------
|5      |BTC   |13000   |
</code>```

table c_current:

```<code>|symbol|price_usd|
------------------
|BTC   |13600   |
</code>```

I have this query:

```<code>SELECT dbo.c_alert.symbol, dbo.c_alert.price_usd AS alert_price, dbo.c_current.price_usd AS current_price, (dbo.c_current.price_usd - dbo.c_alert.price_usd) * 100.0 / dbo.c_alert.price_usd AS pct_diff, dbo.c_alert.dynamic AS pct
FROM dbo.c_alert INNER JOIN
     dbo.c_current
     ON dbo.c_alert.symbol = dbo.c_current.symbol AND
        dbo.c_alert.dynamic > (dbo.c_current.price_usd - dbo.c_alert.price_usd) * 100.0 / dbo.c_alert.price_usd
</code>```

Which returns this:

```<code>|symbol|alert_price|current_price|pct_diff|dynamic|
-----------------------------------------------
|BTC   |13000      |13613.3000   |4.7     |5   |
</code>```

Not very strong with financial queries...Basically I would like to know when the price difference between alert_price and current_price are equal to or greater than value in the dynamic column as a boolean.  So where the difference is equal or greater than 5% show True, else False.  That dynamic value (integer) could change for each row in the c_alert table.  Hope someone can provide a solution to the query.

答:
Use table aliases so your query is easier to write and to read.  Then just use a case:

```<code>SELECT a.symbol, a.price_usd AS alert_price,
       c.price_usd AS current_price,
       (c.price_usd - a.price_usd) * 100.0 / a.price_usd AS pct_diff,
       a.dynamic AS pct,
       (case when (a.price_usd - c.price_used) > a.dynamic
             then 'true' else 'false'
        end) as flag
FROM dbo.c_alert a INNER JOIN
     dbo.c_current c
     ON a.symbol = c.symbol AND
        a.dynamic > (c.price_usd - a.price_usd) * 100.0 / a.price_usd;
</code>```

SQL Server doesn't have a boolean type, so this uses a string.  You can use 0 and 1 instead.

Body:
I have the following table structures:

table c_alert:

|dynamic|symbol|price_usd|
--------------------------
|5      |BTC   |13000   |

table c_current:

|symbol|price_usd|
------------------
|BTC   |13600   |

I have this query:

SELECT dbo.c_alert.symbol, dbo.c_alert.price_usd AS alert_price, dbo.c_current.price_usd AS current_price, (dbo.c_current.price_usd - dbo.c_alert.price_usd) * 100.0 / dbo.c_alert.price_usd AS pct_diff, dbo.c_alert.dynamic AS pct
FROM dbo.c_alert INNER JOIN
     dbo.c_current
     ON dbo.c_alert.symbol = dbo.c_current.symbol AND
        dbo.c_alert.dynamic > (dbo.c_current.price_usd - dbo.c_alert.price_usd) * 100.0 / dbo.c_alert.price_usd

Which returns this:

|symbol|alert_price|current_price|pct_diff|dynamic|
-----------------------------------------------
|BTC   |13000      |13613.3000   |4.7     |5   |

Not very strong with financial queries...Basically I would like to know when the price difference between alert_price and current_price are equal to or greater than value in the dynamic column as a boolean.  So where the difference is equal or greater than 5% show True, else False.  That dynamic value (integer) could change for each row in the c_alert table.  Hope someone can provide a solution to the query.

Body:
Use table aliases so your query is easier to write and to read.  Then just use a case:

SELECT a.symbol, a.price_usd AS alert_price,
       c.price_usd AS current_price,
       (c.price_usd - a.price_usd) * 100.0 / a.price_usd AS pct_diff,
       a.dynamic AS pct,
       (case when (a.price_usd - c.price_used) > a.dynamic
             then 'true' else 'false'
        end) as flag
FROM dbo.c_alert a INNER JOIN
     dbo.c_current c
     ON a.symbol = c.symbol AND
        a.dynamic > (c.price_usd - a.price_usd) * 100.0 / a.price_usd;

SQL Server doesn't have a boolean type, so this uses a string.  You can use 0 and 1 instead.


问:
How do I sum up all remaing amount after get max value from array?
I hesitated to this question either should I ask or not. I think that this is much more logical question. But, I can't really figure it out.

I have a array that may include

```<code>$programFees = [100,200,100,500,800,800]
</code>```

I can get max value from this array using max($programFees). If I have 2 max value like 800,800, I want to take one only. I realized that php max can solve this.

But, I want to sum up all remaining amount from that array.

e.g

```<code>$maxProgramFees = max($programFees);
//I got 800 and remaining amount is [100,200,100,500,800]
</code>```

My total amount should be 1700. Which approach should I use to get this amount?

答:
Sort the array, grab the largest, then shift the array to get the remainder values. Add those values

```<code><?php
$programFees = [100, 200, 100, 500, 800, 800];
rsort($programFees); //sort high -> low

$highest = $programFees[0]; // 800
array_shift($programFees); // remove the highest value

$sum = array_sum($programFees); // 1700
</code>```

rsort() documentation

array_shift() documentation

array_sum() documentation

Body:
I hesitated to this question either should I ask or not. I think that this is much more logical question. But, I can't really figure it out.

I have a array that may include

$programFees = [100,200,100,500,800,800]

I can get max value from this array using max($programFees). If I have 2 max value like 800,800, I want to take one only. I realized that php max can solve this.

But, I want to sum up all remaining amount from that array.

e.g

$maxProgramFees = max($programFees);
//I got 800 and remaining amount is [100,200,100,500,800]

My total amount should be 1700. Which approach should I use to get this amount?

Body:
Sort the array, grab the largest, then shift the array to get the remainder values. Add those values

<?php
$programFees = [100, 200, 100, 500, 800, 800];
rsort($programFees); //sort high -> low

$highest = $programFees[0]; // 800
array_shift($programFees); // remove the highest value

$sum = array_sum($programFees); // 1700

rsort() documentation

array_shift() documentation

array_sum() documentation


问:
how do I access the main class's stage? + Can I pass functions as arguments like this?
There are two files in my actionscript project named "TestAPP", TestAPP.as and Draggable.as

TestAPP.as:

```<code>
    package {
 import flash.display.Sprite;
 import flash.display.Stage;

 public class TestAPP extends Sprite
 {
  var _mainStage:Stage;
  public function TestAPP()//This is where we test the UI components.
  {

   var sp:Sprite = new Sprite();
   _mainStage = stage;
   _mainStage.addChild(sp);
   sp.graphics.beginFill(0x00FF00);
   sp.graphics.drawCircle(0,0,10);
   sp.graphics.endFill();
   sp.x = 50;
   sp.y = 50;
   var draggable1:Draggable = new draggable(sp,_mainStage,limitingfunc);
  }
  public function limitingfunc(x:Number,y:Number):int{
   return 0;
  }

 }
}
</code>```

And for the draggable.as:

```<code>
package
{
 import flash.display.Sprite;
 import flash.display.Stage;
 import flash.events.MouseEvent;

 public class Draggable
 {
  private var _limitingFunc:Function;
  private var _which:Sprite;
  private var _MouseSavedX:Number;
  private var _MouseSavedY:Number;

  private var _stage:Stage;
  public function Draggable(which:Sprite,stage:Stage,limitingfunc:Function)
  {
   _limitingFunc = limitingfunc;
   _which = which;
   _stage = stage;
   _which.addEventListener(MouseEvent.MOUSE_DOWN,begin_drag);

  }
  //limiting func: returns 0 when the object is free to move that place.
  //returns -1 when the user wants to block X coordinate changes (but maintain Y free)
  //returns -2 when the user wants to block Y ...
  //returns -3 or less when the user wants to block both X and Y from changing.
  //returns
  private function Return_0(x:Number = 0,y:Number = 0):int{
   return 0;
  }
  private function begin_drag(ev:MouseEvent):void{
   var xTo:Number = _stage.mouseX - _MouseSavedX + _which.x;
   var yTo:Number = _stage.mouseY - _MouseSavedY + _which.y;
   var limitingFuncReturnValue:int = _limitingFunc(xTo,yTo);
   if(limitingFuncReturnValue == 0){//free to move.
    _which.x = xTo;
    _which.y = yTo;
   }
   else if(limitingFuncReturnValue == -1){//free to move Y
    _which.y = yTo;
   }
   else if(limitingFuncReturnValue == -2){
    _which.y = yTo;
   }
   //else:do nothing.
  }
 }
}
</code>```

In "my actionscript theory", I'm supposed to see a circle that follows the mouse when I click it. (The draggable is not fully implemented) But the circle doesn't even budge :(

...I've been trying to figure out how to access the main class's stage property. I've googled for it, but still no progress.

Please help this helpless newb!!! I'll really appreciate your help:)
Thank you!

答: You're implementing your 2nd class as "draggable", when you named it (and it has to be named) "Draggable" with an upper case. Change it and see if that works. You seem to be passing in the parent classes stage correctly though. </p>

Body:
There are two files in my actionscript project named "TestAPP", TestAPP.as and Draggable.as

TestAPP.as:

    package {
 import flash.display.Sprite;
 import flash.display.Stage;

 public class TestAPP extends Sprite
 {
  var _mainStage:Stage;
  public function TestAPP()//This is where we test the UI components.
  {

   var sp:Sprite = new Sprite();
   _mainStage = stage;
   _mainStage.addChild(sp);
   sp.graphics.beginFill(0x00FF00);
   sp.graphics.drawCircle(0,0,10);
   sp.graphics.endFill();
   sp.x = 50;
   sp.y = 50;
   var draggable1:Draggable = new draggable(sp,_mainStage,limitingfunc);
  }
  public function limitingfunc(x:Number,y:Number):int{
   return 0;
  }

 }
}

And for the draggable.as:

package
{
 import flash.display.Sprite;
 import flash.display.Stage;
 import flash.events.MouseEvent;

 public class Draggable
 {
  private var _limitingFunc:Function;
  private var _which:Sprite;
  private var _MouseSavedX:Number;
  private var _MouseSavedY:Number;

  private var _stage:Stage;
  public function Draggable(which:Sprite,stage:Stage,limitingfunc:Function)
  {
   _limitingFunc = limitingfunc;
   _which = which;
   _stage = stage;
   _which.addEventListener(MouseEvent.MOUSE_DOWN,begin_drag);

  }
  //limiting func: returns 0 when the object is free to move that place.
  //returns -1 when the user wants to block X coordinate changes (but maintain Y free)
  //returns -2 when the user wants to block Y ...
  //returns -3 or less when the user wants to block both X and Y from changing.
  //returns
  private function Return_0(x:Number = 0,y:Number = 0):int{
   return 0;
  }
  private function begin_drag(ev:MouseEvent):void{
   var xTo:Number = _stage.mouseX - _MouseSavedX + _which.x;
   var yTo:Number = _stage.mouseY - _MouseSavedY + _which.y;
   var limitingFuncReturnValue:int = _limitingFunc(xTo,yTo);
   if(limitingFuncReturnValue == 0){//free to move.
    _which.x = xTo;
    _which.y = yTo;
   }
   else if(limitingFuncReturnValue == -1){//free to move Y
    _which.y = yTo;
   }
   else if(limitingFuncReturnValue == -2){
    _which.y = yTo;
   }
   //else:do nothing.
  }
 }
}

In "my actionscript theory", I'm supposed to see a circle that follows the mouse when I click it. (The draggable is not fully implemented) But the circle doesn't even budge :(

...I've been trying to figure out how to access the main class's stage property. I've googled for it, but still no progress.

Please help this helpless newb!!! I'll really appreciate your help:)
Thank you!


问:
Return Column Based on Another Specific Value
I'm trying to show which products our company offers have been purchased by a certain point in time. I would like to show each product's name and then a simple Y or N next to each product indicating if it was sold by a certain date. I'm not sure how to structure the query - this is my attempt

```<code>SELECT product_offering as Product
CASE WHEN date_key='2017-03-30' THEN product_sold ELSE product_sold END as Sold
FROM table1
</code>```

It should look like, if, as a shortened example

1st product sold 2017-03-27

2nd product sold 2017-04-03

3rd product sold 2017-3-28

```<code>|Product | Sold |
|1st Prod|   Y  |
|2nd Prod|   N  |
|3rd Prod|   Y  |
</code>```

Instead, the "Sold" column isn't entirely accurate. I think this has something to do with the date being equal to a certain date instead of a range leading up to, but i'm not sure how to fix this.

答:
You can use the following query to achieve this:</p>

```<code>Select product,(case when min(date_key)<='2017-03-
30' then 'y' else 'n' end) as sold from table1 group by product
</code>```

Body:
I'm trying to show which products our company offers have been purchased by a certain point in time. I would like to show each product's name and then a simple Y or N next to each product indicating if it was sold by a certain date. I'm not sure how to structure the query - this is my attempt

SELECT product_offering as Product
CASE WHEN date_key='2017-03-30' THEN product_sold ELSE product_sold END as Sold
FROM table1

It should look like, if, as a shortened example

1st product sold 2017-03-27

2nd product sold 2017-04-03

3rd product sold 2017-3-28

|Product | Sold |
|1st Prod|   Y  |
|2nd Prod|   N  |
|3rd Prod|   Y  |

Instead, the "Sold" column isn't entirely accurate. I think this has something to do with the date being equal to a certain date instead of a range leading up to, but i'm not sure how to fix this.

Body:
You can use the following query to achieve this:

Select product,(case when min(date_key)<='2017-03-
30' then 'y' else 'n' end) as sold from table1 group by product


问:
Reduce ticks & format axis labels in Matplotlib - scaling
I have an array of subplots, but whenever I try to reduce the tick density or even change the format, the values seem to change.

Is there a distinction here between the 'tick' and its value? How would I match the correct value to the tick if so?

Here's a stand-alone plot that's right: France

Here's the (EDITED) code I'm trying:

```<code>import matplotlib as mpl
from matplotlib.ticker import FormatStrFormatter

f, axarr = plt.subplots(5,6,figsize=(30,30))
for i in range(0,6):
    for j in range(0,5):
        # there are only 26 entries in ser
        if (4*i+j) < 26:
            x = pp_gdp.loc[pp_gdp.index == ser.index[4*i+j],:].round(1)
            y = ser.loc[ser.index == ser.index[4*i+j],:].round(1)
            axarr[j,i].scatter(x,y)
            axarr[j,i].set_title(ser.index[4*i+j])
             xt = axarr[j,i].get_xticks()
        #axarr[j,i].set_xscale('linear')
        axarr[j,i].set_xticks([axarr[j,i].get_xticks()[0],int(len(axarr[j,i].get_xticks())/2), axarr[j,i].get_xticks()[-1]])
        axarr[j,i].set_xticklabels([x.values.min(),sorted(x.values)[0][int(len(xt)/2)],x.values.max()])
        yt = axarr[j,i].get_yticks()
        #axarr[j,i].set_yscale('linear')
        axarr[j,i].set_yticks([axarr[j,i].get_yticks()[0],int(len(axarr[j,i].get_yticks())/2), axarr[j,i].get_yticks()[-1]])
        axarr[j,i].set_yticklabels([y.values.min(),sorted(y.values)[0][int(len(yt)/2)],y.values.max()]);
</code>```

Here's what I get if I comment out all the tick code, i.e. the default subplots:
Default plot

As you can see, it's far too dense to read.

Here's what happens when I try nbins:

```<code>axarr[j,i].locator_params(tight=True, axis='y', nbins=10)
axarr[j,i].locator_params(tight=True, axis='x', nbins=5)
</code>```

France nbins wrong

Again, the values are wrong on both axes.

Using the get_xticks and set_xticks as in the big code sample sort of works, but ruins the intuition of the plot. Also the scale is all wrong because of the way it keeps the 0.

Very linear plots stay linear, but the slope is exaggerated. Plots a little more complicated lose their shape altogether, as in:
China now wrong

The chart on the rightis much harder to understand, just because the scale isn't playing nicely.

With my new

Thanks,
Roy

答:
I don't know why, but it seems that pulling from 2 different data frames in the subplots was making it very unhappy.

Appending one array to the other and then creating subplots from it seemed to cure all my problems:

```<code>pp_gdp_1 = pp_gdp.loc[pp_gdp.index.isin(ser.index), :]
pp_gdp_s = pp_gdp_1.append(ser)
f, axarr = plt.subplots(7,4,figsize=(30,30))
for i in range(0,4):
    for j in range(0,7):
        # there are only 26 entries in ser
        if (7*i+j) < 26:
            x = pp_gdp_s.iloc[7*i+j].round(1)
            y = pp_gdp_s.iloc[(7*i+j)+len(ser)].round(1)
            axarr[j,i].scatter(x,y)
            axarr[j,i].set_title(ser.index[7*i+j])
            axarr[j,i].xaxis.set_major_locator(MaxNLocator(5))
            axarr[j,i].yaxis.set_major_locator(MaxNLocator(5))
</code>```

This produces what I would get when I plotted them one at a time:
Grid of good plots

Body:
I have an array of subplots, but whenever I try to reduce the tick density or even change the format, the values seem to change.

Is there a distinction here between the 'tick' and its value? How would I match the correct value to the tick if so?

Here's a stand-alone plot that's right: France

Here's the (EDITED) code I'm trying:

import matplotlib as mpl
from matplotlib.ticker import FormatStrFormatter

f, axarr = plt.subplots(5,6,figsize=(30,30))
for i in range(0,6):
    for j in range(0,5):
        # there are only 26 entries in ser
        if (4*i+j) < 26:
            x = pp_gdp.loc[pp_gdp.index == ser.index[4*i+j],:].round(1)
            y = ser.loc[ser.index == ser.index[4*i+j],:].round(1)
            axarr[j,i].scatter(x,y)
            axarr[j,i].set_title(ser.index[4*i+j])
             xt = axarr[j,i].get_xticks()
        #axarr[j,i].set_xscale('linear')
        axarr[j,i].set_xticks([axarr[j,i].get_xticks()[0],int(len(axarr[j,i].get_xticks())/2), axarr[j,i].get_xticks()[-1]])
        axarr[j,i].set_xticklabels([x.values.min(),sorted(x.values)[0][int(len(xt)/2)],x.values.max()])
        yt = axarr[j,i].get_yticks()
        #axarr[j,i].set_yscale('linear')
        axarr[j,i].set_yticks([axarr[j,i].get_yticks()[0],int(len(axarr[j,i].get_yticks())/2), axarr[j,i].get_yticks()[-1]])
        axarr[j,i].set_yticklabels([y.values.min(),sorted(y.values)[0][int(len(yt)/2)],y.values.max()]);

Here's what I get if I comment out all the tick code, i.e. the default subplots:
Default plot

As you can see, it's far too dense to read.

Here's what happens when I try nbins:

axarr[j,i].locator_params(tight=True, axis='y', nbins=10)
axarr[j,i].locator_params(tight=True, axis='x', nbins=5)

France nbins wrong

Again, the values are wrong on both axes.

Using the get_xticks and set_xticks as in the big code sample sort of works, but ruins the intuition of the plot. Also the scale is all wrong because of the way it keeps the 0.

Very linear plots stay linear, but the slope is exaggerated. Plots a little more complicated lose their shape altogether, as in:
China now wrong

The chart on the rightis much harder to understand, just because the scale isn't playing nicely.

With my new

Thanks,
Roy

Body:
I don't know why, but it seems that pulling from 2 different data frames in the subplots was making it very unhappy.

Appending one array to the other and then creating subplots from it seemed to cure all my problems:

pp_gdp_1 = pp_gdp.loc[pp_gdp.index.isin(ser.index), :]
pp_gdp_s = pp_gdp_1.append(ser)
f, axarr = plt.subplots(7,4,figsize=(30,30))
for i in range(0,4):
    for j in range(0,7):
        # there are only 26 entries in ser
        if (7*i+j) < 26:
            x = pp_gdp_s.iloc[7*i+j].round(1)
            y = pp_gdp_s.iloc[(7*i+j)+len(ser)].round(1)
            axarr[j,i].scatter(x,y)
            axarr[j,i].set_title(ser.index[7*i+j])
            axarr[j,i].xaxis.set_major_locator(MaxNLocator(5))
            axarr[j,i].yaxis.set_major_locator(MaxNLocator(5))

This produces what I would get when I plotted them one at a time:
Grid of good plots


问:
Is it possible to do that with vertical scroll collection view or table view ?

Can somebody give advice about this ? I prefer the vertical scrolling.

答:
Since it's android and I can't really post entire code, you can probably look at this link for help -

http://sdroid.blogspot.com.au/2011/01/fixed-header-in-tablelayout.html

I would suggest going for table view since collection view is generally for grid layouts. Since your layout looks more like a list of items stacked in one column, table view will be ideal and a little simpler. If you want more complex layout Collection view is much better.

According to apple docs -

A table view displays a list of items in a single column. UITableView
  is a subclass of UIScrollView, which allows users to scroll through
  the table, although UITableView allows vertical scrolling only. The
  cells comprising the individual items of the table are UITableViewCell
  objects; UITableView uses these objects to draw the visible rows of
  the table. Cells have content—titles and images—and can have, near the
  right edge, accessory views. Standard accessory views are disclosure
  indicators or detail disclosure buttons; the former leads to the next
  level in a data hierarchy and the latter leads to a detailed view of a
  selected item. Accessory views can also be framework controls, such as
  switches and sliders, or can be custom views. Table views can enter an
  editing mode where users can insert, delete, and reorder rows of the
  table.


问:
Add objects from case class in Scala
So, I am new to programming and this might be a very rookie question.
I need to add elements to an object. How is this done?

```<code>scala>    case class test (
                               a: String,
                               b: String,
                               c: Int,
                               d: Int
                             )

        var teamData_Temp = test(lol, lel,1, 2)

        var teamData_All = teamData_Temp
</code>```

Then let's say that teamData_Temp becomes teamData_temp = test(kok,kek,3,4) at some point in the script

How do I produce teamData_All = (test(lol,lel,1,2),test(kok,kek,3,4)) ???

答:
Scala is a statically typed language. This means that although variables declared with var can be replaced with a new value, the type of that variable cannot change over the lifetime of the program. The type of teamData_All in your script is test while the type of teamData_All that you are trying to change it to is Tuple2[test, test] (or equivalently (test, test)). These are incompatible types.

If you want to have teamData_All be growable, you have to specify that sort of behavior upfront when declaring the variable, e.g. by making it a list of type List[test]. Then you could have one line set teamData_All = List(test(lol,lel,1,2)) and then have another line set teamData_All = List(test(lol,lel,1,2),test(kok,kek,3,4)).

The reason why this is necessary for a statically typed language is because if you make references to teamData_All in multiple places in your code, there is no way for the compiler to statically, i.e. before running your code, know what the type of teamData_All is at a given point, since you might have changed its type. This makes it impossible for the compiler to make its usual guarantees (e.g. making sure you're only calling methods on things that actually have that method defined).

Title: Add objects from case class in Scala

Body:
So, I am new to programming and this might be a very rookie question.
I need to add elements to an object. How is this done?

scala>    case class test (
                               a: String,
                               b: String,
                               c: Int,
                               d: Int
                             )

        var teamData_Temp = test(lol, lel,1, 2)

        var teamData_All = teamData_Temp

Then let's say that teamData_Temp becomes teamData_temp = test(kok,kek,3,4) at some point in the script

How do I produce teamData_All = (test(lol,lel,1,2),test(kok,kek,3,4)) ???


问:
Comparing game names python
I am trying to create an odds matcher using python that compares game names using pandas. The problem I am having is if the data is not a 100% match, then it will not recognise the game name.

Is there an efficient way to match game names?  E.g a percentage match.  Fuzzy lookup?  I cannot think of a reliable way to do this as to minimise errors.  Any ideas how this might be achieved through Python?

```<code>          a              b           c           d    e
EC Bahia v Salvador U20 2.3 EC Bahia v Salvador 2.3 NaN
EC Bahia v Salvador     2.3 EC Bahia v Salvador 2.3 Match   You could get the first word before v and after but….
Bahai Samone v Salvator 2.3 EC Bahia v Salvador 2.3 Match   However this causes problem when the string was Ec FAHI (different)
</code>```

df1

```<code>                      EW                          WE    DA  \
0                      k                           k     2
1  EC Bahia Salvador U20  Clube Atletico Mineiro U20   2.3
2             Moreirense                     Rio Ave  1.62
3               EC Bahia                Salvadoa U20    14
4               EC Bahia                    Salvador  4141

    DD
0  https://www.b1
1  https://www.b1
2  https://www.b1
3  https://www.b1
4  https://www.b1
</code>```

df2

```<code>                AA            AB                AC    AD  \
0    Starting soon             k                 k  3.15
1          In-Play  FC Nitra U19  Z Michalovce U19  9.60
2          In-Play   Sevilla U19    NK Maribor U19   NaN
3          In-Play    Moreirense           Rio Av   1.02
4  Starting in 13'      EC Bahia          Salvador  1.07

      AE
0  https://www.be
1  https://www.be
2  https://www.be
3  https://www.be
4  https://www.be
</code>```

Desired:

```<code>              AA   AB         AC             AD  \
0  Starting soon    k          k            3.15
1  Starting in 13'  EC        Bahia         9.60
1        In-Play  Moreirense  Rio Av        1.02

              AE         EW        WE  \
0  https://www.b1     k v k         2
1  https://www.b2   EC v Bahia      4141
3  https://www.b3 Moreirense v Rio Av 1.02
</code>```

Formula:

```<code>df1['EW'] = df1['EW'] + ' v ' + df1['EW']
df1['WE'] = df1['DA']
df1['DA'] = df1['DD']

df2['EW'] = df2['AB'] + ' v ' + df2['AC']

print('kk')

df3 = pd.merge(df2, df1, on='EW')
</code>```

答:
You're basically asking "what are all the ways to do string comparisons in Python" which is HUGE question.

Some real basic stuff would be to do some string formatting:

make everything lowercase (e.g here)

remove punctuation (e.g here)

maybe remove spaces

Some more advanced stuff would be:

fuzzy matching (I like the fuzzywuzzy package).

vectorization + cosine similarity (e.g here)

Beyond that you really have to deep dive into each of this IMHO.

Title: Comparing game names python

Body:
I am trying to create an odds matcher using python that compares game names using pandas. The problem I am having is if the data is not a 100% match, then it will not recognise the game name.

Is there an efficient way to match game names?  E.g a percentage match.  Fuzzy lookup?  I cannot think of a reliable way to do this as to minimise errors.  Any ideas how this might be achieved through Python?

          a              b           c           d    e
EC Bahia v Salvador U20 2.3 EC Bahia v Salvador 2.3 NaN
EC Bahia v Salvador     2.3 EC Bahia v Salvador 2.3 Match   You could get the first word before v and after but….
Bahai Samone v Salvator 2.3 EC Bahia v Salvador 2.3 Match   However this causes problem when the string was Ec FAHI (different)

df1

                      EW                          WE    DA  \
0                      k                           k     2
1  EC Bahia Salvador U20  Clube Atletico Mineiro U20   2.3
2             Moreirense                     Rio Ave  1.62
3               EC Bahia                Salvadoa U20    14
4               EC Bahia                    Salvador  4141

    DD
0  https://www.b1
1  https://www.b1
2  https://www.b1
3  https://www.b1
4  https://www.b1

df2

                AA            AB                AC    AD  \
0    Starting soon             k                 k  3.15
1          In-Play  FC Nitra U19  Z Michalovce U19  9.60
2          In-Play   Sevilla U19    NK Maribor U19   NaN
3          In-Play    Moreirense           Rio Av   1.02
4  Starting in 13'      EC Bahia          Salvador  1.07

      AE
0  https://www.be
1  https://www.be
2  https://www.be
3  https://www.be
4  https://www.be

Desired:

              AA   AB         AC             AD  \
0  Starting soon    k          k            3.15
1  Starting in 13'  EC        Bahia         9.60
1        In-Play  Moreirense  Rio Av        1.02

              AE         EW        WE  \
0  https://www.b1     k v k         2
1  https://www.b2   EC v Bahia      4141
3  https://www.b3 Moreirense v Rio Av 1.02

Formula:

df1['EW'] = df1['EW'] + ' v ' + df1['EW']
df1['WE'] = df1['DA']
df1['DA'] = df1['DD']

df2['EW'] = df2['AB'] + ' v ' + df2['AC']

print('kk')

df3 = pd.merge(df2, df1, on='EW')


问:
Any way to dynamically add columns in Angular material table?
I am having a problem creating tables dynamically with Angular Material tables. As the table depends on an interface, I have a fixed number of columns. What I want is to have a dynamic table depending on response from the server. Is there any way to dynamically create the interface or something? Because the way the application is designed is sometimes there would be 2 columns and some times 3 and so on depending on the size of the array.
My interface currently looks like

```<code>export interface Data{
    file:any,
    typea:any,
    typeb:any
}
</code>```

With this interface I have 3 columns. There are minimum 3 columns but depending on data there could be more than 3. I am not able to achieve this, any help would be appreciated.

答:
I'm not 100% down with angular-material tables, but this would allow you to create dynamic properties on your Data object after a server call.

This is a javascript example which will be interchangeable with your typescript implementation where the promise is your http call.

var obj = { };
var promise = new Promise(resolve => resolve(['one', 'two', 'three']));

promise.then(data => {
  for (let column of data){
    obj[column] = 'data -> ' + column;
  }

  console.log(obj);
});```

Body:
I am having a problem creating tables dynamically with Angular Material tables. As the table depends on an interface, I have a fixed number of columns. What I want is to have a dynamic table depending on response from the server. Is there any way to dynamically create the interface or something? Because the way the application is designed is sometimes there would be 2 columns and some times 3 and so on depending on the size of the array.
My interface currently looks like

export interface Data{
    file:any,
    typea:any,
    typeb:any
}

With this interface I have 3 columns. There are minimum 3 columns but depending on data there could be more than 3. I am not able to achieve this, any help would be appreciated.


问:
How to get current item from Spinner without listener - c# android xamarin
I am trying to get the item that is currently in the spinner, but not by Selected or OnChange events.

```<code> public string GetCurrentSport()
        {

            string currentSport = spnSports.GetItemAtPosition(0).ToString();
            return currentSport;
        }
</code>```

the above code throws and error, I am guessing it is the wrong code to get the Spinner value, this is getting passed to another class from a button click so i can't use the OnSelected Events.

If you need more code, please ask.

答:
A Spinner via its subclassed AdapterView has three methods to obtain the "item" that is currently selected, SelectedItem, SelectedItemId, SelectedItemPosition:

```<code>// The data corresponding to the currently selected item, or null if there is nothing selected.
var javaObj = spinner.SelectedItem; // getSelectedItem

//The id corresponding to the currently selected item, or INVALID_ROW_ID if nothing is selected.
var id = spinner.SelectedItemId; // getSelectedItemId

// Return the position of the currently selected item within the adapter's data set
var postion = spinner.SelectedItemPosition; // getSelectedItemPosition
</code>```

re: https://developer.android.com/reference/android/widget/AdapterView.html#getSelectedItem()

Body:
I am trying to get the item that is currently in the spinner, but not by Selected or OnChange events.

 public string GetCurrentSport()
        {

            string currentSport = spnSports.GetItemAtPosition(0).ToString();
            return currentSport;
        }

the above code throws and error, I am guessing it is the wrong code to get the Spinner value, this is getting passed to another class from a button click so i can't use the OnSelected Events.

If you need more code, please ask.

Body:
A Spinner via its subclassed AdapterView has three methods to obtain the "item" that is currently selected, SelectedItem, SelectedItemId, SelectedItemPosition:

// The data corresponding to the currently selected item, or null if there is nothing selected.
var javaObj = spinner.SelectedItem; // getSelectedItem

//The id corresponding to the currently selected item, or INVALID_ROW_ID if nothing is selected.
var id = spinner.SelectedItemId; // getSelectedItemId

// Return the position of the currently selected item within the adapter's data set
var postion = spinner.SelectedItemPosition; // getSelectedItemPosition

re: https://developer.android.com/reference/android/widget/AdapterView.html#getSelectedItem()


问:
create drop down to view month and year in php
I am using this function to create a dropdown for months and year my problem is am getting an error like below:

Unknown column 'format' in 'where clause'

below is the code anyone help to get rid of this error

```<code>date_condition = ' and 1=1 ';
if($date_type==1)
{

    $date_condition = ' and m.submittimestamp BETWEEN DATE_SUB(NOW(), INTERVAL 300 DAY) AND NOW() ';
}
else if($date_type==2)
{
    $date_condition = ' and YEAR(m.submittimestamp) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) and MONTH(m.submittimestamp)=MONTH(CURRENT_DATE - INTERVAL 1 MONTH) ';
}
else if($date_type==3)
{
    $date_condition = ' and YEAR(m.submittimestamp) = YEAR(date(format)) AND MONTH(m.submittimestamp)=MONTH(date) ';
}
</code>```

conditions 1 and 2 are working perfectly but condition 3 is getting error

Below is the code for drop down and script

```<code><div class="form-group ">
    <input name="filter_options"
        <?php echo $option3; ?>
        value="3" onchange="toggleDate(1)" type="radio" class="form-control" id="from_date">
    <label for="from_date">show status for the month of </label>
    <select name="month" class="form-control">
        <?php
        for ($i = 0; $i <= 12; ++$i) {
            $time = strtotime(sprintf('-%d months', $i));
            $value = date('m', $time);
            $label = date('F ', $time);
            printf('<option value="%s">%s</option>', $value, $label);
        }
        ?>
    </select>
    <select name="year" class="form-control">
        <?php
        for ($i = 0; $i <= 12; ++$i) {
            $time = strtotime(sprintf('-%d years', $i));
            $value = date('Y', $time);
            $label = date('Y ', $time);
            printf('<option value="%s">%s</option>', $value, $label);
        }
        ?>
        <option value=" ">year</option>
    </select>
</div>
</code>```

答:
The error is telling you everything you need to know, you have a syntax error. Remove the letter "e" at the beginning of the code noted in your error.

```<code>e) AND MONTH(m.submittimestamp)=MONTH(date) GROUP
</code>```

should be

```<code>) AND MONTH(m.submittimestamp)=MONTH(date) GROUP
</code>```

Body:
I am using this function to create a dropdown for months and year my problem is am getting an error like below:

Unknown column 'format' in 'where clause'

below is the code anyone help to get rid of this error

date_condition = ' and 1=1 ';
if($date_type==1)
{

    $date_condition = ' and m.submittimestamp BETWEEN DATE_SUB(NOW(), INTERVAL 300 DAY) AND NOW() ';
}
else if($date_type==2)
{
    $date_condition = ' and YEAR(m.submittimestamp) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) and MONTH(m.submittimestamp)=MONTH(CURRENT_DATE - INTERVAL 1 MONTH) ';
}
else if($date_type==3)
{
    $date_condition = ' and YEAR(m.submittimestamp) = YEAR(date(format)) AND MONTH(m.submittimestamp)=MONTH(date) ';
}

conditions 1 and 2 are working perfectly but condition 3 is getting error

Below is the code for drop down and script

    <input name="filter_options"
        <?php echo $option3; ?>
        value="3" onchange="toggleDate(1)" type="radio" class="form-control" id="from_date">
    show status for the month of
    <select name="month" class="form-control">
        <?php
        for ($i = 0; $i <= 12; ++$i) {
            $time = strtotime(sprintf('-%d months', $i));
            $value = date('m', $time);
            $label = date('F ', $time);
            printf('<option value="%s">%s</option>', $value, $label);
        }
        ?>
    </select>
    <select name="year" class="form-control">
        <?php
        for ($i = 0; $i <= 12; ++$i) {
            $time = strtotime(sprintf('-%d years', $i));
            $value = date('Y', $time);
            $label = date('Y ', $time);
            printf('<option value="%s">%s</option>', $value, $label);
        }
        ?>
        <option value=" ">year</option>
    </select>

Body:
The error is telling you everything you need to know, you have a syntax error. Remove the letter "e" at the beginning of the code noted in your error.

e) AND MONTH(m.submittimestamp)=MONTH(date) GROUP

should be

) AND MONTH(m.submittimestamp)=MONTH(date) GROUP


问:
PJSIP Integration proper guiding step to run in xcode 7

I had tried to compile pjsip library.but getting error. when run

```<code>$ cd /pjproject-2.5.5
$ ./configure-iphone
//error: -bash: -bash: ./configure-iphone: Permission denied
$ chmod +x configure-iphone //then i tried this
$ ./configure-iphone
//error:-bash: ./configure-iphone: /bin/bash^M: bad interpreter: No such file or directory.
</code>```

Please give me proper guide line by steps to
  run pjsip ios project.

答:
To compile pjsip for iPhone

1. Download source code from one of the following link :

http://www.pjsip.org/download.htm

http://trac.pjsip.org/repos/wiki/Getting-Started/Download-Source

2. Create a new file config_site.h in the project folder /pjlib/include/pj/ with the following code:

```<code>#define PJ_CONFIG_IPHONE 1
#include <pjconfig_site_sample.h>
</code>```

3. To Build PJSIP

Open terminal:

```<code>$ cd /path/to/your/pjsip/dir
$ ./configure-iphone
</code>```

You may get the following problems:

a) Permission denied

```<code>Solution: preface the login with sudo
or login as super user using su command and the type following command
   $ su
   Password:
   # chmod 777 configure-iphone
   # exit
</code>```

b) -bash: ./configure-iphone: /bin/bash^M: bad interpreter: No such file or directory

(This error may come because in the configure-iphone file every line may have been appended by a character $ or may be a carriage return symbol)
        To check this do as:

```<code>$ vim configure-iphone
    (It wil open the vim editor)
    To see the last character press escape(ESC:)set list
    To quit vim press Esc:q
</code>```

Then Eliminate

```<code>$ tr -d '\r' <configure-iphone >FILE.new
</code>```

(It will create new file with name FILE. Now after that delete the configure-iphone file and rename FILE to configure-iphone using the following commands:)

```<code> $ rm configure-iphone
 $ mv FILE.new configure-iphone
</code>```

(Again confirm that new created file has 777 permission if no then assign from su- super user)

```<code>$ ./configure-iphone
</code>```

Again there may be error in ./configure-iphone:
Permission denied

```<code>Solution : Assign 777 permission to the whole folder.
   - $ cd .. (Go to the parent folder in which the PJSIP folder lies)
   - $ su (login as super user)
   - # chmod 777 * (It will assign 777 permission to the whole folder and its content)
Alternatively:
   - $ chmod u+x configure-iphone
</code>```

Again run $ ./configure-iphone command. This time every thing should work fine.

4. To make

```<code>make dep && make clean && make
</code>```

Source: http://gaurav-iphone.blogspot.com.au/2011/09/compiling-pjsip.html

Body:
I had tried to compile pjsip library.but getting error. when run

$ cd /pjproject-2.5.5
$ ./configure-iphone
//error: -bash: -bash: ./configure-iphone: Permission denied
$ chmod +x configure-iphone //then i tried this
$ ./configure-iphone
//error:-bash: ./configure-iphone: /bin/bash^M: bad interpreter: No such file or directory.

Please give me proper guide line by steps to
  run pjsip ios project.

Body:
To compile pjsip for iPhone

1. Download source code from one of the following link :

http://www.pjsip.org/download.htm

http://trac.pjsip.org/repos/wiki/Getting-Started/Download-Source

2. Create a new file config_site.h in the project folder /pjlib/include/pj/ with the following code:

#define PJ_CONFIG_IPHONE 1
#include <pjconfig_site_sample.h>

3. To Build PJSIP

Open terminal:

$ cd /path/to/your/pjsip/dir
$ ./configure-iphone

You may get the following problems:

a) Permission denied

Solution: preface the login with sudo
or login as super user using su command and the type following command
   $ su
   Password:
   # chmod 777 configure-iphone
   # exit

b) -bash: ./configure-iphone: /bin/bash^M: bad interpreter: No such file or directory

(This error may come because in the configure-iphone file every line may have been appended by a character $ or may be a carriage return symbol)
        To check this do as:

$ vim configure-iphone
    (It wil open the vim editor)
    To see the last character press escape(ESC:)set list
    To quit vim press Esc:q

Then Eliminate

$ tr -d '\r' <configure-iphone >FILE.new

(It will create new file with name FILE. Now after that delete the configure-iphone file and rename FILE to configure-iphone using the following commands:)

 $ rm configure-iphone
 $ mv FILE.new configure-iphone

(Again confirm that new created file has 777 permission if no then assign from su- super user)

$ ./configure-iphone

Again there may be error in ./configure-iphone:
Permission denied

Solution : Assign 777 permission to the whole folder.
   - $ cd .. (Go to the parent folder in which the PJSIP folder lies)
   - $ su (login as super user)
   - # chmod 777 * (It will assign 777 permission to the whole folder and its content)
Alternatively:
   - $ chmod u+x configure-iphone

Again run $ ./configure-iphone command. This time every thing should work fine.

4. To make

make dep && make clean && make

Source: http://gaurav-iphone.blogspot.com.au/2011/09/compiling-pjsip.html


问:
Entity Framework : Add Properties/Entities during runtime
I want to use the entity framework. However I also have the requirement of allowing my users to define custom fields in our system. I would like to still use the entity framework and not use a a partial class with a hash table property.

Below is the solution I was thinking of, however it is not simple so I would like to see if there is a better way.

My idea currently, is to have a ModelManager object that would create a column on the appropriate table, modify the EDM files, and compile the files using the edmgen.exe. This would all have to happen in a different process and/or appdomain than the application, since the application would reference the resulting assembly. When the application restarts it will have access to the newly added field.

Is this the only way to do this with the Entity Framework? Thanks for your time.

答:
You are going to end up spending more time trying to make this solution work then to get your entire project done using HashTables.  I don't really think the entity framework is appropriate for this situation because,

your code wouldn't be programmed to use the new fields that were generated

you are going to have to deal with unloading the current assembly from the app domain, and reloading the new one

you are really setting your self up for failure

Sorry but there are just some problems that are not easily applied to certain frameworks.

OwnerDisplayName: CoderGuy

OwnerDisplayName: Nick Berardi


问:
SQL - Can this relation have a primary key?
The relationship between bands and members, 'MemberOf', includes a member id (Mid), band id (Bid), 'StartYear', 'EndYear' and 'Instrument' played. Mid and Bid are both foreign keys to Member and Band relations respectively but I am struggling to identify the primary key in this situation for the 'MemberOf' relation.

Note: start year can be null if a member was in a band from the start and end year can also be null if a member is still in the band.

In this situation, start and end year cannot be used as PK's as they may contain null values, but the member id and band id is not enough information to be unique - e.g. the same member returns to the same band at a later date.

Does this mean no primary key exists? Thanks.

答:
Note: start year can be null if a
  member was in a band from the start

Well, that ridiculous requirement is the biggest part of your problem. Store the year.

{BandId, MemberId, StartYear} as the primary key.

That won't accommodate members who start in February, quit in March, and start again in July, though.


问:
Having trouble with C program output
As far as I know regardless of any other issues the program below should print out the title and menu options, and then prompt for user input.

However, it does absolutely nothing and when I stop the execution it prints out the menu etc and then, as it hasn't asked for the user inputted option it repeatedly prints the "This is not a valid option" line.

*EDIT: I have completely removed the loops. All I have in the program is print the title, print the menu, ask for user input, and I still get nothing to the console until after I terminate. Is there something wrong with my asking for input?

EDIT2: It's definitely the scanf as without it everything works. I ran the code with an added function to print out the value stored in option and it told me -1 when I hadn't previously set it to 0 before asking the user to input. The program seems to be automatically assigning option instead of bothering to ask the user what they want.

```<code>#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main ()
{
    /*Print Title*/
    printf("Maths Quiz Game \n");
    printf("\n");

    int i;
    int rightCount = 0; //count of right answers
    int wrongCount = 0; //count of wrong answers
    int questions = 0; //user input for number of questions
    int exit = 0; //store exit option
    int option = 0; //menu option

    while(exit == 0) //while loop that keeps program running until exit is chosen
    {
        /*Menu Options*/
        printf("Please choose an option from the menu below. Enter the number of your choice. \n");
        printf(" 1. Choose number of questions for this round. (Max = 5) \n");
        printf(" 2. Start Quiz \n");
        printf(" 3. Display total of right and wrong answers. (Only availanle after quiz) \n");
        printf(" 4. Exit Game \n");

        scanf("%d", &option); //taking user menu option

        /*Error check for any input that is not a valid option. It continues until valid entry*/
        while((option != 1) || (option != 2) || (option != 3) || (option != 4))
        {
            printf("\n That is not a valid option. Please try again. \n");
            scanf("%d", &option);
        }
</code>```

答: The problem was with the printf function in that it didn’t print out until after you had entered the following options, it didn’t ask until after the user had answered. A simple flush after the printf sorted this out.</p>

Title: Having trouble with C program output

Body:
As far as I know regardless of any other issues the program below should print out the title and menu options, and then prompt for user input.

However, it does absolutely nothing and when I stop the execution it prints out the menu etc and then, as it hasn't asked for the user inputted option it repeatedly prints the "This is not a valid option" line.

*EDIT: I have completely removed the loops. All I have in the program is print the title, print the menu, ask for user input, and I still get nothing to the console until after I terminate. Is there something wrong with my asking for input?

EDIT2: It's definitely the scanf as without it everything works. I ran the code with an added function to print out the value stored in option and it told me -1 when I hadn't previously set it to 0 before asking the user to input. The program seems to be automatically assigning option instead of bothering to ask the user what they want.

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main ()
{
    /*Print Title*/
    printf("Maths Quiz Game \n");
    printf("\n");

    int i;
    int rightCount = 0; //count of right answers
    int wrongCount = 0; //count of wrong answers
    int questions = 0; //user input for number of questions
    int exit = 0; //store exit option
    int option = 0; //menu option

    while(exit == 0) //while loop that keeps program running until exit is chosen
    {
        /*Menu Options*/
        printf("Please choose an option from the menu below. Enter the number of your choice. \n");
        printf(" 1. Choose number of questions for this round. (Max = 5) \n");
        printf(" 2. Start Quiz \n");
        printf(" 3. Display total of right and wrong answers. (Only availanle after quiz) \n");
        printf(" 4. Exit Game \n");

        scanf("%d", &option); //taking user menu option

        /*Error check for any input that is not a valid option. It continues until valid entry*/
        while((option != 1) || (option != 2) || (option != 3) || (option != 4))
        {
            printf("\n That is not a valid option. Please try again. \n");
            scanf("%d", &option);
        }


问:
Initializing a function pointer without the '&' operator
I was playing around with function pointers, and ran into something that intuitively doesn't fit with my understanding of pointers in C.

Take a look at the following code:

```<code>include <stdio.h>

void fun(int a) {
    printf("fun, %d!\n", a);

}

void bun(int b) {
    printf("bun, %d!\n", b);
}

int main(){

    void (*fooptr)(int) = &bun;
    void (*blooptr) (int) = fun;

    fooptr(200);
    blooptr(100);

    return 0;
}
</code>```

If I treated function pointers like any other pointer in C, I should expect void (*blooptr) (int) = fun; to trigger a compiler warning against incompatible types. My code compiles (silently) and works as expected.

How does C let me initialize a function pointer without the & operator, like I would do a regular pointer, without even a compiler warning? Is this one of those cases where I'm accidentally getting the right behaviour, though I'm technically in undefined behaviour territory? If someone could explain why this works, with some insight (references to literature will also do) into the nature of function pointers, that would be great.

I tried looking around for this specific question, but couldn't find anything related. Seems a bit fundamental, so apologies if it's a dup.

答:
Function type in C automatically and implicitly decays to function pointer type (as if unary & operator was quiety applied). This decay takes place in all contexts, with the exception of unary & operator and sizeof operator. For this reason

```<code>void (*fooptr)(int) = &bun;
</code>```

and

```<code>void (*fooptr)(int) = bun;
</code>```

are two alternative ways to say the same thing.

Body:
I was playing around with function pointers, and ran into something that intuitively doesn't fit with my understanding of pointers in C.

Take a look at the following code:

include <stdio.h>

void fun(int a) {
    printf("fun, %d!\n", a);

}

void bun(int b) {
    printf("bun, %d!\n", b);
}

int main(){

    void (*fooptr)(int) = &bun;
    void (*blooptr) (int) = fun;

    fooptr(200);
    blooptr(100);

    return 0;
}

If I treated function pointers like any other pointer in C, I should expect void (*blooptr) (int) = fun; to trigger a compiler warning against incompatible types. My code compiles (silently) and works as expected.

How does C let me initialize a function pointer without the & operator, like I would do a regular pointer, without even a compiler warning? Is this one of those cases where I'm accidentally getting the right behaviour, though I'm technically in undefined behaviour territory? If someone could explain why this works, with some insight (references to literature will also do) into the nature of function pointers, that would be great.

I tried looking around for this specific question, but couldn't find anything related. Seems a bit fundamental, so apologies if it's a dup.

Body:
Function type in C automatically and implicitly decays to function pointer type (as if unary & operator was quiety applied). This decay takes place in all contexts, with the exception of unary & operator and sizeof operator. For this reason

void (*fooptr)(int) = &bun;

and

void (*fooptr)(int) = bun;

are two alternative ways to say the same thing.


问:
Collapse large number of rows into scrollable view
I have a sheet with a header, followed by a large number of rows, then a row with some aggregates on that data for each column at the bottom (sums, averages, etc.). The aggregate row at the bottom is not very discoverable; you have to scroll past all the data first. I would like to collapse the data rows into a scrollable view, ~20 rows, so that the header shows, then only 20 rows show, then the aggregate row shows, and you can scroll within those 20 rows to see all the data but the size and position of the view remains the same. </p>

答: Google Sheets doesn't have a "collapse/expand" feature but it has "hide/show" and also has Filters and Filter Views.</p>


问:
What does getContext.getCollection() return in CosmosDB stored procedure?
I have written a simple stored procedure to query a collection and return response but when I execute it as node.js script I get 400 error code and following error message:

"PartitionKey extracted from document doesn't match the one specified in the header"

When getContext().getCollection.getSelfLink() value is printed I get dbs/3Mk0AA==/colls/3Mk0AOWMbw0=/ but my database and collection Ids are some other values.

Any kind of help will be much appreciated.

答:
When you observe the documents you created in Azure Cosmos DB, you will see several system generated properties in addition to the ID you set.

You could find official statement from System vs. user defined resources.

```<code>{
    "id": "1",
    "statusId": "new",
    "_rid": "duUuAN3LzQEIAAAAAAAAAA==",
    "_self": "dbs/duUuAA==/colls/duUuAN3LzQE=/docs/duUuAN3LzQEIAAAAAAAAAA==/",
    "_etag": "\"0400d4ee-0000-0000-0000-5a24ac3f0000\"",
    "_attachments": "attachments/",
    "_ts": 1512352831
}
</code>```

getContext().getCollection.getSelfLink() method returns "_self" value, not Id value you set.

PartitionKey extracted from document doesn't match the one specified
  in the header

This issue should be due to you set the PartitionKey incorrectly.

Suppose your partitioning key is color and there are two partitions red and blue in the database. The PK should be set red or blue, not color.

You could refer to a similar thread I answered before : How to specify NONE partition key for deleting a document in Document DB java SDK?

Hope it helps you.

Body:
When you observe the documents you created in Azure Cosmos DB, you will see several system generated properties in addition to the ID you set.

You could find official statement from System vs. user defined resources.

{
    "id": "1",
    "statusId": "new",
    "_rid": "duUuAN3LzQEIAAAAAAAAAA==",
    "_self": "dbs/duUuAA==/colls/duUuAN3LzQE=/docs/duUuAN3LzQEIAAAAAAAAAA==/",
    "_etag": "\"0400d4ee-0000-0000-0000-5a24ac3f0000\"",
    "_attachments": "attachments/",
    "_ts": 1512352831
}

getContext().getCollection.getSelfLink() method returns "_self" value, not Id value you set.

PartitionKey extracted from document doesn't match the one specified
  in the header

This issue should be due to you set the PartitionKey incorrectly.

Suppose your partitioning key is color and there are two partitions red and blue in the database. The PK should be set red or blue, not color.

You could refer to a similar thread I answered before : How to specify NONE partition key for deleting a document in Document DB java SDK?

Hope it helps you.


问:
Cache coherence- MESI protocol
Can there be a case in a cache employing a MESI protocol (has l1 and l2 inclusivity employed) where l2 can send an invalid instruction to an already invalid line in l1. </p>

答:
An "invalidate request", you mean?

I guess so, if L2 doesn't filter its requests according to what it knows about L1, it might just always send an INVD to L1 every time it evicts a line.  No idea if this is plausible for a real design.  (Eviction from L2 could be caused by a HW or SW prefetch into L2, rather than in response to L1 write-back.)

Or if the CPU core can invalidate a line in L1 at the same time that L2 is sending an invalidate, the INVD could arrive in L1 after it's already invalidated the line.

Title: Cache coherence- MESI protocol


问:
Difference between {{template "base" }} and {{template "base" .}} in go-gin
What is the difference between {{template "base" }} and {{template "base" .}}?

I use go-gin, both can run with no problem. I cannot find any description in the documentation about this.

答:
From godoc text/template:

{{template "name"}}

      The template with the specified name is executed with nil data.

{{template "name" pipeline}}

      The template with the specified name is executed with dot set
      to the value of the pipeline.

So {{template "base"}} calls the template base with no data in the context (globals are still available, of course), and {{template "base" .}} calls it with whatever data is in-scope at the point of the call.


问:
SQL Server Percent Difference is Greater than Value
I have the following table structures:

table c_alert:

```<code>|dynamic|symbol|price_usd|
--------------------------
|5      |BTC   |13000   |
</code>```

table c_current:

```<code>|symbol|price_usd|
------------------
|BTC   |13600   |
</code>```

I have this query:

```<code>SELECT dbo.c_alert.symbol, dbo.c_alert.price_usd AS alert_price, dbo.c_current.price_usd AS current_price, (dbo.c_current.price_usd - dbo.c_alert.price_usd) * 100.0 / dbo.c_alert.price_usd AS pct_diff, dbo.c_alert.dynamic AS pct
FROM dbo.c_alert INNER JOIN
     dbo.c_current
     ON dbo.c_alert.symbol = dbo.c_current.symbol AND
        dbo.c_alert.dynamic > (dbo.c_current.price_usd - dbo.c_alert.price_usd) * 100.0 / dbo.c_alert.price_usd
</code>```

Which returns this:

```<code>|symbol|alert_price|current_price|pct_diff|dynamic|
-----------------------------------------------
|BTC   |13000      |13613.3000   |4.7     |5   |
</code>```

Not very strong with financial queries...Basically I would like to know when the price difference between alert_price and current_price are equal to or greater than value in the dynamic column as a boolean.  So where the difference is equal or greater than 5% show True, else False.  That dynamic value (integer) could change for each row in the c_alert table.  Hope someone can provide a solution to the query.

答:
Because the same percent difference term is required in multiple places in the query, I might go with using a CTE first, which calculates this term.  Then, do a straightforward query on the CTE to get the output you want.

```<code>WITH cte AS (
    SELECT
        t2.symbol,
        t2.dynamic,
        t2.price_usd AS alert_price,
        t1.price_usd AS current_price,
        100.0*(t1.price_usd - COALESCE(t2.price_usd, 0.0)) / t2.price_usd AS pct_diff
    FROM dbo.c_current t1
    LEFT JOIN dbo.c_alert t2
        ON t1.symbol = t2.symbol
)

SELECT
    symbol,
    alert_price,
    current_price,
    pct_diff,
    dynamic,
    CASE WHEN pct_diff > dynamic THEN 'TRUE' ELSE 'FALSE' END AS result
FROM cte;
</code>```

Edit:

The logic seems to be working in the demo below.  If you still have issues, then edit the demo and paste the link somewhere as a comment.

Demo

Body:
I have the following table structures:

table c_alert:

|dynamic|symbol|price_usd|
--------------------------
|5      |BTC   |13000   |

table c_current:

|symbol|price_usd|
------------------
|BTC   |13600   |

I have this query:

SELECT dbo.c_alert.symbol, dbo.c_alert.price_usd AS alert_price, dbo.c_current.price_usd AS current_price, (dbo.c_current.price_usd - dbo.c_alert.price_usd) * 100.0 / dbo.c_alert.price_usd AS pct_diff, dbo.c_alert.dynamic AS pct
FROM dbo.c_alert INNER JOIN
     dbo.c_current
     ON dbo.c_alert.symbol = dbo.c_current.symbol AND
        dbo.c_alert.dynamic > (dbo.c_current.price_usd - dbo.c_alert.price_usd) * 100.0 / dbo.c_alert.price_usd

Which returns this:

|symbol|alert_price|current_price|pct_diff|dynamic|
-----------------------------------------------
|BTC   |13000      |13613.3000   |4.7     |5   |

Not very strong with financial queries...Basically I would like to know when the price difference between alert_price and current_price are equal to or greater than value in the dynamic column as a boolean.  So where the difference is equal or greater than 5% show True, else False.  That dynamic value (integer) could change for each row in the c_alert table.  Hope someone can provide a solution to the query.

Body:
Because the same percent difference term is required in multiple places in the query, I might go with using a CTE first, which calculates this term.  Then, do a straightforward query on the CTE to get the output you want.

WITH cte AS (
    SELECT
        t2.symbol,
        t2.dynamic,
        t2.price_usd AS alert_price,
        t1.price_usd AS current_price,
        100.0*(t1.price_usd - COALESCE(t2.price_usd, 0.0)) / t2.price_usd AS pct_diff
    FROM dbo.c_current t1
    LEFT JOIN dbo.c_alert t2
        ON t1.symbol = t2.symbol
)

SELECT
    symbol,
    alert_price,
    current_price,
    pct_diff,
    dynamic,
    CASE WHEN pct_diff > dynamic THEN 'TRUE' ELSE 'FALSE' END AS result
FROM cte;

Edit:

The logic seems to be working in the demo below.  If you still have issues, then edit the demo and paste the link somewhere as a comment.

Demo


问:
Chrome 62 javascript modules
I import modules like that:

```<code><script type="module">
    import mod_test from '../classes/mod_test.js';
    window.mod_test= mod_test;
</script>
</code>```

But Chrome says sometimes if i call a function window.mod_test.test();

cannot read property 'test' of undefined

which is called in a Jquery synchronous request.

What am i doing wrong? Or it is a bug with chrome, because it happens only sometimes?

The module looks like that

```<code>var mod_test = {
    a: null,
    test: function (b) {
         this.a=b;
    }
};

export default mod_test;
</code>```

答:
Since you have no CORS issue, I think that the problem could be in a race condition between module loading and module exported fuction calling. To be sure you may try following approach. Define the app runner before the module loader:

```<code><script>
  window.runTheApp = function(mod_test) {
    mod_test.test();
    // ...
  }
</script>
</code>```

and then load your module with the app runner call:

```<code><script type="module">
    import mod_test from '../classes/mod_test.js';
    window.runTheApp(mod_test);
</script>
</code>```

Also, the dynamic import could be useful. For me it makes the approach more clear:

```<code><script type="module">
  import('../classes/mod_test.js')
  .then(function(module) {
    console.log('module loaded');
    window.runTheApp(module.default);
  })
</script>
</code>```

Title: Chrome 62 javascript modules

Body:
I import modules like that:

But Chrome says sometimes if i call a function window.mod_test.test();

cannot read property 'test' of undefined

which is called in a Jquery synchronous request.

What am i doing wrong? Or it is a bug with chrome, because it happens only sometimes?

The module looks like that

var mod_test = {
    a: null,
    test: function (b) {
         this.a=b;
    }
};

export default mod_test;

Body:
Since you have no CORS issue, I think that the problem could be in a race condition between module loading and module exported fuction calling. To be sure you may try following approach. Define the app runner before the module loader:

<script>
  window.runTheApp = function(mod_test) {
    mod_test.test();
    // ...
  }
</script>

and then load your module with the app runner call:

<script type="module">
    import mod_test from '../classes/mod_test.js';
    window.runTheApp(mod_test);
</script>

Also, the dynamic import could be useful. For me it makes the approach more clear:

<script type="module">
  import('../classes/mod_test.js')
  .then(function(module) {
    console.log('module loaded');
    window.runTheApp(module.default);
  })
</script>


问:
Php Function to send SMS via Kannel
I can now send an SMS via kannel. However this is done via headers eg:

```<code>header("Location:http://localhost:13013/cgi-bin/sendsms?username=xxxx&password=xxxx&to=$in_number&text=$in_msg");
</code>```

I want to send an sms via a php function and I got the code below online but it doesn't work. (Kannel smsbox log shows no request):

```<code>  function sendSmsMessage($in_number, $in_msg)
 {
 $url = '/cgi-bin/sendsms?username=' . CONFIG_KANNEL_USER_NAME
 . '&password=' . CONFIG_KANNEL_PASSWORD
 . '&charset=UCS-2&coding=2'
 . "&to={$in_number}"
 . '&text=' . urlencode(iconv('utf-8', 'ucs-2', $in_msg));

$results = file('http://'
                 . CONFIG_KANNEL_HOST . ':'
                 . CONFIG_KANNEL_PORT . $url);
</code>```

}

Is there something wrong? I tried replacing the CONFIG_KANNEL_USER_NAME and the rest with the actual values but it still doesn't work. Open to suggestions.

答:
If you're attempting to trigger a URL loading in the background (rather than by re-directing the user to the URL), you need to use something like cURL or perhaps even file_get_contents.

For example, if your set up has fopen URL wrappers enabled, you could simply use:

```<code>$response = file_get_contents("http://localhost:13013/cgi-bin/sendsms?username=xxxx&password=xxxx&to=$in_number&text=$in_msg");
</code>```

Irrespective, it's hard to know why the function you found won't work without some additional debug information. (If CONFIG_KANNEL_HOST is defined as "localhost" and CONFIG_KANNEL_PORT is defined as 13013 then it's effectively doing the same thing, albeit with additional character set operations.)

Title: Php Function to send SMS via Kannel

Body:
I can now send an SMS via kannel. However this is done via headers eg:

header("Location:http://localhost:13013/cgi-bin/sendsms?username=xxxx&password=xxxx&to=$in_number&text=$in_msg");

I want to send an sms via a php function and I got the code below online but it doesn't work. (Kannel smsbox log shows no request):

  function sendSmsMessage($in_number, $in_msg)
 {
 $url = '/cgi-bin/sendsms?username=' . CONFIG_KANNEL_USER_NAME
 . '&password=' . CONFIG_KANNEL_PASSWORD
 . '&charset=UCS-2&coding=2'
 . "&to={$in_number}"
 . '&text=' . urlencode(iconv('utf-8', 'ucs-2', $in_msg));

$results = file('http://'
                 . CONFIG_KANNEL_HOST . ':'
                 . CONFIG_KANNEL_PORT . $url);

}

Is there something wrong? I tried replacing the CONFIG_KANNEL_USER_NAME and the rest with the actual values but it still doesn't work. Open to suggestions.

Body:
If you're attempting to trigger a URL loading in the background (rather than by re-directing the user to the URL), you need to use something like cURL or perhaps even file_get_contents.

For example, if your set up has fopen URL wrappers enabled, you could simply use:

$response = file_get_contents("http://localhost:13013/cgi-bin/sendsms?username=xxxx&password=xxxx&to=$in_number&text=$in_msg");

Irrespective, it's hard to know why the function you found won't work without some additional debug information. (If CONFIG_KANNEL_HOST is defined as "localhost" and CONFIG_KANNEL_PORT is defined as 13013 then it's effectively doing the same thing, albeit with additional character set operations.)


问:
Julia: best way to sample from successively shrinking range?
I would like to sample k numbers where the first number is sampled from 1:n and the second from 1:n-1 and the third from 1:n-2 and so on.

I have the below implementation

```<code>function shrinksample(n,k)
    [rand(1:m) for m in n:-1:n-k+1]
end
</code>```

Are there faster solutions in Julia?

答:
If this is not very sensitive to randomness (you're not doing cryptography), the following should be amazingly fast and very simple:

```<code>blazingshrinksample(n,k) = (Int)[trunc(Int,(n-m)rand()+1) for m in 0:k-1]
</code>```

Testing this along with your implementation and with Dan's, I got this:

```<code>using BenchmarkTools

@btime shrinksample(10000,10000);
  259.414 μs (2 allocations: 78.20 KiB)

@btime fastshrinksample(10000,10000);
  66.713 μs (2 allocations: 78.20 KiB)

@btime blazingshrinksample(10000,10000);
  33.614 μs (2 allocations: 78.20 KiB)
</code>```

Body:
I would like to sample k numbers where the first number is sampled from 1:n and the second from 1:n-1 and the third from 1:n-2 and so on.

I have the below implementation

function shrinksample(n,k)
    [rand(1:m) for m in n:-1:n-k+1]
end

Are there faster solutions in Julia?

Body:
If this is not very sensitive to randomness (you're not doing cryptography), the following should be amazingly fast and very simple:

blazingshrinksample(n,k) = (Int)[trunc(Int,(n-m)rand()+1) for m in 0:k-1]

Testing this along with your implementation and with Dan's, I got this:

using BenchmarkTools

@btime shrinksample(10000,10000);
  259.414 μs (2 allocations: 78.20 KiB)

@btime fastshrinksample(10000,10000);
  66.713 μs (2 allocations: 78.20 KiB)

@btime blazingshrinksample(10000,10000);
  33.614 μs (2 allocations: 78.20 KiB)