问:
@expo/vector-icons not loaded when running from subfolder
I'm trying to use create-react-native-app with expo in a monorepo setup. When I start the app from a subfolder app/ and import @expo/vector-icons I get an error that the font family is missing.

```<code>"fontFamily" 'material' is not a system font and has not been loaded
through Expo.Font.loadAsync.
</code>```

If I start the app in the main src/ folder the icons load fine.

I've configured my rn-cli.config.js so that the app compiles and runs fine for other dependencies. My project is setup like a monorepo so that I can have multiple native apps in the repo.

```<code>src/
  MainApp.js
  package.json
  app/App.js
  app/app.json
  app/package.json
  app/rn-cli.config.js
  ...
</code>```

I've tried a couple things to no avail:

Install @expo/vector-icons in the subfolder package.json

Setting "assetExts": ["ttf"] in the app.json file.

My code (mostly from a fresh creat-react-native-app):

app/App.js

```<code>export { default } from "../MainApp";
</code>```

app/app.json

```<code>{
  "expo": {
    "sdkVersion": "22.0.0",
    "react": "16.0.0-beta.5"
  }
}
</code>```

app/package.json

```<code>{
  "private": true,
  "main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
  "scripts": {
    "native": "react-native-scripts start"
  },
  "dependencies": {
    "@expo/vector-icons": "^6.2.1",
    "expo": "^22.0.0",
    "react-native": "^0.49.0",
    "react-native-scripts": "1.7.0"
  }
}
</code>```

app/rn-cli.config.js

```<code>const blacklist = require("metro-bundler/src/blacklist");
const path = require("path");

const roots = [process.cwd(), path.resolve(__dirname, "..")];

const config = {
  getProjectRoots: () => roots,

  /**
   * Specify where to look for assets that are referenced using
   * `image!<image_name>`. Asset directories for images referenced using
   * `./<image.extension>` don't require any entry in here.
   */
  getAssetRoots: () => roots,

  /**
   * Returns a regular expression for modules that should be ignored by the
   * packager on a given platform.
   */
  getBlacklistRE: () =>
    blacklist([
      // Ignore the local react-native so that we avoid duplicate modules
      /\/app\/node_modules\/react-native\/.*/
    ])
};

module.exports = config;
</code>```

package.json

```<code>{
  "name": "react-native-app",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-native-scripts": "1.7.0"
  },
  "scripts": {
    "native": "cd app && yarn native"
  },
  "dependencies": {
    "@expo/vector-icons": "^6.2.1",
    "expo": "^22.0.0",
    "react": "16.0.0-beta.5",
    "react-native": "^0.49.0"
  }
}
</code>```

MainApp.js

```<code>import React from "react";
import { StyleSheet, Text, View } from "react-native";
import MaterialIcons from "react-native-vector-icons/MaterialIcons";

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>Open up App.js to start working on your app!</Text>
        <Text>Changes you make will automatically reload.</Text>
        <Text>Shake your phone to open the developer menu.</Text>
        <MaterialIcons name="search" color="black" size={32} />
        <MaterialIcons name="location-searching" color="black" size={32} />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
});
</code>```

答:
I am pretty new to react-native, but I had a similar issue, that I solved by not installing the expo Icons at all and using them normally. So in my package.json I have

```<code> "react-native-vector-icons": "^4.4.2",
</code>```

and I import fonts like:

```<code>import Icon from 'react-native-vector-icons/FontAwesome';
</code>```

I bet this is no perfect solution, but as expo is just a tool to make things easier, I don´t feel bad doing something that works, instead of using another tool, that complicates things ;)

Body:
I'm trying to use create-react-native-app with expo in a monorepo setup. When I start the app from a subfolder app/ and import @expo/vector-icons I get an error that the font family is missing.

"fontFamily" 'material' is not a system font and has not been loaded
through Expo.Font.loadAsync.

If I start the app in the main src/ folder the icons load fine.

I've configured my rn-cli.config.js so that the app compiles and runs fine for other dependencies. My project is setup like a monorepo so that I can have multiple native apps in the repo.

src/
  MainApp.js
  package.json
  app/App.js
  app/app.json
  app/package.json
  app/rn-cli.config.js
  ...

I've tried a couple things to no avail:

Install @expo/vector-icons in the subfolder package.json

Setting "assetExts": ["ttf"] in the app.json file.

My code (mostly from a fresh creat-react-native-app):

app/App.js

export { default } from "../MainApp";

app/app.json

{
  "expo": {
    "sdkVersion": "22.0.0",
    "react": "16.0.0-beta.5"
  }
}

app/package.json

{
  "private": true,
  "main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
  "scripts": {
    "native": "react-native-scripts start"
  },
  "dependencies": {
    "@expo/vector-icons": "^6.2.1",
    "expo": "^22.0.0",
    "react-native": "^0.49.0",
    "react-native-scripts": "1.7.0"
  }
}

app/rn-cli.config.js

const blacklist = require("metro-bundler/src/blacklist");
const path = require("path");

const roots = [process.cwd(), path.resolve(__dirname, "..")];

const config = {
  getProjectRoots: () => roots,

  /**
   * Specify where to look for assets that are referenced using
   * `image!<image_name>`. Asset directories for images referenced using
   * `./<image.extension>` don't require any entry in here.
   */
  getAssetRoots: () => roots,

  /**
   * Returns a regular expression for modules that should be ignored by the
   * packager on a given platform.
   */
  getBlacklistRE: () =>
    blacklist([
      // Ignore the local react-native so that we avoid duplicate modules
      /\/app\/node_modules\/react-native\/.*/
    ])
};

module.exports = config;

package.json

{
  "name": "react-native-app",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-native-scripts": "1.7.0"
  },
  "scripts": {
    "native": "cd app && yarn native"
  },
  "dependencies": {
    "@expo/vector-icons": "^6.2.1",
    "expo": "^22.0.0",
    "react": "16.0.0-beta.5",
    "react-native": "^0.49.0"
  }
}

MainApp.js

import React from "react";
import { StyleSheet, Text, View } from "react-native";
import MaterialIcons from "react-native-vector-icons/MaterialIcons";

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>Open up App.js to start working on your app!</Text>
        <Text>Changes you make will automatically reload.</Text>
        <Text>Shake your phone to open the developer menu.</Text>
        <MaterialIcons name="search" color="black" size={32} />
        <MaterialIcons name="location-searching" color="black" size={32} />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
});

Body:
I am pretty new to react-native, but I had a similar issue, that I solved by not installing the expo Icons at all and using them normally. So in my package.json I have

 "react-native-vector-icons": "^4.4.2",

and I import fonts like:

import Icon from 'react-native-vector-icons/FontAwesome';

I bet this is no perfect solution, but as expo is just a tool to make things easier, I don´t feel bad doing something that works, instead of using another tool, that complicates things ;)


来源: stackexchange

问:
Trimming Mako output
I really like the Mako templating system that's used in Pylons and a couple other Python frameworks, and my only complaint is how much WS leaks through even a simple inheritance scheme.

Is there anyway to accomplish below, without creating such huge WS gaps... or packing my code in like I started to do with base.mako?

Otherwise to get a grip on what I'm trying to accomplish with below.

Base is kind of like interface class for all views for the entire application, layout is just a prototype idea for 3-4 different layout files ( tables, pure CSS, etc ), and controller/action is a test to make sure my idea's are sane.

Short summary of question:  How to cut out the WS created in my Mako scheme?

Update: Is not a solution because it involves seeding all of my mako files with \'s
   http://www.makotemplates.org/docs/syntax.html#syntax_newline

/base.mako

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head><%def name="headtags()"></%def>${self.headtags()}</head>
  <body>
    <%def name="header()"></%def>${self.header()}${next.body()}<%def name="footer()"></%def>${self.footer()}
  </body>
</html>
</code>```

/layout.mako

```<code><%inherit file="/base.mako"/>
<%def name="headtags()">
   ${parent.headtags()}
   <script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>
</%def>
<%def name="header()">
  <h1>My Blogination</h1>
</%def>
<div id="content">${next.body()}</div>
</code>```

/controller/action.mako

```<code><%inherit file="/layout.mako" />
<%def name="headtags()">
    <title> Hello world, templating system is 1 percent done</title>
    ${parent.headtags()}
</%def>
Hello ${c.name}!
</code>```

rendered output:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title> Hello world, templating system is 1 percent done</title>

   <script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>

</head>
  <body>

  <h1>My Blogination</h1>

<div id="content">

Hello Anonymous!

</div>

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

答:
Found my own answer
http://docs.makotemplates.org/en/latest/filtering.html

It still required some trial and error, but using

```<code>t = TemplateLookup(directories=['/tmp'], default_filters=['trim'])
</code>```

dramatically cut down on whitespace bleed.  Additional savings can be found by checking the compiled template's and looking for any writes that are just pushing ' ' or similar.

OwnerDisplayName: David

ContentLicense: CC BY-SA 2.5

Title: Trimming Mako output

Body:
I really like the Mako templating system that's used in Pylons and a couple other Python frameworks, and my only complaint is how much WS leaks through even a simple inheritance scheme.

Is there anyway to accomplish below, without creating such huge WS gaps... or packing my code in like I started to do with base.mako?

Otherwise to get a grip on what I'm trying to accomplish with below.

Base is kind of like interface class for all views for the entire application, layout is just a prototype idea for 3-4 different layout files ( tables, pure CSS, etc ), and controller/action is a test to make sure my idea's are sane.

Short summary of question:  How to cut out the WS created in my Mako scheme?

Update: Is not a solution because it involves seeding all of my mako files with \'s
   http://www.makotemplates.org/docs/syntax.html#syntax_newline

/base.mako

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <%def name="headtags()"></%def>${self.headtags()}

    <%def name="header()"></%def>${self.header()}${next.body()}<%def name="footer()"></%def>${self.footer()}

/layout.mako

<%inherit file="/base.mako"/>
<%def name="headtags()">
   ${parent.headtags()}

</%def>
<%def name="header()">

My Blogination

</%def>

${next.body()}

/controller/action.mako

<%inherit file="/layout.mako" />
<%def name="headtags()">
    <title> Hello world, templating system is 1 percent done</title>
    ${parent.headtags()}
</%def>
Hello ${c.name}!

rendered output:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title> Hello world, templating system is 1 percent done</title>

My Blogination

Hello Anonymous!

LastEditorDisplayName: David

Body:
Found my own answer
http://docs.makotemplates.org/en/latest/filtering.html

It still required some trial and error, but using

t = TemplateLookup(directories=['/tmp'], default_filters=['trim'])

dramatically cut down on whitespace bleed.  Additional savings can be found by checking the compiled template's and looking for any writes that are just pushing ' ' or similar.

ContentLicense: CC BY-SA 3.0


问:
Performance on updates using cursor in PostgreSQL
I would like to know the performance difference in updating a table using the following method:

```<code>UPDATE films SET kind = 'Dramatic' WHERE CURRENT OF c_films;
</code>```

or like this:

```<code>UPDATE films SET kind = 'Dramatic' WHERE unique_indexed_int_column = 3000;
</code>```

Has anyone tested this or know how updates using cursors work so they can comment on this?

EDIT: I have now benchmarked this and found that it is infact around a third faster to do the latest example. I ran each of the queries 100000 times and timed the difference. I used psycopg2 using server side cursors to communicate with Postgres. I will investigate further to see whether I can find that this is not always the case.

答:
I'm not familiar with PostgreSQL, so I can only give you a generic answer.

First off, if indexed_int_column is not unique, the second statement will update multiple rows, whereas the first one will only update the row currently under the cursor c_films. So the statements are not identical.

Assuming uniqueness and the cursor c_films being at the one row where indexed_int_column = 3000, then updating should be very quick once the cursor is positioned under a certain row, as the cursor holds the information to directly access the physical location of this row. The second statement however, will have to fetch the index first, lookup the value 3000 in it and only then it will know the physical location of the row to update. That said, this lookup  operation had to be done for the cursor at one point to (if we did not iterate over the whole table that is). So in general it only pays off to use the cursor, when you have to read the data first anyway, and then want to update the same row you just read.

Body:
I would like to know the performance difference in updating a table using the following method:

UPDATE films SET kind = 'Dramatic' WHERE CURRENT OF c_films;

or like this:

UPDATE films SET kind = 'Dramatic' WHERE unique_indexed_int_column = 3000;

Has anyone tested this or know how updates using cursors work so they can comment on this?

EDIT: I have now benchmarked this and found that it is infact around a third faster to do the latest example. I ran each of the queries 100000 times and timed the difference. I used psycopg2 using server side cursors to communicate with Postgres. I will investigate further to see whether I can find that this is not always the case.


问:
How to print a dict with some deviations added to its values?
I'm having a bit of trouble figuring out how can I append my dictionary values so that every time I print them, they will be slightly different e.i ±10% deviation.

Example code:

```<code>shop = {
 'Milk': 1.24,
 'Coffee': 8.68,
 'Bread': 1.99,
 'Apples': 0.96,
 'Cakes': 12.96,

}
</code>```

Something to make the shop.values change ±10%:

```<code> random_keys = random.choices(population=list(stock.keys()), k=random.randrange(2, 5))
 print({k: stock[k] for k in random_keys})
</code>```

End result:

```<code>{'Milk': 1.35, 'Cakes' : 12.82}
</code>```

答:
Each time you want to print your dictionary with new random values, you could call this function:

```<code>import random
from typing import Dict

def print_with_deviations(my_dict: Dict[str, float],
                          *,
                          deviation: float = 0.1) -> None:
    print({key: f'{value * random.uniform(1 - deviation, 1 + deviation):.2f}'
           for key, value in my_dict.items()})
</code>```

Just like this: print_with_deviations(shop)

Or if you want to use not 10% but another deviation:

```<code>print_with_deviations(shop, deviation=0.2)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm having a bit of trouble figuring out how can I append my dictionary values so that every time I print them, they will be slightly different e.i ±10% deviation.

Example code:

shop = {
 'Milk': 1.24,
 'Coffee': 8.68,
 'Bread': 1.99,
 'Apples': 0.96,
 'Cakes': 12.96,

}

Something to make the shop.values change ±10%:

 random_keys = random.choices(population=list(stock.keys()), k=random.randrange(2, 5))
 print({k: stock[k] for k in random_keys})

End result:

{'Milk': 1.35, 'Cakes' : 12.82}

Body:
Each time you want to print your dictionary with new random values, you could call this function:

import random
from typing import Dict

def print_with_deviations(my_dict: Dict[str, float],
                          *,
                          deviation: float = 0.1) -> None:
    print({key: f'{value * random.uniform(1 - deviation, 1 + deviation):.2f}'
           for key, value in my_dict.items()})

Just like this: print_with_deviations(shop)

Or if you want to use not 10% but another deviation:

print_with_deviations(shop, deviation=0.2)


问:
Pass the value from a datePicker (start date) to a second datePicker (end date) with React JS
I have two datePickers (StartDate & EndDate) what I want to do is after I select the StartDate pass that value to the EndDate so I can choose a date after the StartDate.

For example if I choose my StartDate to be December 10 then when I go to my EndDate datepicker I wont be able to choose any date before December 10 so that will be my starting point for the EndDate datepicker.

This is my render method.

```<code>render() {

    const today = new Date();
    today.setDate(today.getDate() + 1);

    return (
      <div className={cr.container}>
        <div className ={cr.boton}>
          <Divider/>
        </div>
        <div className={cr.rows}>
          <div>
            <div>
              <DatePicker
                hintText="Start Date"
                minDate = {today}
              />
              <br/>
              <DatePicker
                hintText="End Date"
              />
            </div>
          </div>
        </div>

      </div>
    );
  }
}
</code>```

I'll appreciate the help on this...

Thanks in advance.

答:
Try updating the component state after selecting the start date:

```<code><DatePicker
    selected={this.state.startDate}
    onChange={this.handleChangeStart}
    hintText="Start Date"
    minDate={today}
/>
</code>```

... And then for your end date component, try using that value fore minDate

```<code><DatePicker
    selected={this.state.endDate}
    onChange={this.handleChangeEnd}
    hintText="End Date"
    minDate={this.state.startDate}
/>
</code>```

Body:
I have two datePickers (StartDate & EndDate) what I want to do is after I select the StartDate pass that value to the EndDate so I can choose a date after the StartDate.

For example if I choose my StartDate to be December 10 then when I go to my EndDate datepicker I wont be able to choose any date before December 10 so that will be my starting point for the EndDate datepicker.

This is my render method.

render() {

    const today = new Date();
    today.setDate(today.getDate() + 1);

    return (

          <Divider/>

              <DatePicker
                hintText="Start Date"
                minDate = {today}
              />

              <DatePicker
                hintText="End Date"
              />

    );
  }
}

I'll appreciate the help on this...

Thanks in advance.

Body:
Try updating the component state after selecting the start date:

<DatePicker
    selected={this.state.startDate}
    onChange={this.handleChangeStart}
    hintText="Start Date"
    minDate={today}
/>

... And then for your end date component, try using that value fore minDate

<DatePicker
    selected={this.state.endDate}
    onChange={this.handleChangeEnd}
    hintText="End Date"
    minDate={this.state.startDate}
/>


问:
What indicates the end of a TCP stream?
I'm attempting to make a low-level packet reader, sort of like wireshark, for learning purposes and fun.

Going into http parsing, I quickly found that there are these TCP streams, and that data doesn't all come in one packet.

EDIT: What I consider to be the stream I've been told is not the right term.  David Schwartz referred to it as a Query and EJP as a Sequence of Segments.

So I did a little reading on TCP, and I've read everywhere about the sequence and acknowledgment numbers, how they increase and wrap around etc..

Connection establishment and termination I already had knowledge of.

To be honest I've never been too good at interpretation or using google, but I've been at this for a bit, and I just can't seem to understand how the server/client ends a TCP stream.

I'm asking this because, after sending the totality of the http request, the server immediately replies with the page, so, as I've been going back and forward through packets in wireshark and I can't seem to find what delimits this stream (anything indicating length in the first packet or difference between the penultimate and last packets).

Is there no actual delimiter in TCP, and you just get the total length from the http headers's Content-Length?

As seen here, the first 3 packets are connection establishment.

The 3 after those are the sending of the http request (with first being ACK (the selected one), and the latest 2 being PSH & ACK).
The two after those are ACKs from the server, followed by the entirety of the response.

The last one is my ACK and the connection is never closed for the time I "recorded".

Thank you.

答:
The end of a TCP stream is marked by a segment whose FIN bit is sent.

However that isn't the answer to your real question, which is about the end of an HTTP request or response, which is determined by:

The Content-length, if present, or

The final chunk in a chunked transfer, if used, or

The FIN

if there is a body, otherwise the blank line after the headers as pointed out by @Barmar below.

Title: What indicates the end of a TCP stream?


问:
I implemented card views in XML on Android Studios. How can I have this act as buttons?
I'm new to Android and recently created a dashboard for my app. I followed a tutorial but it only covered the front end. I created a layout called content_main.xml with three Cardviews. Each of these Cardviews contains the code

```<code>android:clickable="true"
</code>```

Beginning the back end of things, I created a java receiver class called DashboardActivity (as seen below). I want to make my Cardviews clickable so that when one is clicked, I am taken to another screen within my app. The other screens in my app I am trying to get to are fragments. Each of these screens has its own java class in my "Fragments" folder. One of them, of which I try calling on in the code that follows is called SettingsViewFragment().

So far, I have tried the following. It does nothing.

```<code>public class DashboardActivity  extends AppCompatActivity {

    CardView cd1, cd2, cd3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        cd1 = (CardView) findViewById(R.id.dash_settings);
        cd2 = (CardView) findViewById(R.id.dash_profile);
        cd3 = (CardView) findViewById(R.id.dash_activity);

        cd1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment fragment1 = new SettingsViewFragment();
            }

        });
    }
}
</code>```

UPDATE: FULL CODE

```<code>public class DashboardActivity extends AppCompatActivity {

    CardView cd1, cd2, cd3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);

        cd1 = findViewById(R.id.dash_settings);
        cd2 = findViewById(R.id.dash_profile);
        cd3 = findViewById(R.id.dash_activity);

        cd1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.i("Testing 123 123 123");
            }

        });

    }
}
</code>```

And my XML: (it continues for 3 cards this way)

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.newproject.DashboardActivity"
    tools:showIn="@layout/toolbar">

    <FrameLayout
        android:id="@+id/dashframe"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:clipToPadding="false"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <android.support.v7.widget.CardView
            android:id="@+id/dash_settings"
            android:foreground="?android:attr/selectableItemBackground"
            android:clickable="true"
            android:focusable="true"
            android:layout_width="160dp"
            android:layout_height="190dp"
            android:layout_margin="10dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center">
                <ImageView
                    android:layout_width="64dp"
                    android:layout_height="64dp"
                    android:background="@drawable/bg_circle1"
                    android:src="@drawable/ic_settingspicture"
                    android:padding="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:layout_marginTop="10dp"
                    android:text="View your settings"/>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="@color/lightgray"
                    android:layout_margin="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="Follow along with guided tutorials"
                    android:padding="5dp"
                    android:textColor="@android:color/darker_gray"/>

            </LinearLayout>
</code>```

答:
Fragments should be instantiated with the newInstance() static method.

```<code>cd1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Fragment settingsFragment = SettingsFragment.newInstance();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.contentView, settingsFragment);
        fragmentTransaction.commit();
    }

});
</code>```

In the SettingsFragment

```<code> public static SettingsFragment newInstance() {
            return new SettingsFragment();
 }
</code>```

XML for content_main

```<code>LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:id="@+id/dash_settings"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        ...

     </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView
        android:id="@+id/dash_profile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        ...

        </android.support.v7.widget.CardView>

      <android.support.v7.widget.CardView
        android:id="@+id/dash_activity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        ...

        </android.support.v7.widget.CardView>

    <FrameLayout
        android:id="@+id/contentView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
    </FrameLayout>

</LinearLayout>
</code>```

This will transact the fragment into the FrameLayout that is positioned below the CardViews. Now this is probably not ideal, you would most likely want to launch a new activity that will host the fragment but this should work. Unless this is already in some Activity that hosts the fragment. But the key code is in the onClick.

Body:
I'm new to Android and recently created a dashboard for my app. I followed a tutorial but it only covered the front end. I created a layout called content_main.xml with three Cardviews. Each of these Cardviews contains the code

android:clickable="true"

Beginning the back end of things, I created a java receiver class called DashboardActivity (as seen below). I want to make my Cardviews clickable so that when one is clicked, I am taken to another screen within my app. The other screens in my app I am trying to get to are fragments. Each of these screens has its own java class in my "Fragments" folder. One of them, of which I try calling on in the code that follows is called SettingsViewFragment().

So far, I have tried the following. It does nothing.

public class DashboardActivity  extends AppCompatActivity {

    CardView cd1, cd2, cd3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        cd1 = (CardView) findViewById(R.id.dash_settings);
        cd2 = (CardView) findViewById(R.id.dash_profile);
        cd3 = (CardView) findViewById(R.id.dash_activity);

        cd1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment fragment1 = new SettingsViewFragment();
            }

        });
    }
}

UPDATE: FULL CODE

public class DashboardActivity extends AppCompatActivity {

    CardView cd1, cd2, cd3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);

        cd1 = findViewById(R.id.dash_settings);
        cd2 = findViewById(R.id.dash_profile);
        cd3 = findViewById(R.id.dash_activity);

        cd1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.i("Testing 123 123 123");
            }

        });

    }
}

And my XML: (it continues for 3 cards this way)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.newproject.DashboardActivity"
    tools:showIn="@layout/toolbar">

    <FrameLayout
        android:id="@+id/dashframe"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:clipToPadding="false"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <android.support.v7.widget.CardView
            android:id="@+id/dash_settings"
            android:foreground="?android:attr/selectableItemBackground"
            android:clickable="true"
            android:focusable="true"
            android:layout_width="160dp"
            android:layout_height="190dp"
            android:layout_margin="10dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:gravity="center">
                <ImageView
                    android:layout_width="64dp"
                    android:layout_height="64dp"
                    android:background="@drawable/bg_circle1"
                    android:src="@drawable/ic_settingspicture"
                    android:padding="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:layout_marginTop="10dp"
                    android:text="View your settings"/>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:background="@color/lightgray"
                    android:layout_margin="10dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="Follow along with guided tutorials"
                    android:padding="5dp"
                    android:textColor="@android:color/darker_gray"/>

            </LinearLayout>

Body:
Fragments should be instantiated with the newInstance() static method.

cd1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Fragment settingsFragment = SettingsFragment.newInstance();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.contentView, settingsFragment);
        fragmentTransaction.commit();
    }

});

In the SettingsFragment

 public static SettingsFragment newInstance() {
            return new SettingsFragment();
 }

XML for content_main

LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:id="@+id/dash_settings"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        ...

     </android.support.v7.widget.CardView>

        <android.support.v7.widget.CardView
        android:id="@+id/dash_profile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        ...

        </android.support.v7.widget.CardView>

      <android.support.v7.widget.CardView
        android:id="@+id/dash_activity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        ...

        </android.support.v7.widget.CardView>

    <FrameLayout
        android:id="@+id/contentView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
    </FrameLayout>

</LinearLayout>

This will transact the fragment into the FrameLayout that is positioned below the CardViews. Now this is probably not ideal, you would most likely want to launch a new activity that will host the fragment but this should work. Unless this is already in some Activity that hosts the fragment. But the key code is in the onClick.


问:
Why does boost have different downloads for windows and linux?
This might be a stupid question, but if boost is meant to be cross-platform, why does each platform need its own version?

If I want to package a (header-only) subset of boost as a dependency with my project, do I need to include both windows and linux versions?

答:
Line endings.

Windows IDEs typically prefer to edit all files in CR+LF (windows) line-ends.

All other platforms use LF (Unix) style line ends.

From old documentation:

.zip file

The .zip format is widely supported by both free decoders and
  commercial compress/archive utilities. If you don't already have a
  .zip file decoder, download one from the Info-ZIP web site, which
  supplies versions for many operating systems. Text file line endings
  in the .zip file are as supplied by each library developer.  This
  works fine for Windows, but not for Unix/Linux.  The .tar.gz and
  .tar.bz2 files supply Unix/Linux friendly line endings.

.tar.gz and .tar.bz2 files

The .tar.gz format is widely supported on Unix/Linux platforms. Some
  Windows compress/archive utilities can read the format as well.
  Because the gzip format compresses the archive as a single file rather
  than compressing each file individually, the .tar.gz file is smaller
  that the .zip file.

The .tar.bz2 format is becoming widely available on Unix/Linux
  platforms and is built into many tar utilities. This format differs
  for the .tar.gz format in the compression used, which is considerably
  better and therefore creates smaller files.

Text file line endings in the .tar.gz and .tar.bz2 files have been
  converted to newlines for ease of use on Unix/Linux platforms.


答:
You should be able to do something like this if you are using material-ui date picker:

```<code><DatePicker
   hintText="Start Date"
   minDate = {today}
   onChange={(null, date) => { setState({ startDate: date }); }}
   value={this.state.startDate}
/>

<DatePicker
   hintText="End Date"
   defaultDate={this.state.startDate + 1}
   {/* or however you calculate endDate */}
   value={this.state.endDate}
   onChange={(null, date) => { setState({ endDate: date }); }}
/>
</code>```

See the controlled example from the docs.

Title: Pass the value from a datePicker (start date) to a second datePicker (end date) with React JS

Body:
You should be able to do something like this if you are using material-ui date picker:

<DatePicker
   hintText="Start Date"
   minDate = {today}
   onChange={(null, date) => { setState({ startDate: date }); }}
   value={this.state.startDate}
/>

<DatePicker
   hintText="End Date"
   defaultDate={this.state.startDate + 1}
   {/* or however you calculate endDate */}
   value={this.state.endDate}
   onChange={(null, date) => { setState({ endDate: date }); }}
/>

See the controlled example from the docs.


问:
First-of-type and Last-of-type for CSS trick causes rounded edges to appear shorter in IE11
Using the radio+label trick for making custom styling of radio buttons, the first-of-type and last-of-type appears different in at least Internet Explorer 11 (IE11). The bottom part of the first and last of each appears to be cut off or shortened, according to the background shown.  If I remove or comment out all the first-of-type and last-of-type selectors, it displays default squared buttons just fine.  Screenshots below.

CSS that's affected:

```<code>/* Trick for custom styling of radio buttons */
.spr-status [type="radio"] + label,
.spr-field  [type="radio"] + label {
  margin: 0 1px;
  padding: 2px 5px;
  font-size: 14px;
  color:#444;
  background-color:#EEE;
  cursor: pointer;
}

.spr-status [type="radio"] + label:first-of-type,
.spr-field  [type="radio"] + label:first-of-type {
  border-top-left-radius: 7px;
  border-bottom-left-radius: 7px;
}

.spr-status [type="radio"] + label:last-of-type,
.spr-field  [type="radio"] + label:last-of-type {
  border-top-right-radius: 7px;
  border-bottom-right-radius: 7px;
}
</code>```

How it should look: Current version of Chrome & Firefox:

How it looks in IE (shortened background on first and last of type):

No IE11 (or any tested browser) issues when not using rounded corners with first-of-type and last-of-type

答:
Searching for this method again, I noticed that I forgot to explicitly put display in the first selector.

The solution was to add display:inline-block, as below:

```<code>.spr-status [type="radio"] + label,
.spr-field  [type="radio"] + label {
  display:inline-block;
...
</code>```

Body:
Using the radio+label trick for making custom styling of radio buttons, the first-of-type and last-of-type appears different in at least Internet Explorer 11 (IE11). The bottom part of the first and last of each appears to be cut off or shortened, according to the background shown.  If I remove or comment out all the first-of-type and last-of-type selectors, it displays default squared buttons just fine.  Screenshots below.

CSS that's affected:

/* Trick for custom styling of radio buttons */
.spr-status [type="radio"] + label,
.spr-field  [type="radio"] + label {
  margin: 0 1px;
  padding: 2px 5px;
  font-size: 14px;
  color:#444;
  background-color:#EEE;
  cursor: pointer;
}

.spr-status [type="radio"] + label:first-of-type,
.spr-field  [type="radio"] + label:first-of-type {
  border-top-left-radius: 7px;
  border-bottom-left-radius: 7px;
}

.spr-status [type="radio"] + label:last-of-type,
.spr-field  [type="radio"] + label:last-of-type {
  border-top-right-radius: 7px;
  border-bottom-right-radius: 7px;
}

How it should look: Current version of Chrome & Firefox:

How it looks in IE (shortened background on first and last of type):

No IE11 (or any tested browser) issues when not using rounded corners with first-of-type and last-of-type

Body:
Searching for this method again, I noticed that I forgot to explicitly put display in the first selector.

The solution was to add display:inline-block, as below:

.spr-status [type="radio"] + label,
.spr-field  [type="radio"] + label {
  display:inline-block;
...


问:
AWS ECS Periodical Job - Automatically Scale in instance
Amazon ECS provides really good service for scheduled tasks : ECS Scheduled tasks that works pretty well.
However it's important in this always keep one ECS instance in ECS cluster.
What is the best way:

Launch/scale in ECS instance in for periodical job (just before task execution);

Run ECS tasks on newly created instance;

Terminate/scale out instance after completion.

One possible workaround is to write lambda that will do smth. like that (launch ec2) but it looks as too much pain.

答:
Finally I found out an easy solution for that problem. Everything was quite simple:

Go to Autoscaling groups (This you can find on EC2 dashboard-> Autoscaling section);

Create scheduled action (In that case necessary frequency can be specified for your container instance);

Save your configuration. Instance will be added in the specified time.

In my case I also need to scale down this instance in 1 hour period.


问:
Access static variables within class in Swift
Is ClassName.staticVaribale the only way to access static variable within the class? I want something like self, but for class. Like class.staticVariable.

答:
I don't like the typealias way in this case. My workaround is: </p>

```<code>class MyClass {

   static let myStaticConst: Int = 1
   var myStaticConst:Int {
      return type(of: self).myStaticConst
   }

   func method() {
      let i:Int = myStaticConst
   }
}
</code>```

Body:
I don't like the typealias way in this case. My workaround is:

class MyClass {

   static let myStaticConst: Int = 1
   var myStaticConst:Int {
      return type(of: self).myStaticConst
   }

   func method() {
      let i:Int = myStaticConst
   }
}


问:
Syntax error in number base converter
I'm trying to write a program that converts number bases. For example, when converting from base 10 to base 2, the input 5 will result in the output 101.

This is my code:

```<code>#!/bin/sh
while read line
do
convert_base()
{
    number=$1
    inputbase=$2
    outputbase=$3
    echo "obase=$outputbase;ibase=$inputbase;$number" |bc
}
convert_base $1 $2 $3
echo $line >> $2
done < $1
</code>```

This gives me a syntax error, though. How can I fix this?

答:
This can be much simpler:</p>

```<code>while read num inb outb ; do echo "obase=$outb;ibase=$inb;$num" | bc; done
5 10 2
101
17 8 10
15
</code>```

Title: Syntax error in number base converter

Body:
I'm trying to write a program that converts number bases. For example, when converting from base 10 to base 2, the input 5 will result in the output 101.

This is my code:

#!/bin/sh
while read line
do
convert_base()
{
    number=$1
    inputbase=$2
    outputbase=$3
    echo "obase=$outputbase;ibase=$inputbase;$number" |bc
}
convert_base $1 $2 $3
echo $line >> $2
done < $1

This gives me a syntax error, though. How can I fix this?

Body:
This can be much simpler:

while read num inb outb ; do echo "obase=$outb;ibase=$inb;$num" | bc; done
5 10 2
101
17 8 10
15


问:
Android oldFile.renameTo(newFile) not working on lower Android

Hello fellow developers. I've been reading on here a lot, but can't find any solution for my problem.

I have an image file from a Camera Intent which I need to rename.
IMPORTANT: It works on Android 8.1 but doesn't work on 5.1.1 as tested.

I have no idea why, but came closer to the troublemaker. It's the renameTo(), which doesn't do anything, or at least I don't know of anything it does.
Here is the part of the code:

```<code>imgFinalName = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            format + ";" + lkwNr + ";" + telefonNr + ".jpg");
    if (imageFile.exists()){
        Log.d("Mati","Old File exists");
    }else{
        Log.d("Mati","Old File doesn't exist");
    }
    imageFile.renameTo(imgFinalName);
    Log.d("Mati","New Filename: " + imgFinalName.getName());
    Log.d("Mati","Path: " + imgFinalName.getAbsolutePath());
    if (imageFile.exists()){
        Log.d("Mati","Old File exists");
    }else{
        Log.d("Mati","Old File doesn't exist");
    }
    if (imgFinalName.exists()){
        Log.d("Mati","New File exists");
    }else{
        Log.d("Mati","New File doesn't exist");
    }
</code>```

The Log results are as followed:

Old file exists

New Filename: 2017-12-04_21:39:03;235;123123.jpg

Path: /storage/sdcard/Pictures/2017-12-04_21:39:03;235;123123.jpg

Old File exists

New File doesn't exist

So as you can see, the Old File exists, then I invoke the renameTo method, the old file still exists and the new file doesn't.

As I said, it works on Android 8.1, but doesn't on 5.1.1 and I really have no idea why... Would be nice if you guys had a solution. Feel free to ask questions

答:
Just as I turned off Android Studio and wanted to go to sleep, I thought about the SimpleDateFormat.

As you can see in the filename, its:

```<code>SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String format = s.format(new Date());
</code>```

I changed it now to:

```<code>SimpleDateFormat s = new SimpleDateFormat("yyyyMMddHHmmss");
String format = s.format(new Date());
</code>```

And it works. Note that the "-", "_" and ":" work in android 8.1.
Those options were added in the future I guess. Anyway, what a stupid mistake, but glad I found it. Sorry for bothering.

Body:
Hello fellow developers. I've been reading on here a lot, but can't find any solution for my problem.

I have an image file from a Camera Intent which I need to rename.
IMPORTANT: It works on Android 8.1 but doesn't work on 5.1.1 as tested.

I have no idea why, but came closer to the troublemaker. It's the renameTo(), which doesn't do anything, or at least I don't know of anything it does.
Here is the part of the code:

imgFinalName = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            format + ";" + lkwNr + ";" + telefonNr + ".jpg");
    if (imageFile.exists()){
        Log.d("Mati","Old File exists");
    }else{
        Log.d("Mati","Old File doesn't exist");
    }
    imageFile.renameTo(imgFinalName);
    Log.d("Mati","New Filename: " + imgFinalName.getName());
    Log.d("Mati","Path: " + imgFinalName.getAbsolutePath());
    if (imageFile.exists()){
        Log.d("Mati","Old File exists");
    }else{
        Log.d("Mati","Old File doesn't exist");
    }
    if (imgFinalName.exists()){
        Log.d("Mati","New File exists");
    }else{
        Log.d("Mati","New File doesn't exist");
    }

The Log results are as followed:

Old file exists

New Filename: 2017-12-04_21:39:03;235;123123.jpg

Path: /storage/sdcard/Pictures/2017-12-04_21:39:03;235;123123.jpg

Old File exists

New File doesn't exist

So as you can see, the Old File exists, then I invoke the renameTo method, the old file still exists and the new file doesn't.

As I said, it works on Android 8.1, but doesn't on 5.1.1 and I really have no idea why... Would be nice if you guys had a solution. Feel free to ask questions

Body:
Just as I turned off Android Studio and wanted to go to sleep, I thought about the SimpleDateFormat.

As you can see in the filename, its:

SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String format = s.format(new Date());

I changed it now to:

SimpleDateFormat s = new SimpleDateFormat("yyyyMMddHHmmss");
String format = s.format(new Date());

And it works. Note that the "-", "_" and ":" work in android 8.1.
Those options were added in the future I guess. Anyway, what a stupid mistake, but glad I found it. Sorry for bothering.


问:
help adding a field to my sql proc result
I have the SQL proc below that I am trying to add a SRS start date field to the result set of the proc below. I want to add a field for SRS_StartDate. The field should be defined as such: coalesce(projectMilestone.startDate, releaseschedual.startDate) as SRS_StartDate - but only for CID=37 as this is the cid for SRS

I am attaching my sample sql code below  for my current proc and a file of table structure and data as well.

you can test with these projectIDs as the excel file has data to support them.

```<code>exec rainbows '66,97,25'   --testing

create PROC rainbows
    @ProjectIDs NVARCHAR(1000)
AS

DECLARE @ProjIDs TABLE (id INT)
INSERT @ProjIDs  SELECT DISTINCT value FROM fn_Split(@ProjectIDs, ',')

--get core data set
SELECT t1.ProjectID,t1.ProjectName,
       case sco.CID when 37 then 'BRS Start'
                    when 37 then 'BRS end'
                    when 39 then 'SRS'
                    when 41 then 'SAD'
                    when 45 then 'Product Profile Review'
                    when 47 then 'SE Integration'
                    when 50 then 'IDE'
                    when 53 then 'UAT'
                    when 72 then 'PE Testing'
                    when 73 then 'Code Freeze'
                    when 75 then 'Dark Pod'
                    when 77 then 'Production' end CID,
       coalesce(t2.EndDate, t1.EndDate) MilestoneEndDate
INTO #DATA
FROM StatusCode sco
      LEFT OUTER JOIN
           (SELECT p.ProjectId,p.ProjectName,sc.CID,rs.EndDate
              FROM StatusCode sc
             INNER JOIN ReleaseSchedule rs ON sc.CID = rs.MilestoneCID
             INNER JOIN Project p  ON rs.ReleaseID = p.ReleaseID
             INNER JOIN @ProjIDs pList ON p.ProjectId = pList.id
            ) AS t1 ON sco.CID = t1.CID
      LEFT OUTER JOIN
           (SELECT sc.CID, pm.EndDate
              FROM StatusCode sc
             INNER JOIN ProjectMilestone pm ON sc.CID = pm.MilestoneCID
             INNER JOIN @ProjIDs pList ON pm.ProjectId = pList.id
            ) AS t2 ON sco.CID = t2.CID
WHERE sco.CID IN (37, 39, 41, 45, 47, 50, 53, 72, 73, 75, 77)

select ProjectID,ProjectName,[BRS start],[BRS Start] [BRS end],[SRS],[SAD],[Product Profile Review],[SE Integration],[IDE],[UAT],
                                         [PE Testing],[Code Freeze],[Dark Pod],[Production]
 from (
SELECT * FROM  #DATA
PIVOT (MAX(MilestoneEndDate) FOR CID IN ([BRS start],[BRS end],[SRS],[SAD],[Product Profile Review],[SE Integration],[IDE],[UAT],
                                         [PE Testing],[Code Freeze],[Dark Pod],[Production]
)) AS P) t1
</code>```

答:
```<code>create PROC rainbows
    @ProjectIDs NVARCHAR(1000)
AS

DECLARE @ProjIDs TABLE (id INT)
INSERT @ProjIDs  SELECT DISTINCT value FROM fn_Split(@ProjectIDs, ',')

--get core data set
SELECT t1.ProjectID,t1.ProjectName,
       case sco.CID when 37 then 'BRS Start'
                    when 37 then 'BRS end'
                    when 39 then 'SRS'
                    when 41 then 'SAD'
                    when 45 then 'Product Profile Review'
                    when 47 then 'SE Integration'
                    when 50 then 'IDE'
                    when 53 then 'UAT'
                    when 72 then 'PE Testing'
                    when 73 then 'Code Freeze'
                    when 75 then 'Dark Pod'
                    when 77 then 'Production' end CID,
       coalesce(t2.EndDate, t1.EndDate) MilestoneEndDate ,
       CASE WHEN sco.CID=37 then coalesce(t2.startDate, t1.startDate) else null as SRS_StartDate
INTO #DATA
FROM StatusCode sco
      LEFT OUTER JOIN
           (SELECT p.ProjectId,p.ProjectName,sc.CID,rs.EndDate, rs.startDate
              FROM StatusCode sc
             INNER JOIN ReleaseSchedule rs ON sc.CID = rs.MilestoneCID
             INNER JOIN Project p  ON rs.ReleaseID = p.ReleaseID
             INNER JOIN @ProjIDs pList ON p.ProjectId = pList.id
            ) AS t1 ON sco.CID = t1.CID
      LEFT OUTER JOIN
           (SELECT sc.CID, pm.EndDate, pm.startDate
              FROM StatusCode sc
             INNER JOIN ProjectMilestone pm ON sc.CID = pm.MilestoneCID
             INNER JOIN @ProjIDs pList ON pm.ProjectId = pList.id
            ) AS t2 ON sco.CID = t2.CID
WHERE sco.CID IN (37, 39, 41, 45, 47, 50, 53, 72, 73, 75, 77)

select ProjectID,ProjectName,SRS_StartDate,[BRS start],[BRS Start] [BRS end],[SRS],[SAD],[Product Profile Review],[SE Integration],[IDE],[UAT],
                                         [PE Testing],[Code Freeze],[Dark Pod],[Production]
 from (
SELECT * FROM  #DATA
PIVOT (MAX(MilestoneEndDate) FOR CID IN ([BRS start],[BRS end],[SRS],[SAD],[Product Profile Review],[SE Integration],[IDE],[UAT],
                                         [PE Testing],[Code Freeze],[Dark Pod],[Production]
)) AS P) t1
</code>```

Body:
I have the SQL proc below that I am trying to add a SRS start date field to the result set of the proc below. I want to add a field for SRS_StartDate. The field should be defined as such: coalesce(projectMilestone.startDate, releaseschedual.startDate) as SRS_StartDate - but only for CID=37 as this is the cid for SRS

I am attaching my sample sql code below  for my current proc and a file of table structure and data as well.

you can test with these projectIDs as the excel file has data to support them.

exec rainbows '66,97,25'   --testing

create PROC rainbows
    @ProjectIDs NVARCHAR(1000)
AS

DECLARE @ProjIDs TABLE (id INT)
INSERT @ProjIDs  SELECT DISTINCT value FROM fn_Split(@ProjectIDs, ',')

--get core data set
SELECT t1.ProjectID,t1.ProjectName,
       case sco.CID when 37 then 'BRS Start'
                    when 37 then 'BRS end'
                    when 39 then 'SRS'
                    when 41 then 'SAD'
                    when 45 then 'Product Profile Review'
                    when 47 then 'SE Integration'
                    when 50 then 'IDE'
                    when 53 then 'UAT'
                    when 72 then 'PE Testing'
                    when 73 then 'Code Freeze'
                    when 75 then 'Dark Pod'
                    when 77 then 'Production' end CID,
       coalesce(t2.EndDate, t1.EndDate) MilestoneEndDate
INTO #DATA
FROM StatusCode sco
      LEFT OUTER JOIN
           (SELECT p.ProjectId,p.ProjectName,sc.CID,rs.EndDate
              FROM StatusCode sc
             INNER JOIN ReleaseSchedule rs ON sc.CID = rs.MilestoneCID
             INNER JOIN Project p  ON rs.ReleaseID = p.ReleaseID
             INNER JOIN @ProjIDs pList ON p.ProjectId = pList.id
            ) AS t1 ON sco.CID = t1.CID
      LEFT OUTER JOIN
           (SELECT sc.CID, pm.EndDate
              FROM StatusCode sc
             INNER JOIN ProjectMilestone pm ON sc.CID = pm.MilestoneCID
             INNER JOIN @ProjIDs pList ON pm.ProjectId = pList.id
            ) AS t2 ON sco.CID = t2.CID
WHERE sco.CID IN (37, 39, 41, 45, 47, 50, 53, 72, 73, 75, 77)

select ProjectID,ProjectName,[BRS start],[BRS Start] [BRS end],[SRS],[SAD],[Product Profile Review],[SE Integration],[IDE],[UAT],
                                         [PE Testing],[Code Freeze],[Dark Pod],[Production]
 from (
SELECT * FROM  #DATA
PIVOT (MAX(MilestoneEndDate) FOR CID IN ([BRS start],[BRS end],[SRS],[SAD],[Product Profile Review],[SE Integration],[IDE],[UAT],
                                         [PE Testing],[Code Freeze],[Dark Pod],[Production]
)) AS P) t1


问:
BLE Accelerometer
I want to send accelerometer values over BLE to an iOS app using a nordic nRF52. The app works perfectly with standard BLE services (HeartRate Measurement, Thermometer etc), but not when I try and define a custom BLE Accelerometer Service. Is there anything I need to do specifically when defining UUID's and things? Any help would be much appreciated, thanks.

Below is my custom Accelerometer class, and the main.cpp uploaded to the nRF52 below that.

```<code>#ifndef __BLE_ACCELEROMETER_SERVICE__
#define __BLE_ACCELEROMETER_SERVICE__

#include "ble/BLE.h"

#define UUID_ACCELEROMETER_SERVICE  "00000000-0000-1000-7450-BE2E44B06B00"

#define UUID_X_CHARACTERISTIC       "00000000-0000-1000-7450-BE2E44B06B01"
#define UUID_Y_CHARACTERISTIC       "00000000-0000-1000-7450-BE2E44B06B02"
#define UUID_Z_CHARACTERISTIC       "00000000-0000-1000-7450-BE2E44B06B03"

/**
 * @class AccelerometerService
 * @brief BLE Custom Accelerometer Service. This provides the x, y and z values of the SEEED 101020051 Grove accelerometer connected to the Nordic nRF52 DK.
 */

class AccelerometerService
{
public:

    /**
     *  @brief Add the Accelerometer Service to an existing BLE object, initialize with values for x, y and z readings, represented as doubles.
     *  @param _ble Reference to the BLE device
     *  @param _x   Initial value for the x axis
     *  @param _y   Initial value for the y axis
     *  @param _z   Initial value for the z axis
     */
    AccelerometerService(BLE &_ble, double _x = 0, double _y = 0, double _z = 0) :
    ble(_ble),
    x(_x),
    y(_y),
    z(_z),
    xAngleCharacteristic(UUID_X_CHARACTERISTIC, &x, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY),
    yAngleCharacteristic(UUID_Y_CHARACTERISTIC, &y, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY),
    zAngleCharacteristic(UUID_Z_CHARACTERISTIC, &z, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY) {

        GattCharacteristic  *readings[] = {&xAngleCharacteristic, &yAngleCharacteristic, &zAngleCharacteristic, };
        GattService         accelerometerService(UUID_ACCELEROMETER_SERVICE, readings, sizeof(readings) / sizeof(GattCharacteristic *));

        ble.addService(accelerometerService);
    }

    /**
     * @brief Update the x axis rotation with a new value.
     * @param _x - New x value from accelerometer
     */
    void update_x(uint8_t _x) {
        x = _x;
        ble.gattServer().write(xAngleCharacteristic.getValueHandle(), &x, 1);
    }

    /**
     * @brief Update the y axis rotation with a new value.
     * @param _z - New y value from accelerometer
     */
    void update_y(uint8_t _y) {
        y = _y;
        ble.gattServer().write(yAngleCharacteristic.getValueHandle(), &y, 1);
    }

    /**
     * @brief Update the z axis rotation with a new value.
     * @param _z - New z value from accelerometer
     */
    void update_z(uint8_t _z) {
        z = _z;
        ble.gattServer().write(zAngleCharacteristic.getValueHandle(), &z, 1);
    }

protected:

    /**
     * A reference to the underlying BLE instance that this object is attached to.
     * The services and characteristics will be registered in this BLE instance.
     */
    BLE &ble;

    /**
     * The current x axis rotation, represented as a double
     */
    uint8_t x;
    /**
     * The current y axis rotation, represented as a double
     */
    uint8_t y;
    /**
     * The current z axis rotation, represented as a double
     */
    uint8_t z;

    /**
     * A ReadOnlyGattCharacteristic that allows access to the peer device to the
     * x axis rotation value through BLE.
     */
    ReadOnlyGattCharacteristic<uint8_t>   xAngleCharacteristic;
    /**
     * A ReadOnlyGattCharacteristic that allows access to the peer device to the
     * y axis rotation value through BLE.
     */
    ReadOnlyGattCharacteristic<uint8_t>   yAngleCharacteristic;
    /**
     * A ReadOnlyGattCharacteristic that allows access to the peer device to the
     * z axis rotation value through BLE.
     */
    ReadOnlyGattCharacteristic<uint8_t>   zAngleCharacteristic;
};

#endif /* __BLE_ACCELEROMETER_SERVICE__ */
</code>```

Below is the main.cpp file I am using via mbed.org.

```<code>#include "mbed.h"
#include "ble/BLE.h"
#include "AccelerometerService.h"

DigitalOut led1(LED1);
DigitalOut led2(LED2);

static AccelerometerService *accelerometerServicePtr;

// Function declarations
void bleInitComplete(BLE::InitializationCompleteCallbackContext *);
void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *);

// Set device name and inital setup options
static const char       DEVICE_NAME[]        = "nRF52";
static const uint16_t   uuid16_list[]        = {0xFFFF};
static volatile bool    triggerSensorPolling = false;

static float           x = 10.0;    // Dummy values for accelerometer for now
static float           y = 15.0;
static float           z = 18.0;

/*
 *  Initialization callback
 */
void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
{
    BLE &ble = params->ble;
    ble_error_t error = params->error;

    if (error != BLE_ERROR_NONE){
        printf("*** Error occured ***\n");
        return;
    }

    /* Ensure that it is the default instance of BLE */
    if(ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
        return;
    }

    ble.gap().onDisconnection(disconnectionCallback);

    // Setup primary service
    accelerometerServicePtr = new AccelerometerService(ble, x, y, z);

    // Setup advertising
    ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);

    // Advertising payload has a maximum of 31 bytes
    // BLE only, no classic BT
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED |
                                           GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
    // Add name
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
    // UUIDs broadcast in advertising packet
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list));
    // Set advertising interval
    ble.gap().setAdvertisingInterval(100); //100ms

    // Start advertising
    ble.gap().startAdvertising();
}

/**
 * Restart advertising on disconnection
 */
void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *)
{
    BLE::Instance(BLE::DEFAULT_INSTANCE).gap().startAdvertising();
}

/**
 * This function is called when the ble initialization process has failed
 */
void onBleInitError(BLE &ble, ble_error_t error)
{
    /* Avoid compiler warnings */
    (void) ble;
    (void) error;
    /* Initialization error handling should go here */
}

int main()
{
    // Initialize program
    printf("\n\r *** Starting Main Loop *** \r\n");

    BLE &ble = BLE::Instance(BLE::DEFAULT_INSTANCE);
    ble.init(bleInitComplete);

    while (ble.hasInitialized() == false)
    {
        while (true)
        {
            if (triggerSensorPolling && ble.gap().getState().connected) {
                triggerSensorPolling = false;

                accelerometerServicePtr->update_x(x);
                accelerometerServicePtr->update_y(y);
                accelerometerServicePtr->update_z(z);
            }
            else {
                ble.waitForEvent();   // Infinite loop waiting for BLE interrupt events
            }
        }
    }
}
</code>```

答:
This is wrong, you are sending a bad advertising packet. (0xFFFF == Insert 16 bit service here)

```<code>...
uuid16_list[]        = {0xFFFF};
...
...
COMPLETE_LIST_128BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list)
</code>```

There are for Bluetooth reserved 16 bit identifiers, which use the reserved UUID space.

Check This page: What range of Bluetooth UUIDs can be used for vendor defined profiles?

What you need to do is specify the full UUID in the 128 bit list.

I cant compile this but try something like this

```<code>char 128bitlist[] = {,0x00,0x00,0x00,0x00 ,0x00,0x00 ,0x10,0x00 ,0x74,0x50 ,0xBE,0x2E,0x44,0xB0,0x6B,0x00};
...
...
ble.gap().accumulateAdvertisingPayload (GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS, (uint8_t *) 128bitlist, 1);
</code>```

An outstanding tool for checking your advertising data is Lightblue.  It is free and really informative.  You should check the advertising on both Android and IOS with this tool.

Another thing to check is that you dont overfill the advertising packet.  If your device name is too long, plus the 128 bit UUID, you can overfill and corrupt the packet. Try removing the name or making it really short.

Title: BLE Accelerometer

Body:
I want to send accelerometer values over BLE to an iOS app using a nordic nRF52. The app works perfectly with standard BLE services (HeartRate Measurement, Thermometer etc), but not when I try and define a custom BLE Accelerometer Service. Is there anything I need to do specifically when defining UUID's and things? Any help would be much appreciated, thanks.

Below is my custom Accelerometer class, and the main.cpp uploaded to the nRF52 below that.

#ifndef __BLE_ACCELEROMETER_SERVICE__
#define __BLE_ACCELEROMETER_SERVICE__

#include "ble/BLE.h"

#define UUID_ACCELEROMETER_SERVICE  "00000000-0000-1000-7450-BE2E44B06B00"

#define UUID_X_CHARACTERISTIC       "00000000-0000-1000-7450-BE2E44B06B01"
#define UUID_Y_CHARACTERISTIC       "00000000-0000-1000-7450-BE2E44B06B02"
#define UUID_Z_CHARACTERISTIC       "00000000-0000-1000-7450-BE2E44B06B03"

/**
 * @class AccelerometerService
 * @brief BLE Custom Accelerometer Service. This provides the x, y and z values of the SEEED 101020051 Grove accelerometer connected to the Nordic nRF52 DK.
 */

class AccelerometerService
{
public:

    /**
     *  @brief Add the Accelerometer Service to an existing BLE object, initialize with values for x, y and z readings, represented as doubles.
     *  @param _ble Reference to the BLE device
     *  @param _x   Initial value for the x axis
     *  @param _y   Initial value for the y axis
     *  @param _z   Initial value for the z axis
     */
    AccelerometerService(BLE &_ble, double _x = 0, double _y = 0, double _z = 0) :
    ble(_ble),
    x(_x),
    y(_y),
    z(_z),
    xAngleCharacteristic(UUID_X_CHARACTERISTIC, &x, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY),
    yAngleCharacteristic(UUID_Y_CHARACTERISTIC, &y, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY),
    zAngleCharacteristic(UUID_Z_CHARACTERISTIC, &z, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY) {

        GattCharacteristic  *readings[] = {&xAngleCharacteristic, &yAngleCharacteristic, &zAngleCharacteristic, };
        GattService         accelerometerService(UUID_ACCELEROMETER_SERVICE, readings, sizeof(readings) / sizeof(GattCharacteristic *));

        ble.addService(accelerometerService);
    }

    /**
     * @brief Update the x axis rotation with a new value.
     * @param _x - New x value from accelerometer
     */
    void update_x(uint8_t _x) {
        x = _x;
        ble.gattServer().write(xAngleCharacteristic.getValueHandle(), &x, 1);
    }

    /**
     * @brief Update the y axis rotation with a new value.
     * @param _z - New y value from accelerometer
     */
    void update_y(uint8_t _y) {
        y = _y;
        ble.gattServer().write(yAngleCharacteristic.getValueHandle(), &y, 1);
    }

    /**
     * @brief Update the z axis rotation with a new value.
     * @param _z - New z value from accelerometer
     */
    void update_z(uint8_t _z) {
        z = _z;
        ble.gattServer().write(zAngleCharacteristic.getValueHandle(), &z, 1);
    }

protected:

    /**
     * A reference to the underlying BLE instance that this object is attached to.
     * The services and characteristics will be registered in this BLE instance.
     */
    BLE &ble;

    /**
     * The current x axis rotation, represented as a double
     */
    uint8_t x;
    /**
     * The current y axis rotation, represented as a double
     */
    uint8_t y;
    /**
     * The current z axis rotation, represented as a double
     */
    uint8_t z;

    /**
     * A ReadOnlyGattCharacteristic that allows access to the peer device to the
     * x axis rotation value through BLE.
     */
    ReadOnlyGattCharacteristic<uint8_t>   xAngleCharacteristic;
    /**
     * A ReadOnlyGattCharacteristic that allows access to the peer device to the
     * y axis rotation value through BLE.
     */
    ReadOnlyGattCharacteristic<uint8_t>   yAngleCharacteristic;
    /**
     * A ReadOnlyGattCharacteristic that allows access to the peer device to the
     * z axis rotation value through BLE.
     */
    ReadOnlyGattCharacteristic<uint8_t>   zAngleCharacteristic;
};

#endif /* __BLE_ACCELEROMETER_SERVICE__ */

Below is the main.cpp file I am using via mbed.org.

#include "mbed.h"
#include "ble/BLE.h"
#include "AccelerometerService.h"

DigitalOut led1(LED1);
DigitalOut led2(LED2);

static AccelerometerService *accelerometerServicePtr;

// Function declarations
void bleInitComplete(BLE::InitializationCompleteCallbackContext *);
void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *);

// Set device name and inital setup options
static const char       DEVICE_NAME[]        = "nRF52";
static const uint16_t   uuid16_list[]        = {0xFFFF};
static volatile bool    triggerSensorPolling = false;

static float           x = 10.0;    // Dummy values for accelerometer for now
static float           y = 15.0;
static float           z = 18.0;

/*
 *  Initialization callback
 */
void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
{
    BLE &ble = params->ble;
    ble_error_t error = params->error;

    if (error != BLE_ERROR_NONE){
        printf("*** Error occured ***\n");
        return;
    }

    /* Ensure that it is the default instance of BLE */
    if(ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
        return;
    }

    ble.gap().onDisconnection(disconnectionCallback);

    // Setup primary service
    accelerometerServicePtr = new AccelerometerService(ble, x, y, z);

    // Setup advertising
    ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);

    // Advertising payload has a maximum of 31 bytes
    // BLE only, no classic BT
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED |
                                           GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
    // Add name
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
    // UUIDs broadcast in advertising packet
    ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list));
    // Set advertising interval
    ble.gap().setAdvertisingInterval(100); //100ms

    // Start advertising
    ble.gap().startAdvertising();
}

/**
 * Restart advertising on disconnection
 */
void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *)
{
    BLE::Instance(BLE::DEFAULT_INSTANCE).gap().startAdvertising();
}

/**
 * This function is called when the ble initialization process has failed
 */
void onBleInitError(BLE &ble, ble_error_t error)
{
    /* Avoid compiler warnings */
    (void) ble;
    (void) error;
    /* Initialization error handling should go here */
}

int main()
{
    // Initialize program
    printf("\n\r *** Starting Main Loop *** \r\n");

    BLE &ble = BLE::Instance(BLE::DEFAULT_INSTANCE);
    ble.init(bleInitComplete);

    while (ble.hasInitialized() == false)
    {
        while (true)
        {
            if (triggerSensorPolling && ble.gap().getState().connected) {
                triggerSensorPolling = false;

                accelerometerServicePtr->update_x(x);
                accelerometerServicePtr->update_y(y);
                accelerometerServicePtr->update_z(z);
            }
            else {
                ble.waitForEvent();   // Infinite loop waiting for BLE interrupt events
            }
        }
    }
}

Body:
This is wrong, you are sending a bad advertising packet. (0xFFFF == Insert 16 bit service here)

...
uuid16_list[]        = {0xFFFF};
...
...
COMPLETE_LIST_128BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list)

There are for Bluetooth reserved 16 bit identifiers, which use the reserved UUID space.

Check This page: What range of Bluetooth UUIDs can be used for vendor defined profiles?

What you need to do is specify the full UUID in the 128 bit list.

I cant compile this but try something like this

char 128bitlist[] = {,0x00,0x00,0x00,0x00 ,0x00,0x00 ,0x10,0x00 ,0x74,0x50 ,0xBE,0x2E,0x44,0xB0,0x6B,0x00};
...
...
ble.gap().accumulateAdvertisingPayload (GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS, (uint8_t *) 128bitlist, 1);

An outstanding tool for checking your advertising data is Lightblue.  It is free and really informative.  You should check the advertising on both Android and IOS with this tool.

Another thing to check is that you dont overfill the advertising packet.  If your device name is too long, plus the 128 bit UUID, you can overfill and corrupt the packet. Try removing the name or making it really short.


问:
Angular 5 getting array issue with data from service to component to template
Trying to display data in template HTML from a component to service call which calls and returns an API, but I'm getting this error

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

HTML

```<code><li *ngFor="let item of testing">
   <a [routerLink]="[item.url]" >
    <span>{{item.name}}</span>
   </a>
</li>
</code>```

Component

```<code>testing: any;

this.arsSevice.getMenu()
     .subscribe(
         result => {
            this.testing = result;
            console.log('menu',result);
      },
      error => {
         console.log('menu error', error);
      }
      )
</code>```

Service:

```<code>getMenu()  {
    return this.http.post(this.menuUrl, JSON.stringify({
        "UserID": 61525,
        "AppID": 15,
        "NavAppID":null,
        "AppGroupID": 116,
        "SelectedCaseID": 0,
        "SelectedRoleID":0
    }), httpOptions)
        .map((response: Response)=> {
            return response;
        })
}
</code>```

Image screenshot of the data

Update

I see a data problem

"menu" has data:  and it what is HERE and NOT working.

the working one is from a different API call
Notice that is has

data: Array(16)

How can I fix my data from object to array ?

答:
The Http service returns a Response object, calling json() on which should give you the data returned by the backend.

Change return response; to return response.json();

Body:
Trying to display data in template HTML from a component to service call which calls and returns an API, but I'm getting this error

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

HTML

    {{item.name}}

Component

testing: any;

this.arsSevice.getMenu()
     .subscribe(
         result => {
            this.testing = result;
            console.log('menu',result);
      },
      error => {
         console.log('menu error', error);
      }
      )

Service:

getMenu()  {
    return this.http.post(this.menuUrl, JSON.stringify({
        "UserID": 61525,
        "AppID": 15,
        "NavAppID":null,
        "AppGroupID": 116,
        "SelectedCaseID": 0,
        "SelectedRoleID":0
    }), httpOptions)
        .map((response: Response)=> {
            return response;
        })
}

Image screenshot of the data

Update

I see a data problem

"menu" has data:  and it what is HERE and NOT working.

the working one is from a different API call
Notice that is has

data: Array(16)

How can I fix my data from object to array ?


问:
Compare two Arrays with Objects and create new array with unmatched objects
I have the following two Javascript arrays:

```<code>const array1 = [{ id: 1}, { id: 2 }, { id: 3 }, { id: 4}];
const array2 = [{ id: 1}, { id: 3 }];
</code>```

I now want a new array array3 that contains only the objects that aren't already in array2, so:

```<code>const array3 = [{ id: 2}, { id: 4 }];
</code>```

I have tried the following but it returns all objects, and when I changed the condition to === it returns the objects of array2.

```<code>const array3 = array1.filter(entry1 => {
  return array2.some(entry2 => entry1.id !== entry2.id);
});
</code>```

Any idea? ES6 welcome

答:
You could reverse the comparison (equal instead of unqual) and return the negated result of some.

const
    array1 = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
    array2 = [{ id: 1 }, { id: 3 }],
    array3 = array1.filter(entry1 => !array2.some(entry2 => entry1.id === entry2.id));
    //                               ^                                ^^^

console.log(array3);```

Body:
I have the following two Javascript arrays:

const array1 = [{ id: 1}, { id: 2 }, { id: 3 }, { id: 4}];
const array2 = [{ id: 1}, { id: 3 }];

I now want a new array array3 that contains only the objects that aren't already in array2, so:

const array3 = [{ id: 2}, { id: 4 }];

I have tried the following but it returns all objects, and when I changed the condition to === it returns the objects of array2.

const array3 = array1.filter(entry1 => {
  return array2.some(entry2 => entry1.id !== entry2.id);
});

Any idea? ES6 welcome


问:
Django Form Logic: Split and display prefilled values
Let's say I have a model that holds several different charfields.

models.py

```<code>class Items(models.Model):
    languages = models.Charfield(...)
    title = models.Charfield(...)
    audio = models.Charfield(...)
</code>```

The data is saved within each with a delimiter ("||").  I would like to create a form that splits the data then prefills the value with the saved data.

Theoretically:

```<code>{'languages': 'English||French||German'}
{'title': '1.1||Red Balloon||Banana'}
{'audio': 'yes||no||yes'}
</code>```

Would be split to:

```<code>{'languages': ['English', 'French', 'German']}
{'title': ['1.1', 'Red Balloon', 'Banana']}
{'audio': ['yes', 'no', 'yes']}
</code>```

Then each value would auto-populate the value field. Eventually displaying as:

```<code><tr>
  <td><input type="text" name="languages[]" value="English"></td>
  <td><input type="text" name="title[]" value="1.1"></td>
  <td><input type="text" name="audio[]" value="yes"></td>
</tr>
<tr>
  <td><input type="text" name="languages[]" value="French"></td>
  <td><input type="text" name="title[]" value="Red Balloon"></td>
  <td><input type="text" name="audio[]" value="no"></td>
</tr>
...
</code>```

As each row would have a different amount of 'languages', for example, what is the preferred way to create this type of form.  I am using Django 1.11. First question posted, so if I have missed something within this post, would you kindly let me know?  I also have searched for information related to this, however I have yet to find a solution. Thanks!

--Edited to reflect that charFields hold the user input.  In this example, the inputs 'languages' and 'title' are not consistent enough to use them as multiple-choice fields.

答: Perhaps you should simply consider ChoiceFields.

Body:
Let's say I have a model that holds several different charfields.

models.py

class Items(models.Model):
    languages = models.Charfield(...)
    title = models.Charfield(...)
    audio = models.Charfield(...)

The data is saved within each with a delimiter ("||").  I would like to create a form that splits the data then prefills the value with the saved data.

Theoretically:

{'languages': 'English||French||German'}
{'title': '1.1||Red Balloon||Banana'}
{'audio': 'yes||no||yes'}

Would be split to:

{'languages': ['English', 'French', 'German']}
{'title': ['1.1', 'Red Balloon', 'Banana']}
{'audio': ['yes', 'no', 'yes']}

Then each value would auto-populate the value field. Eventually displaying as:

  <input type="text" name="languages[]" value="English">
  <input type="text" name="title[]" value="1.1">
  <input type="text" name="audio[]" value="yes">

  <input type="text" name="languages[]" value="French">
  <input type="text" name="title[]" value="Red Balloon">
  <input type="text" name="audio[]" value="no">

...

As each row would have a different amount of 'languages', for example, what is the preferred way to create this type of form.  I am using Django 1.11. First question posted, so if I have missed something within this post, would you kindly let me know?  I also have searched for information related to this, however I have yet to find a solution. Thanks!

--Edited to reflect that charFields hold the user input.  In this example, the inputs 'languages' and 'title' are not consistent enough to use them as multiple-choice fields.


问:
Creating tags on posts RAILS
I am making something that's like that autocomplete tags field for the posts on stackoverflow.com

I want to make it so that when you make a blog post, you can tag it with words in a database, similar to SO.

For the posts, it belongs_to_and_has_many tags
For the tags, it belongs_to_and_has_many posts

However it is a problem for me to do it on the same page because @post would be nil.

How can I implement this?

(If someone can give me the code for the stackoverflow ask question page that would be AWESOME)

答:
This may not help you at all (or you may have already seen it), but here's a link to a Railscasts' episode on auto-complete:

http://railscasts.com/episodes/102-auto-complete-association

I know it helped me when trying to do something similar.

HTH

Title: Creating tags on posts RAILS


问:
Exe file created using pyinstaller shuts immediately when executing
I've tried to create an executable file using pyinstaller (python 3.6) I've tried to to do this on windows 10 using(also python 3.5) py2exe, and freeze(something), but only pyinstaller was "brave" enough to create an exe file.

When I was opening the file.py through command prompt - no problem occured. But when I was trying to execute the file.exe - there is showing up a black window like a command prompt, and suddenly it disappears, while the file.exe is not executing.
While creating an exe.file I had few warnings in command prompt:

```<code>12914 WARNING: lib not found: api-ms-win-crt-convert-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tk86t.dll
12986 WARNING: lib not found: api-ms-win-crt-utility-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tk86t.dll
13141 WARNING: lib not found: api-ms-win-crt-string-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll
13210 WARNING: lib not found: api-ms-win-crt-time-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll
13284 WARNING: lib not found: api-ms-win-crt-math-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll
13357 WARNING: lib not found: api-ms-win-crt-runtime-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll
13432 WARNING: lib not found: api-ms-win-crt-stdio-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll
13505 WARNING: lib not found: api-ms-win-crt-heap-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll
13576 WARNING: lib not found: api-ms-win-crt-environment-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll
13646 WARNING: lib not found: api-ms-win-crt-convert-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll
13725 WARNING: lib not found: api-ms-win-crt-utility-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll
</code>```

and on and on and on...
but finally in the end I had this info:

```<code>15204 INFO: checking COLLECT
15204 INFO: Building COLLECT because out00-COLLECT.toc is non existent
15206 INFO: Building COLLECT out00-COLLECT.toc
21221 INFO: Building COLLECT out00-COLLECT.toc completed successfully.
</code>```

Here is my code - a little bit long
https://codepaste.net/o53jx9

This is my first time trying to create an exe file

答:
If you run the exe in cmd it will tell you exactly what is causing it to crash.

run your .exe from the command window, and not from double clicking it. Then edit your answer and post the error that is given.

Its more than likely you are missing an file that your .py script needs in order to run, which would cause it to crash

Body:
I've tried to create an executable file using pyinstaller (python 3.6) I've tried to to do this on windows 10 using(also python 3.5) py2exe, and freeze(something), but only pyinstaller was "brave" enough to create an exe file.

When I was opening the file.py through command prompt - no problem occured. But when I was trying to execute the file.exe - there is showing up a black window like a command prompt, and suddenly it disappears, while the file.exe is not executing.
While creating an exe.file I had few warnings in command prompt:

12914 WARNING: lib not found: api-ms-win-crt-convert-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tk86t.dll
12986 WARNING: lib not found: api-ms-win-crt-utility-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tk86t.dll
13141 WARNING: lib not found: api-ms-win-crt-string-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll
13210 WARNING: lib not found: api-ms-win-crt-time-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll
13284 WARNING: lib not found: api-ms-win-crt-math-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll
13357 WARNING: lib not found: api-ms-win-crt-runtime-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll
13432 WARNING: lib not found: api-ms-win-crt-stdio-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll
13505 WARNING: lib not found: api-ms-win-crt-heap-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll
13576 WARNING: lib not found: api-ms-win-crt-environment-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll
13646 WARNING: lib not found: api-ms-win-crt-convert-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll
13725 WARNING: lib not found: api-ms-win-crt-utility-l1-1-0.dll dependency of c:\users\krzys\appdata\local\programs\python\python36-32\DLLs\tcl86t.dll

and on and on and on...
but finally in the end I had this info:

15204 INFO: checking COLLECT
15204 INFO: Building COLLECT because out00-COLLECT.toc is non existent
15206 INFO: Building COLLECT out00-COLLECT.toc
21221 INFO: Building COLLECT out00-COLLECT.toc completed successfully.

Here is my code - a little bit long
https://codepaste.net/o53jx9

This is my first time trying to create an exe file


问:
scikit-learn: StandardScaler() freezes in comb. with Pipeline and GridSearchCV
I am trying to fit a model onto a dataset with the following construction:

```<code># Import stuff and generate dataset.
import sklearn as skl
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn import preprocessing
from sklearn import svm
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn import metrics
from tempfile import mkdtemp
from shutil import rmtree
from sklearn.externals.joblib import Memory
X, y = skl.datasets.make_classification(n_samples=1400, n_features=11,  n_informative=5, n_classes=2, weights=[0.94, 0.06], flip_y=0.05, random_state=42)
X_train, X_test, y_train, y_test = skl.model_selection.train_test_split(X, y, test_size=0.3, random_state=42)

# 1. Instantiate a scaler.
#normer = preprocessing.Normalizer()
normer = preprocessing.StandardScaler()

# 2. Instantiate a Linear Support Vector Classifier.
svm1 = svm.SVC(probability=True, class_weight={1: 10})

# 3. Forge normalizer and classifier into a pipeline. Make sure the pipeline steps are memorizable during the grid search.
cached = mkdtemp()
memory = Memory(cachedir=cached, verbose=1)
pipe_1 = Pipeline(steps=[('normalization', normer), ('svm', svm1)], memory=memory)

# 4. Instantiate Cross Validation
cv = skl.model_selection.KFold(n_splits=5, shuffle=True, random_state=42)

# 5. Instantiate the Grid Search for Hypereparameter Tuning
params = [ {"svm__kernel": ["linear"], "svm__C": [1, 10, 100, 1000]},
           {"svm__kernel": ["rbf"], "svm__C": [1, 10, 100, 1000], "svm__gamma": [0.001, 0.0001]} ]
grd = GridSearchCV(pipe_1, params, scoring='roc_auc', cv=cv)
</code>```

The program freezes in my Jupyter notebook when calling

```<code>y_pred = grd3.fit(X_train, y_train).predict_proba(X_test)[:, 1]
</code>```

I aborted after 20 minutes.
When I use preprocessing.Normalizer() instead of StandardScaler, the .fit() is done after two or three minutes.

What could be the problem here?

Edit: here is the output from the GridSearchCV():

```<code>GridSearchCV(cv=KFold(n_splits=5, random_state=2, shuffle=True), error_score='raise',estimator=Pipeline(memory=None, steps=[('normalization', StandardScaler(copy=True, with_mean=True, with_std=True)), ('svm', SVC(C=1.0, cache_size=200, class_weight={1: 10}, coef0=0.0, decision_function_shape='ovr', degree=3, gamma='auto', kernel='rbf', max_iter=-1, probability=True, random_state=None, shrinking=True, tol=0.001, verbose=False))]), fit_params=None, iid=True, n_jobs=1,param_grid=[{'svm__kernel': ['linear'], 'svm__C': [1, 10, 100, 1000]}, {'svm__kernel': ['rbf'], 'svm__C': [1, 10, 100, 1000], 'svm__gamma': [0.001, 0.0001]}],pre_dispatch='2*n_jobs', refit=True, return_train_score=True, scoring='roc_auc', verbose=0)
</code>```

答:
Thanks for answering my comments (and I didn't see your data gen code, my bad).

You had a typo in your code, it should be:

y_pred = grd.fit(X_train, y_train).predict_proba(X_test)[:, 1]

Not:

y_pred = grd3.fit(X_train, y_train).predict_proba(X_test)[:, 1]

But from the logs it doesn't appear to be freezing but gets VERRRRY slow when testing C = 1000 in your grid search.

Does it need to be this high???

Testing on my computer (for the linear kernel, RBF will likely take even longer):

SVM_C = [10, 100, 1000] takes [1.8s, 16s, 127s]

So I'd recommend just testing up to C = 200/500 unless you're planning to run this overnight in a multi-fold CV grid search.

More generally

The both the fit function of a grid search and the predict probability functions can take a large amount of time.

I'd recommend splitting them in to two steps so you can mitigate the chance of freezing.

grd.fit(X_train, y_train)

y_pred = grd.predict_proba(X_test)[:, 1]

Body:
I am trying to fit a model onto a dataset with the following construction:

# Import stuff and generate dataset.
import sklearn as skl
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn import preprocessing
from sklearn import svm
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn import metrics
from tempfile import mkdtemp
from shutil import rmtree
from sklearn.externals.joblib import Memory
X, y = skl.datasets.make_classification(n_samples=1400, n_features=11,  n_informative=5, n_classes=2, weights=[0.94, 0.06], flip_y=0.05, random_state=42)
X_train, X_test, y_train, y_test = skl.model_selection.train_test_split(X, y, test_size=0.3, random_state=42)

# 1. Instantiate a scaler.
#normer = preprocessing.Normalizer()
normer = preprocessing.StandardScaler()

# 2. Instantiate a Linear Support Vector Classifier.
svm1 = svm.SVC(probability=True, class_weight={1: 10})

# 3. Forge normalizer and classifier into a pipeline. Make sure the pipeline steps are memorizable during the grid search.
cached = mkdtemp()
memory = Memory(cachedir=cached, verbose=1)
pipe_1 = Pipeline(steps=[('normalization', normer), ('svm', svm1)], memory=memory)

# 4. Instantiate Cross Validation
cv = skl.model_selection.KFold(n_splits=5, shuffle=True, random_state=42)

# 5. Instantiate the Grid Search for Hypereparameter Tuning
params = [ {"svm__kernel": ["linear"], "svm__C": [1, 10, 100, 1000]},
           {"svm__kernel": ["rbf"], "svm__C": [1, 10, 100, 1000], "svm__gamma": [0.001, 0.0001]} ]
grd = GridSearchCV(pipe_1, params, scoring='roc_auc', cv=cv)

The program freezes in my Jupyter notebook when calling

y_pred = grd3.fit(X_train, y_train).predict_proba(X_test)[:, 1]

I aborted after 20 minutes.
When I use preprocessing.Normalizer() instead of StandardScaler, the .fit() is done after two or three minutes.

What could be the problem here?

Edit: here is the output from the GridSearchCV():

GridSearchCV(cv=KFold(n_splits=5, random_state=2, shuffle=True), error_score='raise',estimator=Pipeline(memory=None, steps=[('normalization', StandardScaler(copy=True, with_mean=True, with_std=True)), ('svm', SVC(C=1.0, cache_size=200, class_weight={1: 10}, coef0=0.0, decision_function_shape='ovr', degree=3, gamma='auto', kernel='rbf', max_iter=-1, probability=True, random_state=None, shrinking=True, tol=0.001, verbose=False))]), fit_params=None, iid=True, n_jobs=1,param_grid=[{'svm__kernel': ['linear'], 'svm__C': [1, 10, 100, 1000]}, {'svm__kernel': ['rbf'], 'svm__C': [1, 10, 100, 1000], 'svm__gamma': [0.001, 0.0001]}],pre_dispatch='2*n_jobs', refit=True, return_train_score=True, scoring='roc_auc', verbose=0)


问:
MIME type XLSX (from LibreOffice)
I'm trying to solve one problem: I want to upload to my website XLS/XLSX file. And I've there for it this condition:

```<code>if((mime_content_type($file) == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || mime_content_type($file) == 'application/vnd.ms-excel') && ($extension == 'xls' || $extension == 'XLS' || $extension == 'xlsx' || $extension == 'XLSX')){...upload...}
</code>```

When I use the XLS/X file (which has been saved directly from MS Excel), it works great. But when I want to upload XLS/X file - which has been saved directly from LibreOffice (not as ODS, but as an XLS/X) - it doesn't work and I can't upload this file.

Thanks for any help!

(And the condition with application/vnd.oasis.opendocument.spreadsheet doesn't work as well.)

Update: Thanks to Dipanwita Kundu I was able to find, which MIME type is used (application/octet-stream) - but its safe to put this as the condition?

答:
If you save an file with LibreOffice Calc, then the php mime_content_type($file) return value is 'application/zip'.

Upload xls or xlsx files with codeigniter, mime-type error

Title: MIME type XLSX (from LibreOffice)

Body:
I'm trying to solve one problem: I want to upload to my website XLS/XLSX file. And I've there for it this condition:

if((mime_content_type($file) == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || mime_content_type($file) == 'application/vnd.ms-excel') && ($extension == 'xls' || $extension == 'XLS' || $extension == 'xlsx' || $extension == 'XLSX')){...upload...}

When I use the XLS/X file (which has been saved directly from MS Excel), it works great. But when I want to upload XLS/X file - which has been saved directly from LibreOffice (not as ODS, but as an XLS/X) - it doesn't work and I can't upload this file.

Thanks for any help!

(And the condition with application/vnd.oasis.opendocument.spreadsheet doesn't work as well.)

Update: Thanks to Dipanwita Kundu I was able to find, which MIME type is used (application/octet-stream) - but its safe to put this as the condition?