问:
Indexing pdf and html files in solr shows error in html indexing
Hi I am new in Solr and using Solr 7.0.0 running in windows 7. The Solr is running in cloud mode.
I created a collection and tried to index a list of pdf and html files residing in a folder using the following command:

```<code>> java -jar -Dc=guidanceDoc -Dauto example\exampledocs\post.jar M:\Projects\guidance\documents\*
</code>```

The pdf files in my folder have no ".pdf" extension, however, the html files have htm extension.

While indexing using the above command, the pdf files are indexed without any error. However, during running the command, if the process gets an html file shows an error as follows:

```<code>> POSTing file ucm073837.htm (text/html) to [base]/extract
> SimplePostTool: WARNING: Solr returned an error #400 (Bad Request) for
> url: http
> ://localhost:8983/solr/guidanceDoc/update/extract?resource.name=M%3A%5CProjects%
> 5Cguidance%5Cdocuments%5Cucm073837.htm&literal.id=M%3A%5CProjects%5Cguidance%5Cd
> ocuments%5Cucm073837.htm SimplePostTool: WARNING: Response: {
> "responseHeader":{
>     "status":400,
>     "QTime":10},   "error":{
>     "metadata":[
>       "error-class","org.apache.solr.common.SolrException",
>       "root-error-class","org.apache.solr.common.SolrException"],
>     "msg":"Document contains multiple values for uniqueKey field: id=[M:\\Projec ts\\guidance\\documents\\ucm073837.htm, UCM073837]",
>     "code":400}} SimplePostTool: WARNING: IOException while reading response: java.io.IOException : Server returned HTTP response code:
> 400 for URL: http://localhost:8983/solr/gu
> idanceDoc/update/extract?resource.name=M%3A%5CProjects%5Cguidance%5Cdocuments%5C
> ucm073837.htm&literal.id=M%3A%5CProjects%5Cguidance%5Cdocuments%5Cucm073837.htm
</code>```

How can I resolve this problem?

答:
The problem of indexing this html files isn't related to extension. As it mentioned in the error message:

```<code>Document contains multiple values for uniqueKey field: id=[M:\\Projec ts\\guidance\\documents\\ucm073837.htm
</code>```

Your uniqueKey shouldn't exists multiple times in the file. Another possibility is to change uniqueKey in the schema.xml to be some other field, but not an id field.

Body:
Hi I am new in Solr and using Solr 7.0.0 running in windows 7. The Solr is running in cloud mode.
I created a collection and tried to index a list of pdf and html files residing in a folder using the following command:

> java -jar -Dc=guidanceDoc -Dauto example\exampledocs\post.jar M:\Projects\guidance\documents\*

The pdf files in my folder have no ".pdf" extension, however, the html files have htm extension.

While indexing using the above command, the pdf files are indexed without any error. However, during running the command, if the process gets an html file shows an error as follows:

> POSTing file ucm073837.htm (text/html) to [base]/extract
> SimplePostTool: WARNING: Solr returned an error #400 (Bad Request) for
> url: http
> ://localhost:8983/solr/guidanceDoc/update/extract?resource.name=M%3A%5CProjects%
> 5Cguidance%5Cdocuments%5Cucm073837.htm&literal.id=M%3A%5CProjects%5Cguidance%5Cd
> ocuments%5Cucm073837.htm SimplePostTool: WARNING: Response: {
> "responseHeader":{
>     "status":400,
>     "QTime":10},   "error":{
>     "metadata":[
>       "error-class","org.apache.solr.common.SolrException",
>       "root-error-class","org.apache.solr.common.SolrException"],
>     "msg":"Document contains multiple values for uniqueKey field: id=[M:\\Projec ts\\guidance\\documents\\ucm073837.htm, UCM073837]",
>     "code":400}} SimplePostTool: WARNING: IOException while reading response: java.io.IOException : Server returned HTTP response code:
> 400 for URL: http://localhost:8983/solr/gu
> idanceDoc/update/extract?resource.name=M%3A%5CProjects%5Cguidance%5Cdocuments%5C
> ucm073837.htm&literal.id=M%3A%5CProjects%5Cguidance%5Cdocuments%5Cucm073837.htm

How can I resolve this problem?

Body:
The problem of indexing this html files isn't related to extension. As it mentioned in the error message:

Document contains multiple values for uniqueKey field: id=[M:\\Projec ts\\guidance\\documents\\ucm073837.htm

Your uniqueKey shouldn't exists multiple times in the file. Another possibility is to change uniqueKey in the schema.xml to be some other field, but not an id field.


来源: stackexchange

问:
Modifying css search-toolbar
I am trying to create a page with a search bar and filters underneath. I really like the way the search-toolbar looks, but it's creating space that I don't need. Is there a way to modify i to get rid of the space?

Thanks!

Here's an image of what I have:
Search bar with toolbar underneath

Edit: That grey space is what I'm trying to get rid of.

Here's my asp code:

```<code>    <div class="search-toolbar" style="background-color:white">
        <ul class="list-unstyled nav nav-pills">
                <li>
                    <a href="#everything" data-toggle="tab">Everything</a>
                </li>
                 <li>
                   <a href="#everything" data-toggle="tab" onclick="searchProvider()">Other Content</a>
                 </li>
        </ul>
    </div>
        <div class="tab-content">
            Content
        </div>
</code>```

答:
Figured it out, I found the css file and edited it.
I'm still new to web development, and I wasn't aware that I could do that.</p>

ContentLicense: CC BY-SA 3.0

Title: Modifying css search-toolbar

Body:
I am trying to create a page with a search bar and filters underneath. I really like the way the search-toolbar looks, but it's creating space that I don't need. Is there a way to modify i to get rid of the space?

Thanks!

Here's an image of what I have:
Search bar with toolbar underneath

Edit: That grey space is what I'm trying to get rid of.

Here's my asp code:

                    Everything

                   Other Content

            Content


问:
How to insert an array of objects into a mapping table - Sequelize
We have two tables - ticket and device. A mapper table 'ticketdevice_map' will have ticket_id(FK), device_id(FK) and some other values.
Associations are shown below:

```<code>ticketdevice_map.belongsTo(collection.device, {
        as: 'device',
        foreignKey: 'device_id'
    })

    ticketdevice_map.belongsTo(collection.ticket, {
        as: 'ticket',
        foreignKey: 'ticket_id'
    })
</code>```

A ticket can have a number of devices associated with it. Now, when I create a ticket how can I insert this array of devices into the 'ticketdevice_map' table.

example:

```<code>{
"abc_id": "B222",
"devices": [{
    "device_id": 200,
    "reg_id": "aa",
    "reg_color": "red",
},{
    "device_id": 201,
    "reg_id": "aa",
    "reg_color": "red",
}]
</code>```

}

in mapper table it should be inserted like,

```<code>ticket_id device_id reg_color
 1          200       red
 1          201       red
</code>```

答:
Using sequelize this code will help you.</p>

```<code>models.tblTicket.findOne({
where : {
    ticket_id : req.body.ticket_id
}
}).then(function(tickets) {
if (tickets) {
    for (var i = 0; i < devices.length; i++) {
        models.ticketdevice_map.create({
            ticket_id : tickets.dataValues.ticket_id,
            device_id : devices[i].device_id,
            reg_color : devices[i].reg_color
        });
    }
  }
});
</code>```

Body:
We have two tables - ticket and device. A mapper table 'ticketdevice_map' will have ticket_id(FK), device_id(FK) and some other values.
Associations are shown below:

ticketdevice_map.belongsTo(collection.device, {
        as: 'device',
        foreignKey: 'device_id'
    })

    ticketdevice_map.belongsTo(collection.ticket, {
        as: 'ticket',
        foreignKey: 'ticket_id'
    })

A ticket can have a number of devices associated with it. Now, when I create a ticket how can I insert this array of devices into the 'ticketdevice_map' table.

example:

{
"abc_id": "B222",
"devices": [{
    "device_id": 200,
    "reg_id": "aa",
    "reg_color": "red",
},{
    "device_id": 201,
    "reg_id": "aa",
    "reg_color": "red",
}]

}

in mapper table it should be inserted like,

ticket_id device_id reg_color
 1          200       red
 1          201       red

Body:
Using sequelize this code will help you.

models.tblTicket.findOne({
where : {
    ticket_id : req.body.ticket_id
}
}).then(function(tickets) {
if (tickets) {
    for (var i = 0; i < devices.length; i++) {
        models.ticketdevice_map.create({
            ticket_id : tickets.dataValues.ticket_id,
            device_id : devices[i].device_id,
            reg_color : devices[i].reg_color
        });
    }
  }
});


问:
Removing COMMENT ON from all objects in PostgreSQL
In the same vein as pg_dump without comments on objects?, is anyone aware of a command to quickly get rid of the comments (created with COMMENT ON) on all objects at once ?

For now, I resorted to bash generating a SQL script that would void one by one the comments on each table/view/column, but it is quite slow, especially with >4000 columns.

Example:

```<code>COMMENT ON COLUMN table1.column1 IS NULL;
COMMENT ON COLUMN table1.column2 IS NULL;
COMMENT ON COLUMN table1.column3 IS NULL;
...
</code>```

答:
If you want to do this without hacking a system table, then this will generate the statements for you:

```<code>SELECT 'COMMENT ON COLUMN ' || quote_ident(pg_namespace.nspname) || '.' || quote_ident(pg_class.relname) || '.' || quote_ident(columns.column_name) || ' IS NULL;'
FROM   pg_description
JOIN pg_class ON pg_class.oid = pg_description.objoid
JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace
JOIN information_schema.columns
  ON columns.table_schema = pg_namespace.nspname
 AND columns.table_name = pg_class.relname
 AND columns.ordinal_position = pg_description.objsubid
</code>```

You should probably add a WHERE clause that constrains it to your schemas.

Body:
In the same vein as pg_dump without comments on objects?, is anyone aware of a command to quickly get rid of the comments (created with COMMENT ON) on all objects at once ?

For now, I resorted to bash generating a SQL script that would void one by one the comments on each table/view/column, but it is quite slow, especially with >4000 columns.

Example:

COMMENT ON COLUMN table1.column1 IS NULL;
COMMENT ON COLUMN table1.column2 IS NULL;
COMMENT ON COLUMN table1.column3 IS NULL;
...

Body:
If you want to do this without hacking a system table, then this will generate the statements for you:

SELECT 'COMMENT ON COLUMN ' || quote_ident(pg_namespace.nspname) || '.' || quote_ident(pg_class.relname) || '.' || quote_ident(columns.column_name) || ' IS NULL;'
FROM   pg_description
JOIN pg_class ON pg_class.oid = pg_description.objoid
JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace
JOIN information_schema.columns
  ON columns.table_schema = pg_namespace.nspname
 AND columns.table_name = pg_class.relname
 AND columns.ordinal_position = pg_description.objsubid

You should probably add a WHERE clause that constrains it to your schemas.


问:
Is there a simpler way of unpacking a tuple?
The below is an example of some code I wrote in a RPG game that I've been working on. Upon winning a battle, the stats are updated in the level_up() function, and returned in the form of a list.
Which brings up my question. Is there a better way of writing the below code?</p>

```<code>stats = level_up()
level = stats[0]
exp = stats[1]
exp_nextlev = stats[2]
health = stats[3]
defense = stats[4]
attack = stats[5]
speed = stats[6]
</code>```

答: It's not shorter, but better style in my opinion, to just return a dictionary like this {"level": ..., "exp":..., ...} from the function. When you later acces values of the dictionary your code will be as readable as with different variables for every item.

Body:
The below is an example of some code I wrote in a RPG game that I've been working on. Upon winning a battle, the stats are updated in the level_up() function, and returned in the form of a list.
Which brings up my question. Is there a better way of writing the below code?

stats = level_up()
level = stats[0]
exp = stats[1]
exp_nextlev = stats[2]
health = stats[3]
defense = stats[4]
attack = stats[5]
speed = stats[6]


问:
Celery scheduled tasks with expiration time for each task instance?
I have a django app with celery 4.1.0 and celery beat with database scheduler. What I want is to run periodic tasks from admin site and set expiration time for each of this tasks. expire property in PeriodicTask is a time scheduler stops creating new messages for that task but i want the expiration to revoke tasks which are scheduled but are older than some value e.g. one hour. how to do this?

I am really confused with celery documentation and differences between different versions of it.

答: Sounds like you need to use a custom scheduler class.</p>


问:
Python: why appending to a list results in same values
This is my code:

```<code>a = []
res = []
for i in range(0, 3):
    a.append(i)
    res.append(a)
print(res)
</code>```

The result is:

```<code>[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
</code>```

But I want the result to be:

```<code>[[0], [0, 1], [0, 1, 2]]
</code>```

I know the solution is using the shallow copy: res.append(a[:]). But can somebody tell me why?

答: You appended the same thing (a) to res three times, so it appears 3 times.  The fact that you changed the contents of a between each call to append doesn't matter.  If each call to append was given its own copy of a, then you'd get the result you expect.

Body:
This is my code:

a = []
res = []
for i in range(0, 3):
    a.append(i)
    res.append(a)
print(res)

The result is:

[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

But I want the result to be:

[[0], [0, 1], [0, 1, 2]]

I know the solution is using the shallow copy: res.append(a[:]). But can somebody tell me why?


问:
Save input into a char array C++
How can I save input into a char array C++?

The problem I have is that I do not know beforehand how much input will the user provide.

I would like to use only arrays and chars.

答:
If you are set on only using an array of char instead of a std::string or even std::vector (basically the same thing) you can dynamically allocate an array with new[] and delete[] (you use delete[] to avoid memory leaks).

You can read more about it and find an example here.

If you don't want to open the link then go to learncpp.com and jump to lesson 6.9a. I would also suggest to read the previous lesson to understand more about dynamic memory allocation.

Title: Save input into a char array C++


问:
Refactor javascript if statement
I have a unusual nested if statement where a third condition is needed to execute some code, but this condition is independent of my else clause. Thus, I've nested this condition inside the outer 2 conditions. The below works as it should, but I'm not positive this is the best way to handle a case like this. Should I use another method or refactor this in a way I'm not thinking of?

```<code>if ($('#preferred-contact').prop('selectedIndex') == index && !$(selector).val())
{
    if (!$(label).parent().hasClass('has-error')) {
        $(selector).after("<span class='help-block form-error'>Required Field</span>");
        $(label).parent().addClass('has-error');
    }
}
else {
    $(selector + ' + .help-block').remove();
    $(label).parent().removeClass('has-error');
}
</code>```

答:
Your First if statement has a second if statement but, not other code.

Why just create a single condition for that ?

```<code>let myCondition = index === $('#preferred-contact').prop('selectedIndex') && !$(selector).val();

if (myCondition && !$(label).parent().hasClass('has-error'))
{
    $(selector).after("<span class='help-block form-error'>Required Field</span>");
    $(label).parent().addClass('has-error');
}
else if (!myCondition)
{
    $(selector + ' + .help-block').remove();
    $(label).parent().removeClass('has-error');
}
</code>```

With that you reduce the cyclomatic complexity and improve your code. In every language you should coding with the least level of nesting possible.

Title: Refactor javascript if statement

Body:
I have a unusual nested if statement where a third condition is needed to execute some code, but this condition is independent of my else clause. Thus, I've nested this condition inside the outer 2 conditions. The below works as it should, but I'm not positive this is the best way to handle a case like this. Should I use another method or refactor this in a way I'm not thinking of?

if ($('#preferred-contact').prop('selectedIndex') == index && !$(selector).val())
{
    if (!$(label).parent().hasClass('has-error')) {
        $(selector).after("Required Field");
        $(label).parent().addClass('has-error');
    }
}
else {
    $(selector + ' + .help-block').remove();
    $(label).parent().removeClass('has-error');
}

Body:
Your First if statement has a second if statement but, not other code.

Why just create a single condition for that ?

let myCondition = index === $('#preferred-contact').prop('selectedIndex') && !$(selector).val();

if (myCondition && !$(label).parent().hasClass('has-error'))
{
    $(selector).after("<span class='help-block form-error'>Required Field</span>");
    $(label).parent().addClass('has-error');
}
else if (!myCondition)
{
    $(selector + ' + .help-block').remove();
    $(label).parent().removeClass('has-error');
}

With that you reduce the cyclomatic complexity and improve your code. In every language you should coding with the least level of nesting possible.

ContentLicense: CC BY-SA 4.0


问:
Why do these links exceed the width?
How can we explain that these links exceed the 200px width:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small">
2 January 2017#foooooo#foooooo#foooooo#foooooo#foooooo#foooooo
</div></code>```

whereas, if we add a newline after each , it doesn't:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small">
2 January 2017
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo
</div></code>```

What is the usual good practice to not be trapped in such corner cases?

答:
It's because you didn't leave a white space between the anchors so the browser doesn't have a point to break the string.
Adding some space between the anchors should work:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="small">
2 January 2017 #foooooo #foooooo #foooooo #foooooo #foooooo #foooooo
</div></code>```

Title: Why do these links exceed the width?

Body:
How can we explain that these links exceed the 200px width:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }

2 January 2017#foooooo#foooooo#foooooo#foooooo#foooooo#foooooo

whereas, if we add a newline after each , it doesn't:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }

2 January 2017
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo
#foooooo

What is the usual good practice to not be trapped in such corner cases?

Body:
It's because you didn't leave a white space between the anchors so the browser doesn't have a point to break the string.
Adding some space between the anchors should work:

.small { background-color: red; width: 200px; }
.tag { background-color: rgba(0,0,0,.05); margin-right: 10px;  }

<div class="small">
<a class="date" href="blah">2 January 2017</a> <a class="tag" href="blah">#foooooo</a> <a class="tag" href="blah">#foooooo</a> <a class="tag" href="blah">#foooooo</a> <a class="tag" href="blah">#foooooo</a> <a class="tag" href="blah">#foooooo</a> <a class="tag" href="blah">#foooooo</a>
</div>


问:
Java implementing swing api, instance of object JButton not recognized
I have a very simple and small java program using the swing libraries to create a static stop watch. Problem being, whenever I try to compile it at the command line with "javac program.java" it seems to give a series of errors as if the statements related to the object button were not recognized by the compiler.

```<code>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

class StopWatch implements ActionListener {

    JLabel jlab;
    long start;  // holds the start time in milliseconds

    StopWatch() {
        // Create a new JFrame Container.
        JFrame jfrm = new JFrame("A Simple StopWatch");

        // Specify the FlowLayout for the layout manager.
        jfrm.setLayout(new FlowLayout());

        // Give the frame an initial size.
        jfrm.setSize(230,90);

        // Terminates the program when the user closes the application.
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Make two buttons
        JButton JbtnStart = new JButton("Start");
        JButton JbtnStop = new JButton("Stop");

        // Add action listeners.
        jbtnStart.addActionListener(this);
        jbtnStop.addActionListener(this);

        // Add the buttons to the content pane
        jfrm.add(jbtnStart);
        jfrm.add(jbtnStop);

        // Create a text-based label
        jlab = new JLabel("Press Start to begin timing.");

        // Add the label
        jfrm.add(jlab);

        jfrm.setVisible(true);

    }

    // Handle button events
    public void actionPerformed(ActionEvent ae) {
        Calendar cal = Calendar.getInstance();  // get current system time

        if (ae.getActionCommand().equals("Start")) {
            start = cal.getTimeInMillis();
            jlab.setText("Stopwatch is Running...");
        }

        else
            // Compute the elapsed time.
            jlab.setText("Elapsed time is "+(double)(cal.getTimeInMillis() - start)/1000);
    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
        public void run() { new StopWatch(); }
        });
    }

}
</code>```

The following are the error messages:

```<code>StopWatch.java:30: error: cannot find symbol
jbtnStart.addActionListener(this);
        ^
Symbol:   variable jbtnStart
location: class StopWatch
StopWatch.java:31: error: cannot find symbol
jbtnStop.addActionListener(this);
        ^
symbol:   variable jbtnStop
location: class StopWatch
StopWatch.java:34: error: cannot find symbol
jfrm.add(jbtnStart);
                 ^
symbol:   variable jbtnStart
location: class StopWatch
StopWatch.java:35: error: cannot find symbol
jfrm.add(jbtnStop);
                     ^
symbol:   variable jbtnStop
location: class StopWatch
4 errors
</code>```

Would jbtnStop and jbtnStart be reserved words in the java language?

答:
Fix these variables names:

```<code>JButton JbtnStart = new JButton("Start");
JButton JbtnStop = new JButton("Stop");
</code>```

They should start from small letter:

```<code>JButton jbtnStart = new JButton("Start");
JButton jbtnStop = new JButton("Stop");
</code>```

Java is a case-sensitive language, so you should be careful with naming

Body:
I have a very simple and small java program using the swing libraries to create a static stop watch. Problem being, whenever I try to compile it at the command line with "javac program.java" it seems to give a series of errors as if the statements related to the object button were not recognized by the compiler.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

class StopWatch implements ActionListener {

    JLabel jlab;
    long start;  // holds the start time in milliseconds

    StopWatch() {
        // Create a new JFrame Container.
        JFrame jfrm = new JFrame("A Simple StopWatch");

        // Specify the FlowLayout for the layout manager.
        jfrm.setLayout(new FlowLayout());

        // Give the frame an initial size.
        jfrm.setSize(230,90);

        // Terminates the program when the user closes the application.
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Make two buttons
        JButton JbtnStart = new JButton("Start");
        JButton JbtnStop = new JButton("Stop");

        // Add action listeners.
        jbtnStart.addActionListener(this);
        jbtnStop.addActionListener(this);

        // Add the buttons to the content pane
        jfrm.add(jbtnStart);
        jfrm.add(jbtnStop);

        // Create a text-based label
        jlab = new JLabel("Press Start to begin timing.");

        // Add the label
        jfrm.add(jlab);

        jfrm.setVisible(true);

    }

    // Handle button events
    public void actionPerformed(ActionEvent ae) {
        Calendar cal = Calendar.getInstance();  // get current system time

        if (ae.getActionCommand().equals("Start")) {
            start = cal.getTimeInMillis();
            jlab.setText("Stopwatch is Running...");
        }

        else
            // Compute the elapsed time.
            jlab.setText("Elapsed time is "+(double)(cal.getTimeInMillis() - start)/1000);
    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
        public void run() { new StopWatch(); }
        });
    }

}

The following are the error messages:

StopWatch.java:30: error: cannot find symbol
jbtnStart.addActionListener(this);
        ^
Symbol:   variable jbtnStart
location: class StopWatch
StopWatch.java:31: error: cannot find symbol
jbtnStop.addActionListener(this);
        ^
symbol:   variable jbtnStop
location: class StopWatch
StopWatch.java:34: error: cannot find symbol
jfrm.add(jbtnStart);
                 ^
symbol:   variable jbtnStart
location: class StopWatch
StopWatch.java:35: error: cannot find symbol
jfrm.add(jbtnStop);
                     ^
symbol:   variable jbtnStop
location: class StopWatch
4 errors

Would jbtnStop and jbtnStart be reserved words in the java language?

Body:
Fix these variables names:

JButton JbtnStart = new JButton("Start");
JButton JbtnStop = new JButton("Stop");

They should start from small letter:

JButton jbtnStart = new JButton("Start");
JButton jbtnStop = new JButton("Stop");

Java is a case-sensitive language, so you should be careful with naming


问:
Need help understanding a specific alloc/release idiom in iOS/Objective-C programming
I'm an experienced C/C++ programmer starting to learn Objective-C development. I'm currently looking through the UICatalog sample and came across another instance of an idiom I've seen several places and never understood.

Code:

```<code>ButtonsViewController *buttonsViewController = [[ButtonsViewController alloc] initWithNibName:@"ButtonsViewController" bundle:nil];
[self.menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                       NSLocalizedString(@"ButtonsTitle", @""), kTitleKey,
                                       NSLocalizedString(@"ButtonsExplain", @""), kExplainKey,
                                       buttonsViewController, kViewControllerKey, nil]];
[buttonsViewController release];
</code>```

AFAIK, this allocates and initializes a ButtonsViewController, creates an NSDictionary for the ButtonsViewController and adds the dictionary to an NSMutableArray called menuList (which is a member variable of the MainViewController where the above code lives) and then releases the buttonsViewController that it just created. Later, the MainViewController uses the dictionary entry to switch views to the buttonsViewController when necessary.

My question is: why is the buttonsViewController still valid after this code? It was allocated and released with no 'retains' between. Does adding something to an NSDictionary or NSMutableArray have an implicit 'retain'? If so, was I supposed to be able to figure that out somehow, or is it just one of those things you have to read and remember?

答:
As mentioned, NSDictionary and NSArray send retain messages to objects added and also send release to objects when removed.  The code above is conceptually transferring ownership of buttonsViewController to the dictionary.  An example of how you might know this... from the documentation :

-addObject:forKey:

Parameters: anObject - The value for key.
  The object receives a retain message
  before being added to the dictionary.
  This value must not be nil.

-removeAllObjects

Discussion: Each key and corresponding
  value object is sent a release
  message.

ContentLicense: CC BY-SA 2.5

Body:
I'm an experienced C/C++ programmer starting to learn Objective-C development. I'm currently looking through the UICatalog sample and came across another instance of an idiom I've seen several places and never understood.

Code:

ButtonsViewController *buttonsViewController = [[ButtonsViewController alloc] initWithNibName:@"ButtonsViewController" bundle:nil];
[self.menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                       NSLocalizedString(@"ButtonsTitle", @""), kTitleKey,
                                       NSLocalizedString(@"ButtonsExplain", @""), kExplainKey,
                                       buttonsViewController, kViewControllerKey, nil]];
[buttonsViewController release];

AFAIK, this allocates and initializes a ButtonsViewController, creates an NSDictionary for the ButtonsViewController and adds the dictionary to an NSMutableArray called menuList (which is a member variable of the MainViewController where the above code lives) and then releases the buttonsViewController that it just created. Later, the MainViewController uses the dictionary entry to switch views to the buttonsViewController when necessary.

My question is: why is the buttonsViewController still valid after this code? It was allocated and released with no 'retains' between. Does adding something to an NSDictionary or NSMutableArray have an implicit 'retain'? If so, was I supposed to be able to figure that out somehow, or is it just one of those things you have to read and remember?


问:
Write a const pattern to a file of specific size
I need to write C++ code that will open a binary file and will write 5 MB of '1' in to it.

Currently my code is:

```<code>#define BYTES_BUFFER_SIZE_5MB (1024*1024*5)

static char buffer[BYTES_BUFFER_SIZE_5MB];
memset(buffer, 0xff, BYTES_BUFFER_SIZE_5MB);
ofstream myFile ("data.bin", ios::out | ios::binary);
myFile.write(buffer, BYTES_BUFFER_SIZE_5MB);
</code>```

Is there a memset-like method for writing to a file, so I can avoid having a buffer?

答:
You can use a smaller buffer and write it several times with a for loop.

If you have to write 5Mb you can do something like

```<code>#define BYTES_SIZE_5MB (5242880) // Bathsheba comment have to be considered
#define BUFFER_SIZE (1024) // Chunk size to be written (this is an arbitrary amount)

static char buffer[BUFFER_SIZE];
ofstream myFile ("data.bin", ios::out | ios::binary);
int i, repetitions = BYTES_SIZE_5MB / BUFFER_SIZE;
memset(buffer, 0xff, BUFFER_SIZE);
for (i=0; i < repetitions; ++i)
    myFile.write(buffer, BYTES_BUFFER_SIZE_5MB);
myFile.close();
</code>```

Note write() method could become really slow, it's better to choose a bigger chunk size and that way you will do less write calls, which improves the speed of your program

Body:
I need to write C++ code that will open a binary file and will write 5 MB of '1' in to it.

Currently my code is:

#define BYTES_BUFFER_SIZE_5MB (1024*1024*5)

static char buffer[BYTES_BUFFER_SIZE_5MB];
memset(buffer, 0xff, BYTES_BUFFER_SIZE_5MB);
ofstream myFile ("data.bin", ios::out | ios::binary);
myFile.write(buffer, BYTES_BUFFER_SIZE_5MB);

Is there a memset-like method for writing to a file, so I can avoid having a buffer?

Body:
You can use a smaller buffer and write it several times with a for loop.

If you have to write 5Mb you can do something like

#define BYTES_SIZE_5MB (5242880) // Bathsheba comment have to be considered
#define BUFFER_SIZE (1024) // Chunk size to be written (this is an arbitrary amount)

static char buffer[BUFFER_SIZE];
ofstream myFile ("data.bin", ios::out | ios::binary);
int i, repetitions = BYTES_SIZE_5MB / BUFFER_SIZE;
memset(buffer, 0xff, BUFFER_SIZE);
for (i=0; i < repetitions; ++i)
    myFile.write(buffer, BYTES_BUFFER_SIZE_5MB);
myFile.close();

Note write() method could become really slow, it's better to choose a bigger chunk size and that way you will do less write calls, which improves the speed of your program


问:
How do I POST XML data to a webservice with Postman?
I want POST an XML request to a webservice using Postman. However, when I check the available request formats, I only see options for form-data, x-www-form-urlencoded, raw, and binary.

How do I POST an XML request to a webservice with Postman?

答:
Send XML requests with the raw data type, then set the Content-Type to text/xml.

After creating a request, use the dropdown to change the request type to POST.

Open the Body tab and check the data type for raw.

Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

Enter your raw XML data into the input field below

Click Send to submit your XML Request to the specified server.


答:
I have made changes to your code just changed JbtnStart with jbtnStart
and JbtnStop with jbtnStop

```<code>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

class StopWatch implements ActionListener {

    JLabel jlab;
    long start;  // holds the start time in milliseconds

    StopWatch() {
        // Create a new JFrame Container.
        JFrame jfrm = new JFrame("A Simple StopWatch");

        // Specify the FlowLayout for the layout manager.
        jfrm.setLayout(new FlowLayout());

        // Give the frame an initial size.
        jfrm.setSize(230,90);

        // Terminates the program when the user closes the application.
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Make two buttons
        JButton jbtnStart = new JButton("Start");
        JButton jbtnStop = new JButton("Stop");

        // Add action listeners.
        jbtnStart.addActionListener(this);
        jbtnStop.addActionListener(this);

        // Add the buttons to the content pane
        jfrm.add(jbtnStart);
        jfrm.add(jbtnStop);

        // Create a text-based label
        jlab = new JLabel("Press Start to begin timing.");

        // Add the label
        jfrm.add(jlab);

        jfrm.setVisible(true);

    }

    // Handle button events
    public void actionPerformed(ActionEvent ae) {
        Calendar cal = Calendar.getInstance();  // get current system time

        if (ae.getActionCommand().equals("Start")) {
            start = cal.getTimeInMillis();
            jlab.setText("Stopwatch is Running...");
        }

        else
            // Compute the elapsed time.
            jlab.setText("Elapsed time is "+(double)(cal.getTimeInMillis() - start)/1000);
    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
        public void run() { new StopWatch(); }
        });
    }

}
</code>```

Title: Java implementing swing api, instance of object JButton not recognized

Body:
I have made changes to your code just changed JbtnStart with jbtnStart
and JbtnStop with jbtnStop

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

class StopWatch implements ActionListener {

    JLabel jlab;
    long start;  // holds the start time in milliseconds

    StopWatch() {
        // Create a new JFrame Container.
        JFrame jfrm = new JFrame("A Simple StopWatch");

        // Specify the FlowLayout for the layout manager.
        jfrm.setLayout(new FlowLayout());

        // Give the frame an initial size.
        jfrm.setSize(230,90);

        // Terminates the program when the user closes the application.
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Make two buttons
        JButton jbtnStart = new JButton("Start");
        JButton jbtnStop = new JButton("Stop");

        // Add action listeners.
        jbtnStart.addActionListener(this);
        jbtnStop.addActionListener(this);

        // Add the buttons to the content pane
        jfrm.add(jbtnStart);
        jfrm.add(jbtnStop);

        // Create a text-based label
        jlab = new JLabel("Press Start to begin timing.");

        // Add the label
        jfrm.add(jlab);

        jfrm.setVisible(true);

    }

    // Handle button events
    public void actionPerformed(ActionEvent ae) {
        Calendar cal = Calendar.getInstance();  // get current system time

        if (ae.getActionCommand().equals("Start")) {
            start = cal.getTimeInMillis();
            jlab.setText("Stopwatch is Running...");
        }

        else
            // Compute the elapsed time.
            jlab.setText("Elapsed time is "+(double)(cal.getTimeInMillis() - start)/1000);
    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
        public void run() { new StopWatch(); }
        });
    }

}


问:
@HostBinding disabling class from child component Angular 4
I have an angular app which has user login and logout. I am showing up a welcome page as the home page before a user logs in. I want to enable a background image only on the welcome page. Once the user logs in, the background image must disappear. When the user logs out, he will be redirected to welcome page which must show up the background image again.

I have tried using @HostBinding in the app.component.ts by renaming the selector to 'body'.

```<code>app.component.ts

import {Component, HostBinding, Input} from '@angular/core';
import {InputMask} from "primeng/primeng";

@Component({
  selector: 'body',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  path = '../assets/img/AvayaHome.jpg';
  title = 'app';
  toggleClass = true;
  @HostBinding('class.bodyClass') isWelcomePage = this.toggleClass;
}
</code>```

Here is my CSS.

```<code>app.component.css

.bodyClass  {
    background-image: url("../assets/img/AvayaHome.jpg");
}
</code>```

Here is my index.html

```<code><!doctype html>
<html lang="en">
<head>
 <title> Something </title>
</head>
<body class="bodyClass">

    <app-welcome-page></app-welcome-page>

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

I am enabling the css style for bodyClass by assigning toggleClass as true. Once the user logs in, I am changing the value of toggleClass (which is in the app.component.ts) from the child component.

Here is my login.component.ts

```<code>onLogin() {
    console.log('onLogin() invoked:', this._email, ':' , this.password);
    if (this._email == null || this.password == null) {
      this.errorMessage = 'All fields are required';
      return;
    }
    this.errorMessage = null;
    this.loginservice.authenticate(this._email, this.password);
    this.appComponent.toggleClass = true;
    this.router.navigate(['/dashboard']);
  }
</code>```

The value of the toggleClass changes when the user logs in to FALSE. But I am still seeing the background image. Not sure what I am doing wrong. Any help will be appreciated.

答:
Hostbinding only binds stuff to host tag, in your case  tag.

So if you want to manipulate the body tag, you have to do it using plan javascript from your component or also create a component in the body.

```<code>@Component({
  selector: 'body',
  template: `<child></child>`
})
export class AppComponent {
  @HostBinding('class') public cssClass = 'class1';
}
</code>```

Body:
I have an angular app which has user login and logout. I am showing up a welcome page as the home page before a user logs in. I want to enable a background image only on the welcome page. Once the user logs in, the background image must disappear. When the user logs out, he will be redirected to welcome page which must show up the background image again.

I have tried using @HostBinding in the app.component.ts by renaming the selector to 'body'.

app.component.ts

import {Component, HostBinding, Input} from '@angular/core';
import {InputMask} from "primeng/primeng";

@Component({
  selector: 'body',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  path = '../assets/img/AvayaHome.jpg';
  title = 'app';
  toggleClass = true;
  @HostBinding('class.bodyClass') isWelcomePage = this.toggleClass;
}

Here is my CSS.

app.component.css

.bodyClass  {
    background-image: url("../assets/img/AvayaHome.jpg");
}

Here is my index.html

<!doctype html>

 <title> Something </title>

    <app-welcome-page></app-welcome-page>

I am enabling the css style for bodyClass by assigning toggleClass as true. Once the user logs in, I am changing the value of toggleClass (which is in the app.component.ts) from the child component.

Here is my login.component.ts

onLogin() {
    console.log('onLogin() invoked:', this._email, ':' , this.password);
    if (this._email == null || this.password == null) {
      this.errorMessage = 'All fields are required';
      return;
    }
    this.errorMessage = null;
    this.loginservice.authenticate(this._email, this.password);
    this.appComponent.toggleClass = true;
    this.router.navigate(['/dashboard']);
  }

The value of the toggleClass changes when the user logs in to FALSE. But I am still seeing the background image. Not sure what I am doing wrong. Any help will be appreciated.

Body:
Hostbinding only binds stuff to host tag, in your case  tag.

So if you want to manipulate the body tag, you have to do it using plan javascript from your component or also create a component in the body.

@Component({
  selector: 'body',
  template: `<child></child>`
})
export class AppComponent {
  @HostBinding('class') public cssClass = 'class1';
}


问:
Jupyter | How to rotate 3D graph
I am not sure about how to rotate graph in Python Jupyter notebook, its static for me and not rotate on mouse movement

```<code>from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x =[1,2,3,4,5,6,7,8,9,10]
y =[5,6,2,3,13,4,1,2,4,8]
z =[2,3,3,3,5,7,9,11,9,10]

ax.scatter(x, y, z, c='r', marker='o')

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()
</code>```

答:
To enable interactivity you need to use the notebook backend of matplotlib. You can do this by running %matplotlib notebook.

This must be done before you plot anything, e.g.:

```<code>%matplotlib notebook

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d

fig = ...
</code>```

Title: Jupyter | How to rotate 3D graph

Body:
I am not sure about how to rotate graph in Python Jupyter notebook, its static for me and not rotate on mouse movement

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x =[1,2,3,4,5,6,7,8,9,10]
y =[5,6,2,3,13,4,1,2,4,8]
z =[2,3,3,3,5,7,9,11,9,10]

ax.scatter(x, y, z, c='r', marker='o')

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

Body:
To enable interactivity you need to use the notebook backend of matplotlib. You can do this by running %matplotlib notebook.

This must be done before you plot anything, e.g.:

%matplotlib notebook

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d

fig = ...


答:
```<code>JbtnStart != jbtnStart
</code>```

Java is a case sensitive language.

Body:
JbtnStart != jbtnStart

Java is a case sensitive language.


问:
can powerbi support and display images using binary?
I use a query from SQL to generate a report, and i have a column that is var binary for images.

Using GetData i pull this into PowerBI,

How do i then get the images generated ?

I can view the column containing the binary code in the query editor in PowerBI

Column name :Image

However it is not available outside of the query editor

Is there some setting i need to enable to get this to work, or is it even possible ?

Below is the query i use to pull the data:

```<code>Select
    prd.ShortCode                                       As 'Short Code'
,   st.CountryName                                      As 'Country'
,   st.Concept                                          As 'Partner'
,   prd.StyleDescription                                As 'Product Description'
,   prd.StockHoldingGroup                               As 'Stock Holding Group'
,   dept.DepartmentNumber                               As 'Department'
,   Sum(sls.SalesExVAT/sls.ExchangeRateEuro)            As 'Sales Ex VAT'
,   Sum(sls.SalesQuantity)                              As 'Sales Quantity'
,   Count(Distinct(sls.BranchNo))                       As 'No of Stores Sold'
,   img.SmallImage                                      As 'Image'

From
    euuksql01.dashboard.dbo.Calendar                cal

Inner Join
    euuksql01.dashboard.dbo.Sale                    sls
On  sls.DateID = cal.DateID

Inner Join
    euuksql01.dashboard.dbo.Product                 prd
On  prd.ProductID = sls.ProductID

Inner Join
    euuksql01.dashboard.dbo.Department              dept
On  dept.DeptID = prd.DepartmentID

Inner Join
    euuksql01.dashboard.dbo.DistrictStructure       st
On  sls.BranchNo = st.BranchNo

Inner Join
    euuksql01.dashboard.dbo.ProductImage                                img
On  img.ShortCode = prd.ShortCode

Where
    cal.FiscalYearWeek      = (Select FiscalYearWeek From euuksql01.dashboard.dbo.calendar where convert(date,getdate()-7) = FullDate)
And st.StoreType            = 'Concession'
And prd.StockHoldingGroup   Not In ('0441','0444','0445')
And dept.DepartmentNumber   Not In (31,32,50,51,52,53,54,55)

Group By
    prd.ShortCode
,   st.CountryName
,   st.Concept
,   prd.StyleDescription
,   prd.StockHoldingGroup
,   dept.DepartmentNumber
,   img.SmallImage
</code>```

答:
No, Power BI does not support displaying binary data as image.

It only supports displaying image from URL / inserting image at the moment.

You can find the relevant idea suggestion here. (with a lot of spam comments because of the word binary..)

Body:
I use a query from SQL to generate a report, and i have a column that is var binary for images.

Using GetData i pull this into PowerBI,

How do i then get the images generated ?

I can view the column containing the binary code in the query editor in PowerBI

Column name :Image

However it is not available outside of the query editor

Is there some setting i need to enable to get this to work, or is it even possible ?

Below is the query i use to pull the data:

Select
    prd.ShortCode                                       As 'Short Code'
,   st.CountryName                                      As 'Country'
,   st.Concept                                          As 'Partner'
,   prd.StyleDescription                                As 'Product Description'
,   prd.StockHoldingGroup                               As 'Stock Holding Group'
,   dept.DepartmentNumber                               As 'Department'
,   Sum(sls.SalesExVAT/sls.ExchangeRateEuro)            As 'Sales Ex VAT'
,   Sum(sls.SalesQuantity)                              As 'Sales Quantity'
,   Count(Distinct(sls.BranchNo))                       As 'No of Stores Sold'
,   img.SmallImage                                      As 'Image'

From
    euuksql01.dashboard.dbo.Calendar                cal

Inner Join
    euuksql01.dashboard.dbo.Sale                    sls
On  sls.DateID = cal.DateID

Inner Join
    euuksql01.dashboard.dbo.Product                 prd
On  prd.ProductID = sls.ProductID

Inner Join
    euuksql01.dashboard.dbo.Department              dept
On  dept.DeptID = prd.DepartmentID

Inner Join
    euuksql01.dashboard.dbo.DistrictStructure       st
On  sls.BranchNo = st.BranchNo

Inner Join
    euuksql01.dashboard.dbo.ProductImage                                img
On  img.ShortCode = prd.ShortCode

Where
    cal.FiscalYearWeek      = (Select FiscalYearWeek From euuksql01.dashboard.dbo.calendar where convert(date,getdate()-7) = FullDate)
And st.StoreType            = 'Concession'
And prd.StockHoldingGroup   Not In ('0441','0444','0445')
And dept.DepartmentNumber   Not In (31,32,50,51,52,53,54,55)

Group By
    prd.ShortCode
,   st.CountryName
,   st.Concept
,   prd.StyleDescription
,   prd.StockHoldingGroup
,   dept.DepartmentNumber
,   img.SmallImage


问:
Angular 2 Stop *NgFor if certain value is funded
I have a JSon like this:

```<code>[
{"Name": "xxxx", "country": "country1", etc...}
{"Name": "xxxx", "country": "country2", etc...}
{"Name": "xxxx", "country": "country1", etc...}
{"Name": "xxxx", "country": "country1", etc...}
]
</code>```

...and code:

```<code><ng-container *ngFor="let contact of contacts">
  <ng-container *ngIf="contact.country == 'country1'">
  <div>COUNTRY1</div>
</ng-container></ng-container>
</code>```

This code create the COUNTRY1 every time it find "country1"
i'd like to print the country value once. is it possible?

答:
I guess you need first to filter your list based on your filter criteria and print filtered result:

```<code><ng-container *ngFor="let contact of contacts | filterBy: 'country1'">
  <ng-container ...>
  <div>COUNTRY1</div>
</ng-container></ng-container>
</code>```

And create pipe to filter

```<code>@Pipe({
  name: 'filterBy'
})
export class FilterByPipe implements PipeTransform {
  transform(value: any[], filter: string): any[] {
    return value.filter(x => x.country === filter);
  }
}
</code>```

Body:
I have a JSon like this:

[
{"Name": "xxxx", "country": "country1", etc...}
{"Name": "xxxx", "country": "country2", etc...}
{"Name": "xxxx", "country": "country1", etc...}
{"Name": "xxxx", "country": "country1", etc...}
]

...and code:

<ng-container *ngFor="let contact of contacts">
  <ng-container *ngIf="contact.country == 'country1'">

COUNTRY1

</ng-container></ng-container>

This code create the COUNTRY1 every time it find "country1"
i'd like to print the country value once. is it possible?

Body:
I guess you need first to filter your list based on your filter criteria and print filtered result:

<ng-container *ngFor="let contact of contacts | filterBy: 'country1'">
  <ng-container ...>
  <div>COUNTRY1</div>
</ng-container></ng-container>

And create pipe to filter

@Pipe({
  name: 'filterBy'
})
export class FilterByPipe implements PipeTransform {
  transform(value: any[], filter: string): any[] {
    return value.filter(x => x.country === filter);
  }
}


问:
Plot a graph by reading coulmns from CSV
I have a csv file which contains four columns. The first column in time, the second, third and fourth columns are Accelerometer readings. I want to plot Time on X-Axis and the Accelerometer reading on Y-Axis.

Sample Data:

```<code>0   1.0969  9.7721  0.614
20  1.1146  9.7501  0.7444
40  1.1146  9.7501  0.7444
60  1.0124  9.7151  0.7169
79  1.0124  9.7151  0.7169
100 1.0927  9.7324  0.7356
120 1.0927  9.7324  0.7356
</code>```

Here is what I have so far.

```<code>from numpy import genfromtxt
import csv
import matplotlib.pyplot as plt
#import numpy as np

# Open the desired file for reading
f = open('walk-shoe.csv', "rb")

# create a object of csv class and read the file
# use ',' as a delimiter
reader = csv.reader(f, delimiter=',')

time_row = 0
accel_1_row = 0
accel_2_row = 0
accel_3_row = 0

time = []
accel_1 = []
accel_2 = []
accel_3 = []

# create a list of 'Time in ms'
for row in reader:
    # Skip the first row
    time_row = time_row + 1
if time_row == 1:
    continue
time.append(row[0])
accel_1.append(row[1])
accel_2.append(row[2])
accel_3.append(row[3])

# print the contents of the list
# print time
#print accel_1
#print accel_2
#print accel_3

# append all the list accelerometer list together
final_accel = []
final_accel.append(accel_1)
final_accel.append(accel_2)
final_accel.append(accel_3)

#print final_accel

# plot the graph
for i in range(len(final_accel)):
    plt.plot(time,[pt[i] for pt in final_accel],label = 'id %s'%i)
plt.legend()
plt.show()
</code>```

I want to plot all the sensor readings on one graph on y axis and time in x axis

答:
You seem to be importing numpy in the code you give, therefore I will take that to mean that library is available to you. Numpy lets you read in data very easily using numpy.loadtxt().

You can then create a for loop which goes through columns 1 to 3 and plots data against column 0 (time).

```<code>import numpy as np
import matplotlib.pyplot as plt

data = np.loadtxt('walk-shoe.csv', delimiter=',', dtype=float)
print (data)
#[[   0.        1.0969    9.7721    0.614 ]
# [  20.        1.1146    9.7501    0.7444]
# [  40.        1.1146    9.7501    0.7444]
# [  60.        1.0124    9.7151    0.7169]
# [  79.        1.0124    9.7151    0.7169]
# [ 100.        1.0927    9.7324    0.7356]
# [ 120.        1.0927    9.7324    0.7356]]

for i in range(1,data.shape[1]):
    plt.plot(data[:,0], data[:,i], label='id %s' %i)

plt.legend()
plt.show()
</code>```

Body:
I have a csv file which contains four columns. The first column in time, the second, third and fourth columns are Accelerometer readings. I want to plot Time on X-Axis and the Accelerometer reading on Y-Axis.

Sample Data:

0   1.0969  9.7721  0.614
20  1.1146  9.7501  0.7444
40  1.1146  9.7501  0.7444
60  1.0124  9.7151  0.7169
79  1.0124  9.7151  0.7169
100 1.0927  9.7324  0.7356
120 1.0927  9.7324  0.7356

Here is what I have so far.

from numpy import genfromtxt
import csv
import matplotlib.pyplot as plt
#import numpy as np

# Open the desired file for reading
f = open('walk-shoe.csv', "rb")

# create a object of csv class and read the file
# use ',' as a delimiter
reader = csv.reader(f, delimiter=',')

time_row = 0
accel_1_row = 0
accel_2_row = 0
accel_3_row = 0

time = []
accel_1 = []
accel_2 = []
accel_3 = []

# create a list of 'Time in ms'
for row in reader:
    # Skip the first row
    time_row = time_row + 1
if time_row == 1:
    continue
time.append(row[0])
accel_1.append(row[1])
accel_2.append(row[2])
accel_3.append(row[3])

# print the contents of the list
# print time
#print accel_1
#print accel_2
#print accel_3

# append all the list accelerometer list together
final_accel = []
final_accel.append(accel_1)
final_accel.append(accel_2)
final_accel.append(accel_3)

#print final_accel

# plot the graph
for i in range(len(final_accel)):
    plt.plot(time,[pt[i] for pt in final_accel],label = 'id %s'%i)
plt.legend()
plt.show()

I want to plot all the sensor readings on one graph on y axis and time in x axis

Body:
You seem to be importing numpy in the code you give, therefore I will take that to mean that library is available to you. Numpy lets you read in data very easily using numpy.loadtxt().

You can then create a for loop which goes through columns 1 to 3 and plots data against column 0 (time).

import numpy as np
import matplotlib.pyplot as plt

data = np.loadtxt('walk-shoe.csv', delimiter=',', dtype=float)
print (data)
#[[   0.        1.0969    9.7721    0.614 ]
# [  20.        1.1146    9.7501    0.7444]
# [  40.        1.1146    9.7501    0.7444]
# [  60.        1.0124    9.7151    0.7169]
# [  79.        1.0124    9.7151    0.7169]
# [ 100.        1.0927    9.7324    0.7356]
# [ 120.        1.0927    9.7324    0.7356]]

for i in range(1,data.shape[1]):
    plt.plot(data[:,0], data[:,i], label='id %s' %i)

plt.legend()
plt.show()


问:
Angular 5 compile very slow and sometimes runs out of memory
We have a medium-size Angular application. FWIW, Angular4 build produced app.js that is 4MB in size. We do not use Angular-CLI. When we first started it wasn't available; and then it didn't seem like we need it. The build time (npm start) took about 2 minutes.

Now we upgraded to Angular 5. The same build takes over an hour and on some machines reports Out of memory. I noticed in the task manager that the memory allocated by npm indeed goes up to about 2GB before it crashes. Not sure if it's 2GB limit for command-line session, or it runs out of physical memory (you can only conduct so many hour-long experiments :)

Anyway, is there a way to see what is causing npm slowness?

Platform: Windows 10, npm 5.5.1

UPDATE: configuration files:

package.json

```<code>{
  "name": "myapp",
  "version": "0.0.1",
  "description": "my awesome application",
  "scripts": {
    "start": "webpack-dev-server --inline --debug --progress --port 10071",
    "test": "karma start",
    "build": "rimraf dist && webpack -p --config ./config/webpack.prod.js --progress --profile --bail"
  },
  "dependencies": {
    "@angular/animations": "^5.0.1",
    "@angular/cdk": "^5.0.0-rc0",
    "@angular/common": "^5.0.1",
    "@angular/compiler": "^5.0.1",
    "@angular/core": "^5.0.1",
    "@angular/flex-layout": "^2.0.0-beta.10-4905443",
    "@angular/forms": "^5.0.1",
    "@angular/http": "^5.0.1",
    "@angular/material": "^5.0.0-rc0",
    "@angular/platform-browser": "^5.0.1",
    "@angular/platform-browser-dynamic": "^5.0.1",
    "@angular/platform-server": "^5.0.1",
    "@angular/router": "^5.0.1",
    "@ng-idle/core": "^2.0.0-beta.12",
    "@ng-idle/keepalive": "^2.0.0-beta.12",
    "@types/html2canvas": "^0.5.35",
    "@types/jspdf": "^1.1.31",
    "angular-svg-round-progressbar": "^1.2.0",
    "angular2-moment": "^1.7.0",
    "bootstrap": "^3.3.7",
    "core-js": "^2.5.1",
    "font-awesome": "^4.7.0",
    "hammerjs": "^2.0.8",
    "html2canvas": "^0.5.0-beta4",
    "jquery": "^3.2.1",
    "jspdf": "^1.3.5",
    "jspdf-autotable": "^2.3.2",
    "material-design-icons": "^3.0.1",
    "mime-types": "^2.1.17",
    "moment": "^2.19.1",
    "ngx-perfect-scrollbar": "^5.0.0",
    "primeng": "^5.0.0-rc.0",
    "rxjs": "^5.5.2",
    "zone.js": "^0.8.18"
  },
  "devDependencies": {
    "@angular/compiler-cli": "^5.0.1",
    "@types/jasmine": "^2.6.2",
    "@types/node": "^8.0.47",
    "angular2-template-loader": "^0.6.2",
    "awesome-typescript-loader": "^3.3.0",
    "css-loader": "^0.28.7",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^1.1.5",
    "html-loader": "^0.5.1",
    "html-webpack-plugin": "^2.30.1",
    "jasmine-core": "^2.8.0",
    "karma": "^1.7.1",
    "karma-jasmine": "^1.1.0",
    "karma-phantomjs-launcher": "^1.0.4",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "^2.0.5",
    "node-sass": "^4.6.0",
    "null-loader": "^0.1.1",
    "phantomjs-prebuilt": "^2.1.16",
    "raw-loader": "^0.5.1",
    "rimraf": "^2.6.2",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.19.0",
    "typescript": "^2.6.1",
    "url-loader": "^0.6.2",
    "webpack": "^3.8.1",
    "webpack-dev-server": "^2.9.4",
    "webpack-merge": "^4.1.1"
  }
}
</code>```

tsconfig.json

```<code>{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": true,
        "suppressImplicitAnyIndexErrors": true,
        "noStrictGenericChecks": true,
        "lib": [ "es2015", "dom" ],
        "typeRoots": [
            "./node_modules/@types"
        ],
        "types": [
            "html2canvas",
            "jasmine",
            "node",
            "jspdf"
        ]
    }
}
</code>```

答: The culprit was the version of Typescript. Once I downgraded to 2.5.1, it sped up! Same behavior on Angular 4 and 5.</p>

Body:
We have a medium-size Angular application. FWIW, Angular4 build produced app.js that is 4MB in size. We do not use Angular-CLI. When we first started it wasn't available; and then it didn't seem like we need it. The build time (npm start) took about 2 minutes.

Now we upgraded to Angular 5. The same build takes over an hour and on some machines reports Out of memory. I noticed in the task manager that the memory allocated by npm indeed goes up to about 2GB before it crashes. Not sure if it's 2GB limit for command-line session, or it runs out of physical memory (you can only conduct so many hour-long experiments :)

Anyway, is there a way to see what is causing npm slowness?

Platform: Windows 10, npm 5.5.1

UPDATE: configuration files:

package.json

{
  "name": "myapp",
  "version": "0.0.1",
  "description": "my awesome application",
  "scripts": {
    "start": "webpack-dev-server --inline --debug --progress --port 10071",
    "test": "karma start",
    "build": "rimraf dist && webpack -p --config ./config/webpack.prod.js --progress --profile --bail"
  },
  "dependencies": {
    "@angular/animations": "^5.0.1",
    "@angular/cdk": "^5.0.0-rc0",
    "@angular/common": "^5.0.1",
    "@angular/compiler": "^5.0.1",
    "@angular/core": "^5.0.1",
    "@angular/flex-layout": "^2.0.0-beta.10-4905443",
    "@angular/forms": "^5.0.1",
    "@angular/http": "^5.0.1",
    "@angular/material": "^5.0.0-rc0",
    "@angular/platform-browser": "^5.0.1",
    "@angular/platform-browser-dynamic": "^5.0.1",
    "@angular/platform-server": "^5.0.1",
    "@angular/router": "^5.0.1",
    "@ng-idle/core": "^2.0.0-beta.12",
    "@ng-idle/keepalive": "^2.0.0-beta.12",
    "@types/html2canvas": "^0.5.35",
    "@types/jspdf": "^1.1.31",
    "angular-svg-round-progressbar": "^1.2.0",
    "angular2-moment": "^1.7.0",
    "bootstrap": "^3.3.7",
    "core-js": "^2.5.1",
    "font-awesome": "^4.7.0",
    "hammerjs": "^2.0.8",
    "html2canvas": "^0.5.0-beta4",
    "jquery": "^3.2.1",
    "jspdf": "^1.3.5",
    "jspdf-autotable": "^2.3.2",
    "material-design-icons": "^3.0.1",
    "mime-types": "^2.1.17",
    "moment": "^2.19.1",
    "ngx-perfect-scrollbar": "^5.0.0",
    "primeng": "^5.0.0-rc.0",
    "rxjs": "^5.5.2",
    "zone.js": "^0.8.18"
  },
  "devDependencies": {
    "@angular/compiler-cli": "^5.0.1",
    "@types/jasmine": "^2.6.2",
    "@types/node": "^8.0.47",
    "angular2-template-loader": "^0.6.2",
    "awesome-typescript-loader": "^3.3.0",
    "css-loader": "^0.28.7",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^1.1.5",
    "html-loader": "^0.5.1",
    "html-webpack-plugin": "^2.30.1",
    "jasmine-core": "^2.8.0",
    "karma": "^1.7.1",
    "karma-jasmine": "^1.1.0",
    "karma-phantomjs-launcher": "^1.0.4",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "^2.0.5",
    "node-sass": "^4.6.0",
    "null-loader": "^0.1.1",
    "phantomjs-prebuilt": "^2.1.16",
    "raw-loader": "^0.5.1",
    "rimraf": "^2.6.2",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.19.0",
    "typescript": "^2.6.1",
    "url-loader": "^0.6.2",
    "webpack": "^3.8.1",
    "webpack-dev-server": "^2.9.4",
    "webpack-merge": "^4.1.1"
  }
}

tsconfig.json

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": true,
        "suppressImplicitAnyIndexErrors": true,
        "noStrictGenericChecks": true,
        "lib": [ "es2015", "dom" ],
        "typeRoots": [
            "./node_modules/@types"
        ],
        "types": [
            "html2canvas",
            "jasmine",
            "node",
            "jspdf"
        ]
    }
}


问:
How to use a config file for Unit Test and another for production in NODE
I have a value in config file which is used in an IF condition and once that value is set I am not able to get the minimum coverage required.

As work around I created two json files one is production.json and other is test.json and I want to use test.json for Unit Testing and production.json for normal execution.

Please let me know if there is a better way to test this scenario.

答:
You can do this with environment variables, prod settings should not be commited to SCM.

Check : dotenv


问:
Optimizing Nested mySQL Query... Or letting it run indefinitely
We are able to buy "trunks" from our VOIP provider and any time we go over our trunks, we get billed (a pretty penny) per minute. The provider gives NO reporting features, so we are pretty much guessing what trunks we should be getting and we are frequently guessing very poorly. So, I've setup a DB that has all of our call records in it. Then I created a SQL query that will tell me many trunks we would have needed to complete the call (row) for "free". Here's the query I'm using:

```<code>USE cdrs;
CREATE TEMPORARY TABLE IF NOT EXISTS cdr_temp
AS (
    SELECT callrecords.Timestamp, callrecords.CallEnd, callrecords.CallDirection, callrecords.Rate
    FROM cdrs.callrecords
);

UPDATE cdrs.callrecords AS a
SET TrunksNeeded = (
    select count(CallID)
    FROM cdr_temp AS b
    WHERE b.Timestamp <= a.Timestamp
    AND b.CallEnd >= a.Timestamp
    AND b.CallDirection = a.CallDirection
    AND b.Rate > 0
)
WHERE TrunksNeeded IS NULL AND Rate > 0
LIMIT 50;

DROP TEMPORARY TABLE IF EXISTS cdr_temp;
</code>```

Notice, the limit 50... For just 50 records this takes 50-80 seconds. I've tried optimizing using indexes. But nothing I do seems to help. Below is a show table dump:

```<code>CREATE TABLE 'callrecords' (
    'Timestamp' datetime DEFAULT NULL,
    'AccountID' varchar(45) DEFAULT NULL,
    'CNAME' varchar(45) DEFAULT NULL,
    'To' varchar(255) DEFAULT NULL,
    'From' varchar(255) DEFAULT NULL,
    'CallDirection' varchar(45) DEFAULT NULL,
    'hangup_cause' varchar(45) DEFAULT NULL,
    'BillingSeconds' int(11) DEFAULT NULL,
    'DurationSeconds' int(11) DEFAULT NULL,
    'Rate' float DEFAULT NULL,
    'RateName' varchar(45) DEFAULT NULL,
    'Cost' float DEFAULT NULL,
    'CallID' varchar(255) DEFAULT NULL,
    'CallEnd' datetime DEFAULT NULL,
    'TrunksNeeded' int(11) DEFAULT NULL,
    KEY 'idx_calldata' ('Timestamp','CallEnd','CallDirection','Rate')
) ENGINE=InnoDB DEFAULT CHARSET=utf8
</code>```

There's about 1.5 million records in the DB representing 90 days of call logs. And about 400k of them have a rate over 0. Meaning, they are billable, non-internal calls.

I have two questions.

1) Is there an easy way to change the table or the query I'm using to make the query run faster?

2) If not, by my calculations, it'll take 5 days to run the query against 30 days worth of records. I know it sounds crazy, but for the next year or so at least, I'm OK with that. Is there a way to issue this command so that it will eventually just complete in the background and ignore timeouts?

EDIT:
Adding an index to the temporary table as @Sentinel recommended helped a lot. Also, I noticed my HDD was maxing out. So I put the temp DB into memory and that was a huge improvement too. Looks like the query now will take a little under a day to run. But I'm still left with the question of how I can let a query run for that long...

Updated SQL Query:

```<code>USE cdrs;

CREATE TEMPORARY TABLE IF NOT EXISTS cdr_temp ENGINE=MEMORY
AS (
    SELECT callrecords.Timestamp, callrecords.CallEnd, callrecords.CallDirection, callrecords.Rate
    FROM cdrs.callrecords
);
alter table cdr_temp add index idx1 (CallDirection, rate, timestamp, callend);

UPDATE cdrs.callrecords AS a
SET TrunksNeeded = (
     select count(CallID)
     FROM cdr_temp AS b
     WHERE b.Timestamp <= a.Timestamp
     AND b.CallEnd >= a.Timestamp
     AND b.CallDirection = a.CallDirection
     AND b.Rate <> 0
)
WHERE TrunksNeeded IS NULL AND Rate <> 0
ORDER BY Timestamp
LIMIT 5000;

DROP TEMPORARY TABLE IF EXISTS cdr_temp;
</code>```

答:
Much of the time you report may well be spent in instantiating your temp table cdr_temp which has no indexes on it to improve performance.

Have you tried not using the temp table:

```<code>UPDATE cdrs.callrecords AS a
SET TrunksNeeded = (
    select count(CallID)
    FROM cdrs.callrecords AS b
    WHERE b.Timestamp <= a.Timestamp
    AND b.CallEnd >= a.Timestamp
    AND b.CallDirection = a.CallDirection
    AND b.Rate <> 0
)
WHERE TrunksNeeded IS NULL AND Rate > 0
LIMIT 50;
</code>```

You may also get better performance if you have an index on (CallDirection, Rate) especially if you test for b.Rate <> 0 instead of b.Rate > 0 since the query optimizer/planner may be able to eliminate more records before doing the range scans needed to check for overlapping calls.

To keep the temp table and add indexes to it (note the revised column order):

```<code>alter table cdr_temp add index idx1 (CallDirection, rate, timestamp, callend);
</code>```

This will use the temp table, with the new index and has the code changes I recommended.

```<code>UPDATE callrecords AS a
SET TrunksNeeded = (
    select count(CallID)
    FROM cdr_temp AS b
    WHERE b.CallDirection = a.CallDirection
    AND b.Rate <> 0
    AND a.Timestamp BETWEEN b.Timestamp AND b.CallEnd
)
WHERE TrunksNeeded IS NULL AND Rate > 0
LIMIT 50;
</code>```

Body:
We are able to buy "trunks" from our VOIP provider and any time we go over our trunks, we get billed (a pretty penny) per minute. The provider gives NO reporting features, so we are pretty much guessing what trunks we should be getting and we are frequently guessing very poorly. So, I've setup a DB that has all of our call records in it. Then I created a SQL query that will tell me many trunks we would have needed to complete the call (row) for "free". Here's the query I'm using:

USE cdrs;
CREATE TEMPORARY TABLE IF NOT EXISTS cdr_temp
AS (
    SELECT callrecords.Timestamp, callrecords.CallEnd, callrecords.CallDirection, callrecords.Rate
    FROM cdrs.callrecords
);

UPDATE cdrs.callrecords AS a
SET TrunksNeeded = (
    select count(CallID)
    FROM cdr_temp AS b
    WHERE b.Timestamp <= a.Timestamp
    AND b.CallEnd >= a.Timestamp
    AND b.CallDirection = a.CallDirection
    AND b.Rate > 0
)
WHERE TrunksNeeded IS NULL AND Rate > 0
LIMIT 50;

DROP TEMPORARY TABLE IF EXISTS cdr_temp;

Notice, the limit 50... For just 50 records this takes 50-80 seconds. I've tried optimizing using indexes. But nothing I do seems to help. Below is a show table dump:

CREATE TABLE 'callrecords' (
    'Timestamp' datetime DEFAULT NULL,
    'AccountID' varchar(45) DEFAULT NULL,
    'CNAME' varchar(45) DEFAULT NULL,
    'To' varchar(255) DEFAULT NULL,
    'From' varchar(255) DEFAULT NULL,
    'CallDirection' varchar(45) DEFAULT NULL,
    'hangup_cause' varchar(45) DEFAULT NULL,
    'BillingSeconds' int(11) DEFAULT NULL,
    'DurationSeconds' int(11) DEFAULT NULL,
    'Rate' float DEFAULT NULL,
    'RateName' varchar(45) DEFAULT NULL,
    'Cost' float DEFAULT NULL,
    'CallID' varchar(255) DEFAULT NULL,
    'CallEnd' datetime DEFAULT NULL,
    'TrunksNeeded' int(11) DEFAULT NULL,
    KEY 'idx_calldata' ('Timestamp','CallEnd','CallDirection','Rate')
) ENGINE=InnoDB DEFAULT CHARSET=utf8

There's about 1.5 million records in the DB representing 90 days of call logs. And about 400k of them have a rate over 0. Meaning, they are billable, non-internal calls.

I have two questions.

1) Is there an easy way to change the table or the query I'm using to make the query run faster?

2) If not, by my calculations, it'll take 5 days to run the query against 30 days worth of records. I know it sounds crazy, but for the next year or so at least, I'm OK with that. Is there a way to issue this command so that it will eventually just complete in the background and ignore timeouts?

EDIT:
Adding an index to the temporary table as @Sentinel recommended helped a lot. Also, I noticed my HDD was maxing out. So I put the temp DB into memory and that was a huge improvement too. Looks like the query now will take a little under a day to run. But I'm still left with the question of how I can let a query run for that long...

Updated SQL Query:

USE cdrs;

CREATE TEMPORARY TABLE IF NOT EXISTS cdr_temp ENGINE=MEMORY
AS (
    SELECT callrecords.Timestamp, callrecords.CallEnd, callrecords.CallDirection, callrecords.Rate
    FROM cdrs.callrecords
);
alter table cdr_temp add index idx1 (CallDirection, rate, timestamp, callend);

UPDATE cdrs.callrecords AS a
SET TrunksNeeded = (
     select count(CallID)
     FROM cdr_temp AS b
     WHERE b.Timestamp <= a.Timestamp
     AND b.CallEnd >= a.Timestamp
     AND b.CallDirection = a.CallDirection
     AND b.Rate <> 0
)
WHERE TrunksNeeded IS NULL AND Rate <> 0
ORDER BY Timestamp
LIMIT 5000;

DROP TEMPORARY TABLE IF EXISTS cdr_temp;

Body:
Much of the time you report may well be spent in instantiating your temp table cdr_temp which has no indexes on it to improve performance.

Have you tried not using the temp table:

UPDATE cdrs.callrecords AS a
SET TrunksNeeded = (
    select count(CallID)
    FROM cdrs.callrecords AS b
    WHERE b.Timestamp <= a.Timestamp
    AND b.CallEnd >= a.Timestamp
    AND b.CallDirection = a.CallDirection
    AND b.Rate <> 0
)
WHERE TrunksNeeded IS NULL AND Rate > 0
LIMIT 50;

You may also get better performance if you have an index on (CallDirection, Rate) especially if you test for b.Rate <> 0 instead of b.Rate > 0 since the query optimizer/planner may be able to eliminate more records before doing the range scans needed to check for overlapping calls.

To keep the temp table and add indexes to it (note the revised column order):

alter table cdr_temp add index idx1 (CallDirection, rate, timestamp, callend);

This will use the temp table, with the new index and has the code changes I recommended.

UPDATE callrecords AS a
SET TrunksNeeded = (
    select count(CallID)
    FROM cdr_temp AS b
    WHERE b.CallDirection = a.CallDirection
    AND b.Rate <> 0
    AND a.Timestamp BETWEEN b.Timestamp AND b.CallEnd
)
WHERE TrunksNeeded IS NULL AND Rate > 0
LIMIT 50;


问:
How to properly use a Case statement in T-SQL's order by clause?
I am having some difficulty with using a case statement in the Order By clause and am hoping for some guidance on what I am not taking into account.(SSMS 2017, SS2008 R2 SP3)

Given that I can run:

```<code>Select Myname = [name],
        OjectId = [object_id]
From sys.tables
Order By [name],[object_id]
</code>```

and can run:

```<code>Select Myname = [name],
        OjectId = [object_id]
From sys.tables
Order By Myname,OjectId
</code>```

as well as:

```<code>Declare @Sort as Varchar(25)
Set @Sort = 'Name'
Select Myname = [name],
        OjectId = [object_id]
From sys.tables
Order By case @Sort
    When 'Name'
    Then  [name]
    End
</code>```

I am having trouble understanding why this fails:

```<code>Declare @Sort as Varchar(25)
Set @Sort = 'Name'
Select Myname = [name],
        OjectId = [object_id]
From sys.tables
Order By case @Sort
    When 'Name'
    Then  Myname
    End
</code>```

as well as this:

```<code>Declare @Sort as Varchar(25)
Set @Sort = 'NameObj'
Select Myname = [name],
        OjectId = [object_id]
From sys.tables
Order By case @Sort
    When 'NameObj' then [name],[object_id]
    End
</code>```

Any input that anyone can share would be helpful.

答:
Here is how Microsoft define Then keyword in case statement

THEN

Is the expression returned when input_expression equals when_expression evaluates to TRUE, or Boolean_expression evaluates to TRUE. result expression is any valid expression.

Now lets define expression?

Expressions

Is a combination of symbols and operators that the SQL Server Database Engine evaluates to obtain a single data value. Simple expressions can be a single constant, variable, column, or scalar function.

https://learn.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql

https://learn.microsoft.com/en-us/sql/t-sql/language-elements/expressions-transact-sql

Body:
I am having some difficulty with using a case statement in the Order By clause and am hoping for some guidance on what I am not taking into account.(SSMS 2017, SS2008 R2 SP3)

Given that I can run:

Select Myname = [name],
        OjectId = [object_id]
From sys.tables
Order By [name],[object_id]

and can run:

Select Myname = [name],
        OjectId = [object_id]
From sys.tables
Order By Myname,OjectId

as well as:

Declare @Sort as Varchar(25)
Set @Sort = 'Name'
Select Myname = [name],
        OjectId = [object_id]
From sys.tables
Order By case @Sort
    When 'Name'
    Then  [name]
    End

I am having trouble understanding why this fails:

Declare @Sort as Varchar(25)
Set @Sort = 'Name'
Select Myname = [name],
        OjectId = [object_id]
From sys.tables
Order By case @Sort
    When 'Name'
    Then  Myname
    End

as well as this:

Declare @Sort as Varchar(25)
Set @Sort = 'NameObj'
Select Myname = [name],
        OjectId = [object_id]
From sys.tables
Order By case @Sort
    When 'NameObj' then [name],[object_id]
    End

Any input that anyone can share would be helpful.


问:
hiding text on mobile and hiding on sizes above mobile
I'm hiding some text with the following code

```<code>/* Smartphones in portrait mode (0-401px) */
@media only screen and ( max-width: 401px ) {
    .dontdisplayonmobile    {
    display: none !important;
}
}
</code>```

It stops it displaying on mobile. but the spacing it creates is still there so it's making the text go but not completely going as if there's nothing there.

I tried adding , but it didn't work

```<code>margin: 0 !important;
padding: 0 !important;
</code>```

Any ideas.?

EDIT

Does anyone know the best way to media query when you want to hide something on anything above 401 px for example.

Do you just put 100000000 or similar so it never shows ?

答:
On your site you have a span class called 'dontdisplayonmobie' that hides correctly when the viewport is less than 401 px. But your span class is in a paragraph (

). P has a padding-bottom: 1em; which is the empty space you still see. Remove the padding-bottom of that paragraph when the viewport is less than 401 px and it should look fine.

Body:
I'm hiding some text with the following code

/* Smartphones in portrait mode (0-401px) */
@media only screen and ( max-width: 401px ) {
    .dontdisplayonmobile    {
    display: none !important;
}
}

It stops it displaying on mobile. but the spacing it creates is still there so it's making the text go but not completely going as if there's nothing there.

I tried adding , but it didn't work

margin: 0 !important;
padding: 0 !important;

Any ideas.?

EDIT

Does anyone know the best way to media query when you want to hide something on anything above 401 px for example.

Do you just put 100000000 or similar so it never shows ?

Body: On your site you have a span class called 'dontdisplayonmobie' that hides correctly when the viewport is less than 401 px. But your span class is in a paragraph (<p> </p>). P has a padding-bottom: 1em; which is the empty space you still see. Remove the padding-bottom of that paragraph when the viewport is less than 401 px and it should look fine.


问:
Error between intel HD and nvidia GPU same directx application same Feature Level
My application runs fine or as i want on my local development pc with a intel hd. I force the feature level(10_1) by device creation to be on the same than my target machine.

However, if i run it on my intel HD it is all fine and working, but crashes on the target after a while and behaves differently.
I added code that uses CopySubresourceRegion(...) to copy from one render target to another. this seems to behave diffrently already until it crashes.
Maybe that has to do with the issue. I wonder thought, because i thought since i use the same runtime and feature level it should behave the same.

If my question is to general i can add specifics, but for now I am asking if you know what could cause that behavior and I am missing. I am still new to DirectX programming.

e: has this to do with threading?

答:
Fixed the issue by remote debugging on my target with enabled debug layer.

The error was indeed caused by CopySubresourceRegion(...).
The error was in the output locally (intel hd) and remote (nvidia). But the
nvidia seems to behave differently when this error arises and crashed (removed).

This link also says something about CopyResourceRegion(...) and the undefined behavior that caused the issue:

https://msdn.microsoft.com/de-de/library/windows/desktop/jj200584(v=vs.85).aspx

The fix was to simply handle the edge cases in my copy region parameters correct and not relying on the undefined behavior.

Thanks to Chuck Walbourn for hinting to solve the issue.


问:
How to fix "More than one file was found with OS independent path 'project.properties'" Error in Android Studio 3.0 Beta-6
I am using Android Gradle:3.0.0-beta-6 and it throws the following Error ever since I included Google Translation API.

```<code>FAILURE: Build failed with an exception.

What went wrong: Execution failed for task
':app:transformResourcesWithMergeJavaResForDebug'.

More than one file was found with OS independent path 'project.properties'
</code>```

This is my dependencies

```<code>dependencies {
    annotationProcessor 'com.google.auto.value:auto-value:1.2'
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:support-v4:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1',
 {
  exclude group: 'com.android.support', module: 'support-annotations'
    })
    api 'com.twitter.sdk.android:twitter-core:3.1.1'
    api 'com.google.cloud:google-cloud-translate:1.6.0'
}
</code>```

How can I fix this error and why exactly this is happening because I searched exhaustively for last 34 hrs and I didn't get an explanation.

答:
Have you tried adding this to your build.gradle?</p>

```<code>android {
    ...
    packagingOptions {
        exclude 'META-INF/project.properties'
    }
}
</code>```

Body:
I am using Android Gradle:3.0.0-beta-6 and it throws the following Error ever since I included Google Translation API.

FAILURE: Build failed with an exception.

What went wrong: Execution failed for task
':app:transformResourcesWithMergeJavaResForDebug'.

More than one file was found with OS independent path 'project.properties'

This is my dependencies

dependencies {
    annotationProcessor 'com.google.auto.value:auto-value:1.2'
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:support-v4:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1',
 {
  exclude group: 'com.android.support', module: 'support-annotations'
    })
    api 'com.twitter.sdk.android:twitter-core:3.1.1'
    api 'com.google.cloud:google-cloud-translate:1.6.0'
}

How can I fix this error and why exactly this is happening because I searched exhaustively for last 34 hrs and I didn't get an explanation.

Body:
Have you tried adding this to your build.gradle?

android {
    ...
    packagingOptions {
        exclude 'META-INF/project.properties'
    }
}


问:
Create view of linked tables and avoid NULL values in SQL
I have two tables Table_Company and Table_House which are linked. They contain the columns C_Index (unique), C_Name and H_Index (unique), C_Index, H_Renovated (FALSE / TRUE), H_Cost (NULL values allowed)  respectively. The column C_Index makes the link between the two tables.

How do I create a view which brings together C_Name and H_Cost for each company's house which is renovated (H_Renovated=TRUE) with the lowest cost (lowest value for H_Cost which is not NULL)? It should show for each company which was the lowest cost to renovate a house.

答:
Try this out   </p>

```<code>select c.c_name, h.h_index, h.h_cost
from @table_company c
join @table_house h on c.c_index = h.c_index
join  (select h_index, MIN(h.h_cost) as h_cost
from @table_house h
where h.h_cost is not null
and h_renovated = 1
group by h_index) as x on x.h_index = h.h_index and x.h_cost = h.h_cost
</code>```

Body:
Try this out

select c.c_name, h.h_index, h.h_cost
from @table_company c
join @table_house h on c.c_index = h.c_index
join  (select h_index, MIN(h.h_cost) as h_cost
from @table_house h
where h.h_cost is not null
and h_renovated = 1
group by h_index) as x on x.h_index = h.h_index and x.h_cost = h.h_cost


问:
How do you work around the need to cast an interfaced object back to its base class?
This question is meant to apply to interfaces in general, but I'll use AS3/Flex for my language.  It should be [mostly] obvious how to apply it in different languages.

If I create a base class, and it extends an interface, there is an explicit contract defined: for every method in the interface, the base class must implement said method.

This is easy enough.  But I don't understand why you have the capacity to cast an interfaced instance back to its original base class.  Of course, I've had to do this a few times (the example below is very close to the situation I'm struggling with), but that doesn't mean I understand it :^)

Here's a sample interface:

```<code>public interface IFooable extends IUIComponent {
    function runFoo():void;
}
</code>```

Let's say I create a base class, which extends VBox and implements the interface:

```<code>public class Foo extends VBox implements IFooable {
    public Foo() {
        super();
        //stuff here to create Foo..blah blah
    }
    public function runFoo():void {
        // do something to run foo
    }
}
</code>```

Now, the reason I used the interface, is because I want to guarantee "runFoo" is always implemented.  It is a common piece of functionality all of my classes should have, regardless of how they implement it.  Thus, my parent class (an Application) will instantiate Foo via its interface:

```<code>public function init():void {
    var foo:IFooable = new Foo();
    foo.percentHeight = 100; //works because of IUIComponent
}
</code>```

But, if I want to add Foo to the Application container, I now have to cast it back to the base class (or to a different base class):

```<code>public function init():void {
    var foo:IFooable = new Foo();
    foo.percentHeight = 100;

    addChild(foo as DisplayObject); //_have_ to cast, because addChild takes a 'DisplayObject' class type

    //could also do this:
    //addChild(foo as VBox);
}
</code>```

Wasn't the original intention to hide the implementation of Foo?  There is still an assumption that Foo is a DisplayObject.  Unfortunately, being able to add the custom object to a container seems impossible without casting.

Am I missing something entirely?  Is this really just a phenomenon in Flex/AS3?  If you have a container in the base API of a language, and it only allows you to add children of a certain class type, how do you then abstract out implementation?

For the record, this question appears to ask if this sort of operation is possible, but it doesn't really address why it might be bad design (and how to fix it).

2nd Thought:

Abstract Classes:

As Matthew pointed out, abstract classes helps solve some of this: I could create a base abstract class which inherits from the DisplayObject (or, in my case, the VBox, since it is a child of DisplayObject), and have the base class implement the interface.  Thus, any class which extends the abstract class would then be required to implement the methods therein.

Great idea -- but AS3 doesn't have abstract classes (to my knowledge, anyway).

So, I could create a base class which implements interface and extends the VBox, and inherit from it, and I could insert code in those methods which need to be extended; such code would throw an error if the base class is the executor.  Unfortunately, this is run-time checking as opposed to compile-time enforcement.

It's still a solution, though.

Context:

Some context might help:

I have an application which can have any number of sub-containers.  Each of these sub-containers will have their own respective configuration options, parameters, etc.  The application itself, however, has a global ApplicationControlBar which will contain the entry-point Menu for accessing these configuration options.  Therefore, whenever I add a sub-component to the main Application (via "addChild"), it will also "register" its own configuration options with the ApplicationControlBar menu.  This keeps the knowledge of configurability with the containers themselves, yet allows for a more unified means of accessing them.

Thus, when I create each container, I want to instantiate them via their interface so I can guarantee they can register with the ApplicationControlBar.  But when I add them to the application, they need to be the base class.

答:
Situation here is that it should be just the other way around for optimal practice... you shouldn't look to cast your interface to a displayobject but to have your instance already as a displayobject and then cast that to your interface to apply specific methods.

Let's say I have a baseclass Page and other subclasses Homepage, Contactpage and so on. Now you don't apply stuff to the baseclass as it's kind of abstract but you desing interfaces for your subclasses.

Let's say sub-pages implement for example an interface to deal with init, addedtostage, loader and whatever, and another one that deals with logic, and have eventually the base req to be manageble as displayobjects.

Getting to design the implementation.. one should just use an interface for specialized stuff and extend the subclass from where it mainly belongs to.. now a page has a 'base' meaning to be displayed (design wise.. the 'base'-class is a displayobject) but may require some specialization for which one builds an interface to cover that.

```<code>        public class Page extends Sprite{...}
        public interface IPageLoader{ function loadPage():void{}; function initPage():void{}; }
        public class Homepage extends Page implements IPageLoader
        { function loadPage():void{/*do stuff*/}; function initPage():void{/*do stuff*/}; }

        var currentpage:Page;
        var currentpageLoader:IPageLoader;

        currentpage = new Homepage;
        currentpageLoader = currentpage as IPageLoader;

        currentpageLoader.loadPage();
        currentpageLoader.initPage();

        addChild(currentpage);
        Tween(currentpage, x, CENTER);
</code>```

Body:
This question is meant to apply to interfaces in general, but I'll use AS3/Flex for my language.  It should be [mostly] obvious how to apply it in different languages.

If I create a base class, and it extends an interface, there is an explicit contract defined: for every method in the interface, the base class must implement said method.

This is easy enough.  But I don't understand why you have the capacity to cast an interfaced instance back to its original base class.  Of course, I've had to do this a few times (the example below is very close to the situation I'm struggling with), but that doesn't mean I understand it :^)

Here's a sample interface:

public interface IFooable extends IUIComponent {
    function runFoo():void;
}

Let's say I create a base class, which extends VBox and implements the interface:

public class Foo extends VBox implements IFooable {
    public Foo() {
        super();
        //stuff here to create Foo..blah blah
    }
    public function runFoo():void {
        // do something to run foo
    }
}

Now, the reason I used the interface, is because I want to guarantee "runFoo" is always implemented.  It is a common piece of functionality all of my classes should have, regardless of how they implement it.  Thus, my parent class (an Application) will instantiate Foo via its interface:

public function init():void {
    var foo:IFooable = new Foo();
    foo.percentHeight = 100; //works because of IUIComponent
}

But, if I want to add Foo to the Application container, I now have to cast it back to the base class (or to a different base class):

public function init():void {
    var foo:IFooable = new Foo();
    foo.percentHeight = 100;

    addChild(foo as DisplayObject); //_have_ to cast, because addChild takes a 'DisplayObject' class type

    //could also do this:
    //addChild(foo as VBox);
}

Wasn't the original intention to hide the implementation of Foo?  There is still an assumption that Foo is a DisplayObject.  Unfortunately, being able to add the custom object to a container seems impossible without casting.

Am I missing something entirely?  Is this really just a phenomenon in Flex/AS3?  If you have a container in the base API of a language, and it only allows you to add children of a certain class type, how do you then abstract out implementation?

For the record, this question appears to ask if this sort of operation is possible, but it doesn't really address why it might be bad design (and how to fix it).

2nd Thought:

Abstract Classes:

As Matthew pointed out, abstract classes helps solve some of this: I could create a base abstract class which inherits from the DisplayObject (or, in my case, the VBox, since it is a child of DisplayObject), and have the base class implement the interface.  Thus, any class which extends the abstract class would then be required to implement the methods therein.

Great idea -- but AS3 doesn't have abstract classes (to my knowledge, anyway).

So, I could create a base class which implements interface and extends the VBox, and inherit from it, and I could insert code in those methods which need to be extended; such code would throw an error if the base class is the executor.  Unfortunately, this is run-time checking as opposed to compile-time enforcement.

It's still a solution, though.

Context:

Some context might help:

I have an application which can have any number of sub-containers.  Each of these sub-containers will have their own respective configuration options, parameters, etc.  The application itself, however, has a global ApplicationControlBar which will contain the entry-point Menu for accessing these configuration options.  Therefore, whenever I add a sub-component to the main Application (via "addChild"), it will also "register" its own configuration options with the ApplicationControlBar menu.  This keeps the knowledge of configurability with the containers themselves, yet allows for a more unified means of accessing them.

Thus, when I create each container, I want to instantiate them via their interface so I can guarantee they can register with the ApplicationControlBar.  But when I add them to the application, they need to be the base class.

Body:
Situation here is that it should be just the other way around for optimal practice... you shouldn't look to cast your interface to a displayobject but to have your instance already as a displayobject and then cast that to your interface to apply specific methods.

Let's say I have a baseclass Page and other subclasses Homepage, Contactpage and so on. Now you don't apply stuff to the baseclass as it's kind of abstract but you desing interfaces for your subclasses.

Let's say sub-pages implement for example an interface to deal with init, addedtostage, loader and whatever, and another one that deals with logic, and have eventually the base req to be manageble as displayobjects.

Getting to design the implementation.. one should just use an interface for specialized stuff and extend the subclass from where it mainly belongs to.. now a page has a 'base' meaning to be displayed (design wise.. the 'base'-class is a displayobject) but may require some specialization for which one builds an interface to cover that.

        public class Page extends Sprite{...}
        public interface IPageLoader{ function loadPage():void{}; function initPage():void{}; }
        public class Homepage extends Page implements IPageLoader
        { function loadPage():void{/*do stuff*/}; function initPage():void{/*do stuff*/}; }

        var currentpage:Page;
        var currentpageLoader:IPageLoader;

        currentpage = new Homepage;
        currentpageLoader = currentpage as IPageLoader;

        currentpageLoader.loadPage();
        currentpageLoader.initPage();

        addChild(currentpage);
        Tween(currentpage, x, CENTER);


问:
Can I grant access to objects owned by another account in AWS S3 using bucket policies?
I want to control access to an object, which is created by another AWS account. Can I do that by bucket policies?
In other words, does bucket policies apply to objects that are owned by another account?

I do not have 2 AWS accounts so I can not test this case in action.

答:
Yes you can by creating a policy. Please find a sample policy below,

{
   "Version": "2012-10-17",
   "Statement": [
      {
         "Sid": "Example permissions",
         "Effect": "Allow",
         "Principal": {
            "AWS": "arn:aws:iam::AccountB-ID:root"
         },
         "Action": [
            "s3:GetBucketLocation",
            "s3:ListBucket"
         ],
         "Resource": [
            "arn:aws:s3:::examplebucket"
         ]
      }
   ]
}```
</div>
</div>
</p>

<p>You can do it through AWS console, CLI or API. Please find CLI sample below,</p>

```aws s3 ls s3://examplebucket --profile AccountBadmin
aws s3api get-bucket-location --bucket examplebucket --profile AccountBadmin
```

Please read documentation here for more details

Body:
Yes you can by creating a policy. Please find a sample policy below,

{
   "Version": "2012-10-17",
   "Statement": [
      {
         "Sid": "Example permissions",
         "Effect": "Allow",
         "Principal": {
            "AWS": "arn:aws:iam::AccountB-ID:root"
         },
         "Action": [
            "s3:GetBucketLocation",
            "s3:ListBucket"
         ],
         "Resource": [
            "arn:aws:s3:::examplebucket"
         ]
      }
   ]
}

You can do it through AWS console, CLI or API. Please find CLI sample below,

aws s3 ls s3://examplebucket --profile AccountBadmin
aws s3api get-bucket-location --bucket examplebucket --profile AccountBadmin

Please read documentation here for more details