问:
Windows Task Scheduler Bat file Doesn't Recognize Python as internal or external command
I've tried running this .bat file by just double clicking it, and it works. However when I try to run it through Task Scheduler:

```<code>CD /D %~dp0
@echo on

python -W ignore DailyRates.py

PAUSE
</code>```

I get the classic

```<code>C:\Windows\system32>CD /D U:\

U:\>python -W ignore DailyRates.py
'python' is not recognized as an internal or external command,
operable program or batch file.

U:\>PAUSE
Press any key to continue . . .
</code>```

Which means it isn't recognizing python in my PATH, but I am in the correct directory (U: drive)

答:
For anyone curious, I ended up using the explicit path instead of trying to simply call python.</p>

```<code>C:\Users\...\...\...\...\...\python.exe -W ignore U:\Sandbox\DailyRates.py
</code>```

Body:
I've tried running this .bat file by just double clicking it, and it works. However when I try to run it through Task Scheduler:

CD /D %~dp0
@echo on

python -W ignore DailyRates.py

PAUSE

I get the classic

C:\Windows\system32>CD /D U:\

U:\>python -W ignore DailyRates.py
'python' is not recognized as an internal or external command,
operable program or batch file.

U:\>PAUSE
Press any key to continue . . .

Which means it isn't recognizing python in my PATH, but I am in the correct directory (U: drive)

Body:
For anyone curious, I ended up using the explicit path instead of trying to simply call python.

C:\Users\...\...\...\...\...\python.exe -W ignore U:\Sandbox\DailyRates.py


来源: stackexchange

问:
Nodejs Net TCP client data event triggered without any write action in server side
I was using net module to build a simple server/client example.  The client side just send a simple message after connection is built, and server side didn't do anything but just print some log, but after that I found the data event in client side got triggered, and the data received is the data it send to the server (but server didn't write anything to client).

Client.js:

```<code>var net = require('net');

  var port = 3540;
  var hostName = "127.0.0.1";

  var client = new net.Socket();
  client.connect(port, hostName, function() {
     console.log("Connected to the remote host: " + hostName + ":" + port);
     client.write("hello,world");
     client.end();
  });
  var bytesReceived = 0;
  client.on('data', function(data) {
    bytesReceived += data.length;
    console.log('Received bytes: ' + data.length + ', total bytes received: ' + bytesReceived);
    console.log(data.toString())
    })

  client.on('error', function(error) {
    console.log(error);
    client.destroy();
  });

  client.on('close', function() {
    console.log('Closed connection');
  })
</code>```

server.js:

```<code>var net = require('net');
    port = 3540;

var log = function(who, what) {
  return function() {
    var args = Array.prototype.slice.call(arguments);
    console.log('[%s on %s]', who, what, args);
  };
};
var count = 0
var echo = function (socket) {
  socket.on('end', function() {
    console.log('recevied a FIN packet');
    socket.end();
  });
  socket.on('data', function(data) {
    console.log(count + ': received bytes: ' + data.length);
    count++;
  });
  socket.on('error', function(error) {
    console.log(error);
    socket.destroy();
  });
  socket.on('close', function() {
    console.log('connection has been closed!');
  });
  socket.pipe(socket);
}

var server = net.createServer(echo);
server.listen(port); // port or unix socket, cannot listen on both with one server

server.on('listening', function() {
  var ad = server.address();
  if (typeof ad === 'string') {
    console.log('[server on listening] %s', ad);
  } else {
    console.log('[server on listening] %s:%s using %s', ad.address, ad.port, ad.family);
  }
});

server.on('connection', function(socket) {
  server.getConnections(function(err, count) {
    console.log('%d open connections!', count);
  });
});

server.on('close', function() { console.log('[server on close]'); });
server.on('err', function(err) {
  console.log(err);
  server.close(function() { console.log("shutting down the server!"); });
});
</code>```

After that the client print out:

```<code>Connected to the remote host: 127.0.0.1:3540
Received bytes: 11, total bytes received: 11
hello,world
Closed connection
</code>```

答:
but server didn't write anything to client

It does:

```<code>socket.pipe(socket)
</code>```

This will echo the data received from the client (represented by socket) back to the client.

ContentLicense: CC BY-SA 3.0

Body:
I was using net module to build a simple server/client example.  The client side just send a simple message after connection is built, and server side didn't do anything but just print some log, but after that I found the data event in client side got triggered, and the data received is the data it send to the server (but server didn't write anything to client).

Client.js:

var net = require('net');

  var port = 3540;
  var hostName = "127.0.0.1";

  var client = new net.Socket();
  client.connect(port, hostName, function() {
     console.log("Connected to the remote host: " + hostName + ":" + port);
     client.write("hello,world");
     client.end();
  });
  var bytesReceived = 0;
  client.on('data', function(data) {
    bytesReceived += data.length;
    console.log('Received bytes: ' + data.length + ', total bytes received: ' + bytesReceived);
    console.log(data.toString())
    })

  client.on('error', function(error) {
    console.log(error);
    client.destroy();
  });

  client.on('close', function() {
    console.log('Closed connection');
  })

server.js:

var net = require('net');
    port = 3540;

var log = function(who, what) {
  return function() {
    var args = Array.prototype.slice.call(arguments);
    console.log('[%s on %s]', who, what, args);
  };
};
var count = 0
var echo = function (socket) {
  socket.on('end', function() {
    console.log('recevied a FIN packet');
    socket.end();
  });
  socket.on('data', function(data) {
    console.log(count + ': received bytes: ' + data.length);
    count++;
  });
  socket.on('error', function(error) {
    console.log(error);
    socket.destroy();
  });
  socket.on('close', function() {
    console.log('connection has been closed!');
  });
  socket.pipe(socket);
}

var server = net.createServer(echo);
server.listen(port); // port or unix socket, cannot listen on both with one server

server.on('listening', function() {
  var ad = server.address();
  if (typeof ad === 'string') {
    console.log('[server on listening] %s', ad);
  } else {
    console.log('[server on listening] %s:%s using %s', ad.address, ad.port, ad.family);
  }
});

server.on('connection', function(socket) {
  server.getConnections(function(err, count) {
    console.log('%d open connections!', count);
  });
});

server.on('close', function() { console.log('[server on close]'); });
server.on('err', function(err) {
  console.log(err);
  server.close(function() { console.log("shutting down the server!"); });
});

After that the client print out:

Connected to the remote host: 127.0.0.1:3540
Received bytes: 11, total bytes received: 11
hello,world
Closed connection

Body:
but server didn't write anything to client

It does:

socket.pipe(socket)

This will echo the data received from the client (represented by socket) back to the client.


问:
Why is my Android Studio 2.3.3 not upgrading to Canary? Windows
Android Studio opens and asks me to upgrade to Canary and once it's downloaded and I have followed the prompts it still doesn't work?</p>

答:
Unpack the ZIP file.

Rename the resulting folder to something unique
like "Android Studio Preview."
3.Move it to a permanent location, such
as next to your existing Android Studio install in C:\Program

Files\Android.

Inside C:\Program Files\Android\Android Studio

Preview\bin\, launch studio64.exe (or if you're on a 32-bit machine,
launch studio.exe).

**

To make the preview version available in your Start menu, right-click studio64.exe and click Pin to Start Menu.

**
Source: https://developer.android.com/studio/preview/install-preview.html


问:
How to skip rerendering a reactive component
I have a component with reactive properties.
I want the properties to be changed and want to know when its changing using any possible event but I don't want to rerender the DOM.

How can I achieve that?

答:
Not sure what you mean but vuejs already has several functions to do this.

```<code>var component_name = new Vue({
     el:'#element_container',
     data: {
         'data_to_be_watched': {'name': 'Abdel', 'surname': 'Sakherdine'}
     },
     watch: {
         'data_to_be_watched.name': function(value){
             //do something with value here
        }
    }
});
</code>```

https://v2.vuejs.org/v2/guide/computed.html#Watchers

Body:
Not sure what you mean but vuejs already has several functions to do this.

var component_name = new Vue({
     el:'#element_container',
     data: {
         'data_to_be_watched': {'name': 'Abdel', 'surname': 'Sakherdine'}
     },
     watch: {
         'data_to_be_watched.name': function(value){
             //do something with value here
        }
    }
});

https://v2.vuejs.org/v2/guide/computed.html#Watchers

ContentLicense: CC BY-SA 4.0


问:
Displaying JPA resultList in console
I've just started to learn JPA 2 and am trying to make a simple display of my table content in console.

This is how my method looks like:

```<code>public static List<Bronie> getListaBroni() {

    EntityManager em = DatabaseHandler.getEntityManager();
    String qString = "SELECT b FROM Bronie b";

    TypedQuery<Bronie> q = em.createQuery(qString, Bronie.class);

    result = q.getResultList();

    return result;

}
</code>```

I'm trying to display it in console, but the result I get is:

```<code>Hibernate: select bronie0_.id as id1_1_, bronie0_.ilosc as ilosc2_1_, bronie0_.kaliber as kaliber3_1_, bronie0_.model_broni as model_br4_1_ from bronie bronie0_
[arma.itemdb.Bronie@7662c85f]
</code>```

So far there's only one object in the database, but I see no point of putting more of them for this question.

I know I have to, somehow, divide the objects I receive in parts that represent different columns, but I have no clue how. And how to avoid this kind of display

```<code>Bronie@7662c85f
</code>```

later?

Don't know if it helps, but I'll be trying to put the result list into a TableView at the end, so I'll probably need to separate each column from the object anyway.

答: I think that your class should implement Serializable class.

Title: Displaying JPA resultList in console

Body:
I've just started to learn JPA 2 and am trying to make a simple display of my table content in console.

This is how my method looks like:

public static List<Bronie> getListaBroni() {

    EntityManager em = DatabaseHandler.getEntityManager();
    String qString = "SELECT b FROM Bronie b";

    TypedQuery<Bronie> q = em.createQuery(qString, Bronie.class);

    result = q.getResultList();

    return result;

}

I'm trying to display it in console, but the result I get is:

Hibernate: select bronie0_.id as id1_1_, bronie0_.ilosc as ilosc2_1_, bronie0_.kaliber as kaliber3_1_, bronie0_.model_broni as model_br4_1_ from bronie bronie0_
[arma.itemdb.Bronie@7662c85f]

So far there's only one object in the database, but I see no point of putting more of them for this question.

I know I have to, somehow, divide the objects I receive in parts that represent different columns, but I have no clue how. And how to avoid this kind of display

Bronie@7662c85f

later?

Don't know if it helps, but I'll be trying to put the result list into a TableView at the end, so I'll probably need to separate each column from the object anyway.


问:
Writing text over parallax image
Okay so I created an image that uses parallax scrolling.

The code is:

Welcome to RyanTeaches

</body```

The problem is that for some reason, my message "Welcome to RyanTeaches" is stuck at the top of the page behind the nav bar. (Have only included relevant code for the parallax scrolling+message)

I have tried numerous things, top:300;, margin-top, padding-top etc. to try and move this message down but it is insistent on remaining at the top of the page, hidden behind the nav bar.

Also, when I try and move the  code to my .css stylesheet, the parallax image hides behind everything and is not visible on the screen?

New coder - any help would be appreciated!

Cheers

答:
You could add some flexbox properties to .Welcome:

/*Parallax*/

.hpimg1 {
  /* Set a specific height */
  height: 540px;
  /* Create the parallax scrolling effect */
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  padding-left: 0px;
}

.hpimg1 {
  /* The image used */
  background-image: url("https://placehold.it/200x200");
}

.welcome {
  height: 200px;
  background-color: #fff;
  word-wrap: normal;
  word-break: keep-all;
  font-family: 'Montserrat';
  font-weight: 700;
  font-size: 31px;
  line-height: 1.125em;
  margin-right: 0;
  margin-left: 0;
  margin-bottom: 0;
  box-sizing: border-box;
  top: 300px;
}

.Welcome {
  display: flex;
  height: 100%;
  align-items: center;
  justify-content: center;
}

h5 {
  color: white;
  top: 300px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  text-transform: uppercase;
  padding-bottom: 38px;
  -webkit-margin-before: 0.67em;
  -webkit-margin-after: 0.67em;
  -webkit-margin-start: 0px;
  -webkit-margin-end: 0px;
  -webkit-tap-highlight-colour: rgba(0, 0, 0, 0);
  -webkit-font-smoothing: antialiased;
  -webkit-box-direction: normal;
}

h5:after,
h5:before {
  content: '';
  width: 50px;
  height: 2px;
  background: black;
  margin: 0 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="hpimg1">
    <div class="Welcome">
      <h5>Welcome to RyanTeaches</h5>
    </div>
  </div>
</body></code>```

Title: Writing text over parallax image

Body:
Okay so I created an image that uses parallax scrolling.

The code is:

Welcome to RyanTeaches

</body

The problem is that for some reason, my message "Welcome to RyanTeaches" is stuck at the top of the page behind the nav bar. (Have only included relevant code for the parallax scrolling+message)

I have tried numerous things, top:300;, margin-top, padding-top etc. to try and move this message down but it is insistent on remaining at the top of the page, hidden behind the nav bar.

Also, when I try and move the  code to my .css stylesheet, the parallax image hides behind everything and is not visible on the screen?

New coder - any help would be appreciated!

Cheers

Body:
You could add some flexbox properties to .Welcome:

/*Parallax*/

.hpimg1 {
  /* Set a specific height */
  height: 540px;
  /* Create the parallax scrolling effect */
  background-attachment: fixed;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  padding-left: 0px;
}

.hpimg1 {
  /* The image used */
  background-image: url("https://placehold.it/200x200");
}

.welcome {
  height: 200px;
  background-color: #fff;
  word-wrap: normal;
  word-break: keep-all;
  font-family: 'Montserrat';
  font-weight: 700;
  font-size: 31px;
  line-height: 1.125em;
  margin-right: 0;
  margin-left: 0;
  margin-bottom: 0;
  box-sizing: border-box;
  top: 300px;
}

.Welcome {
  display: flex;
  height: 100%;
  align-items: center;
  justify-content: center;
}

h5 {
  color: white;
  top: 300px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  text-transform: uppercase;
  padding-bottom: 38px;
  -webkit-margin-before: 0.67em;
  -webkit-margin-after: 0.67em;
  -webkit-margin-start: 0px;
  -webkit-margin-end: 0px;
  -webkit-tap-highlight-colour: rgba(0, 0, 0, 0);
  -webkit-font-smoothing: antialiased;
  -webkit-box-direction: normal;
}

h5:after,
h5:before {
  content: '';
  width: 50px;
  height: 2px;
  background: black;
  margin: 0 10px;
}

<body>
  <div class="hpimg1">
    <div class="Welcome">
      <h5>Welcome to RyanTeaches</h5>
    </div>
  </div>
</body>


问:
$_GET undefined index
By passing a js variable to php code it displays a value at the end of the program.

But the problem is no mather what i try to initialise it with the score disapears at the end.

If i leave it alone everything displays as it should, but with the annoying undefined message until the last screen (where the value actually gets displayed).

```<code>$varOne = $xml->addChild('one', $_GET['resultone']);
</code>```

The variable in the js is being past by using window.location.href

I have tried several isset ways but none of them seem to have succeeded in resolving this annoying problem.

Kind regards.

答:
Have you tried testing for $_GET and $_GET['resultone']?</p>

```<code>if( isset($_GET) && isset($_GET['resultone']) ) {
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: $_GET undefined index

Body:
By passing a js variable to php code it displays a value at the end of the program.

But the problem is no mather what i try to initialise it with the score disapears at the end.

If i leave it alone everything displays as it should, but with the annoying undefined message until the last screen (where the value actually gets displayed).

$varOne = $xml->addChild('one', $_GET['resultone']);

The variable in the js is being past by using window.location.href

I have tried several isset ways but none of them seem to have succeeded in resolving this annoying problem.

Kind regards.

Body:
Have you tried testing for $_GET and $_GET['resultone']?

if( isset($_GET) && isset($_GET['resultone']) ) {
}


问:
Impex attribute modifier to check length of a value in Hybris
I am trying to import an impex file. Currently, there is no such condition on the attributes. So, it is working fine.

However,I want to insert only those records for which the length of the value is not less than 10 characters but I haven't found any attribute modifiers in the Hybris documentation using which I can do that.

Below is my impex file:

```<code>Update Product;code[unique=true];value
              ;2055     ;ABCDEFGHIJKLMNOPQR
              ;2455     ;ABCDEFGH
</code>```

Here, the first row should get inserted but not the second one since the length of value field is less than 10 characters.

Is there any way I can achieve this ?

Thanks

答:
basically you could leverage the translator on the particular column in impex file. By defining your customized translator to validate the length of that column. For example:</p>

```<code>INSERT_UPDATE Media;mediaFormat(qualifier);code[unique=true];@media[translator=de.hybris.platform.impex.jalo.media.MediaDataTranslator][forceWrite=true];realfilename;altText;
</code>```

Body:
I am trying to import an impex file. Currently, there is no such condition on the attributes. So, it is working fine.

However,I want to insert only those records for which the length of the value is not less than 10 characters but I haven't found any attribute modifiers in the Hybris documentation using which I can do that.

Below is my impex file:

Update Product;code[unique=true];value
              ;2055     ;ABCDEFGHIJKLMNOPQR
              ;2455     ;ABCDEFGH

Here, the first row should get inserted but not the second one since the length of value field is less than 10 characters.

Is there any way I can achieve this ?

Thanks

Body:
basically you could leverage the translator on the particular column in impex file. By defining your customized translator to validate the length of that column. For example:

INSERT_UPDATE Media;mediaFormat(qualifier);code[unique=true];@media[translator=de.hybris.platform.impex.jalo.media.MediaDataTranslator][forceWrite=true];realfilename;altText;


问:
How to place imageView inside AutocompleteTextView
I am trying to align the ImageView inside the Autocomplete textView. I did this but the ImageView appears below the AutocomplteTextView. I changed the width of textView but same problem arises. I am looking for something like this:

Is there any way I can achieve this?

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.kalpu.placepick.SearchFragment">

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <AutoCompleteTextView
            android:id="@+id/acTextView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:completionHint="From"
            android:dropDownHeight="match_parent"
            android:hint="From"
            android:visibility="visible"
            />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@id/image"
            android:padding="5dp"
            android:layout_alignTop="@id/acTextView1"
            android:layout_alignBottom="@id/acTextView1"
            android:layout_alignRight="@id/acTextView1"
            android:src="@mipmap/ic_arrow_drop_down"

            />

        <AutoCompleteTextView
            android:id="@+id/acTextView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/acTextView1"
            android:completionHint="From"
            android:dropDownHeight="match_parent"
            android:hint="Intermediate (Optional) "
            android:paddingTop="50dp"
            android:visibility="visible" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@id/image"
            android:padding="5dp"
            android:layout_alignTop="@id/acTextView2"
            android:layout_alignBottom="@id/acTextView2"
            android:layout_alignRight="@id/acTextView1"
            android:src="@mipmap/ic_arrow_drop_down"

            />
 </LinearLayout>
</RelativeLayout>
</code>```

答:
Try this bro:</p>

```<code> <FrameLayout
    android:id="@+id/search"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true">

    <android.support.v7.widget.AppCompatAutoCompleteTextView
        android:id="@+id/autoCompleteSearch"
        android:layout_width="260dp"
        android:layout_height="40dp"
        android:paddingLeft="10dp"
        android:background="@android:color/transparent"
        android:hint="Search by Event"
        android:inputType="textAutoComplete"
        android:textSize="14sp"
        android:visibility="visible" />

    <ImageView
        android:id="@+id/searchBu"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_gravity="center_vertical|right"
        android:padding="10dp"
        android:src="@mipmap/ic_arrow_drop_down" />

</FrameLayout>`
</code>```

Body:
I am trying to align the ImageView inside the Autocomplete textView. I did this but the ImageView appears below the AutocomplteTextView. I changed the width of textView but same problem arises. I am looking for something like this:

Is there any way I can achieve this?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.kalpu.placepick.SearchFragment">

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <AutoCompleteTextView
            android:id="@+id/acTextView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:completionHint="From"
            android:dropDownHeight="match_parent"
            android:hint="From"
            android:visibility="visible"
            />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@id/image"
            android:padding="5dp"
            android:layout_alignTop="@id/acTextView1"
            android:layout_alignBottom="@id/acTextView1"
            android:layout_alignRight="@id/acTextView1"
            android:src="@mipmap/ic_arrow_drop_down"

            />

        <AutoCompleteTextView
            android:id="@+id/acTextView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/acTextView1"
            android:completionHint="From"
            android:dropDownHeight="match_parent"
            android:hint="Intermediate (Optional) "
            android:paddingTop="50dp"
            android:visibility="visible" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@id/image"
            android:padding="5dp"
            android:layout_alignTop="@id/acTextView2"
            android:layout_alignBottom="@id/acTextView2"
            android:layout_alignRight="@id/acTextView1"
            android:src="@mipmap/ic_arrow_drop_down"

            />
 </LinearLayout>
</RelativeLayout>

Body:
Try this bro:

 <FrameLayout
    android:id="@+id/search"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true">

    <android.support.v7.widget.AppCompatAutoCompleteTextView
        android:id="@+id/autoCompleteSearch"
        android:layout_width="260dp"
        android:layout_height="40dp"
        android:paddingLeft="10dp"
        android:background="@android:color/transparent"
        android:hint="Search by Event"
        android:inputType="textAutoComplete"
        android:textSize="14sp"
        android:visibility="visible" />

    <ImageView
        android:id="@+id/searchBu"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_gravity="center_vertical|right"
        android:padding="10dp"
        android:src="@mipmap/ic_arrow_drop_down" />

</FrameLayout>`


问:
How to glue two dependent tables?
I have Customer and Application tables. I want to create select query which provides info about a customer and also to count a number of applications user has in the system.

```<code>select distinct c.id, c.region, c.city, count(a.customer_id_id)
from customers c
join applications a on c.id=a.customer_id_id
group by c.id;
</code>```

But I get an error that I need to group by region and city but I want to display info about each application not to group by region and city. Because in such a way I will get not a number of applications for each user but for each group of users.
I read that it's possible to do with nested queries and full outer join but I tried and it didn't work. Can you explain to me how to do that?

答:
You are close.

Use a LEFT OUTER JOIN so that Customers with 0 records in Applications will also be included (assuming your intent here)

Don't use DISTINCT and GROUP BY together. Distinct means "If all the fields are the same value across multiple records in the record set produced by this SELECT statement, then only give back distinct records, dropping the duplicates". Instead with GROUP BY, "Group by this list of fields. Any remaining fields not in this list will be aggregated using a formula in your SELECT clause like count(a.customer_id_id)." They are similar, but you can't aggregate a field with merely a DISTINCT.

When using GROUP BY, if you are not going to aggregate a field with an aggregation formula (count, sum, avg, etc..) then you must include it in your group by. This isn't necessary with some RDBMS (older versions of MySQL, for example) but it's poor practice since a field that isn't explicitly aggregated with a formula that is also missing from the GROUP BY is like telling the RDBMS "Just pick which ever value you wish from matching records" which might have some unexpected consequences.

```<code>SELECT c.id, c.region, c.city, count(a.customer_id_id)
FROM customers c
    LEFT OUTER JOIN applications a on c.id=a.customer_id_id
GROUP BY c.id, c.region, c.city;
</code>```

Title: How to glue two dependent tables?

Body:
I have Customer and Application tables. I want to create select query which provides info about a customer and also to count a number of applications user has in the system.

select distinct c.id, c.region, c.city, count(a.customer_id_id)
from customers c
join applications a on c.id=a.customer_id_id
group by c.id;

But I get an error that I need to group by region and city but I want to display info about each application not to group by region and city. Because in such a way I will get not a number of applications for each user but for each group of users.
I read that it's possible to do with nested queries and full outer join but I tried and it didn't work. Can you explain to me how to do that?

Body:
You are close.

Use a LEFT OUTER JOIN so that Customers with 0 records in Applications will also be included (assuming your intent here)

Don't use DISTINCT and GROUP BY together. Distinct means "If all the fields are the same value across multiple records in the record set produced by this SELECT statement, then only give back distinct records, dropping the duplicates". Instead with GROUP BY, "Group by this list of fields. Any remaining fields not in this list will be aggregated using a formula in your SELECT clause like count(a.customer_id_id)." They are similar, but you can't aggregate a field with merely a DISTINCT.

When using GROUP BY, if you are not going to aggregate a field with an aggregation formula (count, sum, avg, etc..) then you must include it in your group by. This isn't necessary with some RDBMS (older versions of MySQL, for example) but it's poor practice since a field that isn't explicitly aggregated with a formula that is also missing from the GROUP BY is like telling the RDBMS "Just pick which ever value you wish from matching records" which might have some unexpected consequences.

SELECT c.id, c.region, c.city, count(a.customer_id_id)
FROM customers c
    LEFT OUTER JOIN applications a on c.id=a.customer_id_id
GROUP BY c.id, c.region, c.city;


问:
How do I project lines dynamically on to 3D terrain?
I'm working on a game in XNA for Xbox 360.  The game has 3D terrain with a collection of static objects that are connected by a graph of links.  I want to draw the links connecting the objects as lines projected on to the terrain.  I also want to be able to change the colors etc. of links as players move their selection around, though I don't need the links to move.  However, I'm running into issues making this work correctly and efficiently.

Some ideas I've had are:

1) Render quads to a separate render target, and use the texture as an overlay on top of the terrain. I currently have this working, generating the texture only for the area currently visible to the camera to minimize aliasing.  However, I'm still getting aliasing issues -- the lines look jaggy, and the game chugs frequently when moving the camera EDIT: it chugs all the time, I just don't have a frame rate counter on Xbox so I only notice it when things move.

2) Bake the lines into a texture ahead of time.  This could increase performance, but makes the aliasing issue worse.  Also, it doesn't let me dynamically change the properties of the lines without much munging.

3) Make geometry that matches the shape of the terrain by tessellating the line-quads over the terrain.  This option seems like it could help, but I'm unsure if I should spend time trying it out if there's an easier way.

Is there some magical way to do this that I haven't thought of? Is one of these paths the best when done correctly?

答:
Your 1) is a fairly good solution.  You can reduce the jagginess by filtering -- first, make sure to use bilinear sampling when using the overlay.  Then, try blurring the overlay after drawing it but before using it; if you choose a proper filter, it will remove the aliasing.

If it's taking too much time to render the overlay, try reducing its resolution.  Without the antialiasing filter, that would just make it jaggier, but with a good filter, it might even look better.

I don't know why the game would chug only when moving the camera.  Remember, you should have a separate camera for the overlay -- orthogonal, and pointing down onto the terrain.

OwnerDisplayName: Neil Williams

LastEditorDisplayName: Neil Williams

OwnerDisplayName: comingstorm


问:
String Pattern Question - Core Java (repeatSeparator)
Write a Java function such that Given two strings, word and a separator, return a big string made of count occurences of the word, separated by the separator string.

```<code>repeatSeparator("Word", "X", 3) → "WordXWordXWord"
repeatSeparator("This", "And", 2) → "ThisAndThis"
repeatSeparator("This", "And", 1) → "This"
</code>```

My code is as below but is not working

```<code>public String repeatSeparator(String word, String sep, int count) {
    if(count == 1) {
        return word;
    }
    if(count > 1) {
        for (int i = 0; i < count-1; i++){
            word = word + sep + word;
        }
    }
   return word;
}
</code>```

Example Output ::

```<code>                                   Expected         Run                  Result
repeatSeparator("Word", "X", 3) → "WordXWordXWord" "WordXWordXWordXWord" X
</code>```

答: Don't for get to consider the edge cases too. If the count is zero then the program should return an empty String.</p>

Body:
Write a Java function such that Given two strings, word and a separator, return a big string made of count occurences of the word, separated by the separator string.

repeatSeparator("Word", "X", 3) → "WordXWordXWord"
repeatSeparator("This", "And", 2) → "ThisAndThis"
repeatSeparator("This", "And", 1) → "This"

My code is as below but is not working

public String repeatSeparator(String word, String sep, int count) {
    if(count == 1) {
        return word;
    }
    if(count > 1) {
        for (int i = 0; i < count-1; i++){
            word = word + sep + word;
        }
    }
   return word;
}

Example Output ::

                                   Expected         Run                  Result
repeatSeparator("Word", "X", 3) → "WordXWordXWord" "WordXWordXWordXWord" X


问:
Linq OrderBy last n values
Lets say i have array of ints:

```<code>int[] values = new int[]{1,2,7,9,8,0};
</code>```

How to OrderBy last 2 values?

```<code>int[] values = new int[]{1,2,7,9,0,8};
</code>```

答:
You can do it like this:</p>

```<code>int[] values = new int[] { 1, 2, 7, 9, 8, 0 };
// Array.Sort accepts index and length, so you can sort only part of array
Array.Sort(values, values.Length - 2, 2);
// results in {1, 2, 7, 9, 0, 8}
</code>```

Title: Linq OrderBy last n values

Body:
Lets say i have array of ints:

int[] values = new int[]{1,2,7,9,8,0};

How to OrderBy last 2 values?

int[] values = new int[]{1,2,7,9,0,8};

Body:
You can do it like this:

int[] values = new int[] { 1, 2, 7, 9, 8, 0 };
// Array.Sort accepts index and length, so you can sort only part of array
Array.Sort(values, values.Length - 2, 2);
// results in {1, 2, 7, 9, 0, 8}


问:
E-R entity design for a web application
for exercise, I have to design a web application with online forums. Each forum refers to a specific category of sport and a specific course, e.g. soccer forum of informatic. Each user can submit a post in a forum, this post has a text, a photo and a date.

I've designed the forum like an entity with only one attribute, the category (of sport), and the post like another entity, linked by a "part of" relationship with Forum.

The Forum is linked by a relationship with the entity Course.

Do you think this is the best solution?

Thanks.

Here's an image of my elaboration:

答:
Each user can submit a post in a forum, this post has a text, a photo and a date.

So I would add the entity "user" which would have a relation with post (users submits posts) and then I would put a relation between "user" and "forum" because the user that is subscribed to the forum writes posts. Because of this, I would cancel the relation between "forum" and "post". In addtion a forum belongs only to a course I think. However consider that this is my own solution and an E/R model can be done in many ways.
This is my solution:

Title: E-R entity design for a web application


问:
Excel VBA Remove Conditional formatting keep borders
I have found a thread where the conditional formatting is removed but the format is kept.

If I run the script I am losing the conditional formatting of the borders. Is it also possible to keep all information on the border?

Best,
Alex

答:
Inside the With aCell block, you can try adding this:

```<code>Dim b as long
For b = 1 To 12
  .Borders(b).LineStyle = .DisplayFormat.Borders(b).LineStyle
  .Borders(b).Color = .DisplayFormat.Borders(b).Color
  .Borders(b).Weight = .DisplayFormat.Borders(b).Weight
Next
</code>```

p.s. I used numeric values for the enumeration xlEdgeTop, xlEdgeLeft etc..., to shorten the code with a loop.

Body:
Inside the With aCell block, you can try adding this:

Dim b as long
For b = 1 To 12
  .Borders(b).LineStyle = .DisplayFormat.Borders(b).LineStyle
  .Borders(b).Color = .DisplayFormat.Borders(b).Color
  .Borders(b).Weight = .DisplayFormat.Borders(b).Weight
Next

p.s. I used numeric values for the enumeration xlEdgeTop, xlEdgeLeft etc..., to shorten the code with a loop.


问:
ASP.NET CORE Application using some Angular 4 pages (--> ASP.NET CORE routing)
We have an existing ASP.NET CORE App with lots of controllers and views (with knockout for 2-way-binding).
Now the requirement is to build new pages (views) with Angular 4 but the rest of the App should stay unchanged.

The management says it should be made like previous knockout extensions which integrate seamlessly in ASP.NET CORE views. This means each page should be a seperate Angular 4 SPA. This requires that routing has to be done with ASP.NET CORE and not Angular 4.

Question: Is this feasible? If yes, how?

Question: Are there better strategies to extend an existing ASP.NET CORE App with Angular 4 parts than this approach?

EDIT:
What I don't understand so far is how to provide routing by ASP.NET CORE in combination with Angular4. In ASP.NET we use _Layout.cshtml for common layout code including a @Html.Partial("_Navigation") for navigation and @RenderBody() for rendering the views. We want to use razor partial views as for the Angular templates. This excellent article describes how.
But how can this be done with ASP.NET routing?

答:
One of the key purposes of Angular is to write single page applications (or SPAs). And that does NOT mean what it sounds like. The idea is that the user can seamlessly move from "page" to "page" in the Angular app without hitting the server to ask for the next page. So from the servers perspective, it is providing a single page down to the client ... and then Angular takes over and displays all 10, 50, or 100's of views.

Retaining the ASP.NET routing and rewriting each page in Angular would be pointless.

For a more concrete example, say you have a Product Management application. In Angular you would write every view: Product List, Product Detail, Product Edit, Product History, etc. When the user accesses the app ... all views are downloaded. Then the Angular routing moves the user between these views without needing to hit the server again for another page.

If each of these was an ASP.NET view, then ASP.NET would serve the Product List page. Then if the user moves to view details, they'd have to wait for the server to serve the Product Detail page. Then if the user returns to the Product List page, the user would have to wait for the server to serve the Product List page again.

So my advice is to tell management to take an Angular course (I have one if they are interested) or leave it to the developers to make the appropriate architectural choices. :-)

Seriously though ... it seems like there would be a large expense for very little benefit if you were still planning to serve every individual page from ASP.NET.

And maybe that's the answer here ... ask them what they are truly trying to achieve with a move to Angular.


问:
MS ACCESS - Hierarchical tree sort
I'm struggling with a sorting problem.

I've got a table which is as follows:

```<code>aspect_id (int)
aspect_text (memo)
root_id (int) which has as a foreign key a aspect_id
</code>```

I've got a non cyclic tree with the following dummy data:

```<code>aspect_id  aspect_text  root_id

1          root         null
2          aspect1      1
3          aspect2      1
4          aspect3      2
5          aspect5      4
</code>```

In the example the data is sorted correctly, in my database its not. I want to sort that it starts at the root element, then finds a child, output that child and does that recursively.

With CTE it is fairly doable. Access doesn't support this. With CTE it would be something like:

```<code>WITH aspectTree (aspect_id, root_id, Level#) AS
(
        Select
            aspect.aspect_id,
            aspect.root_id,
            0
        FROM aspect
        WHERE aspect.aspect_id = 44
    UNION ALL
        SELECT
            aspect.aspect_id,
            aspect.root_id,
            T.Level# + 1
        FROM aspect
        INNER JOIN aspectTree AS T
            On T.aspect_id = aspect.root_id
)
SELECT * FROM aspectTree;
</code>```

答:
If performance is not a consideration, this fairly simple solution would work:

```<code>Public Function GetLevel(ByVal lngNodeId As Long) As Long

    Dim varRootId As Variant

    varRootId = DLookup("root_id", "aspect", "aspect_id=" & lngNodeId)

    If IsNull(varRootId) Then
        GetLevel = 0
    Else
        GetLevel = GetLevel(varRootId) + 1
    End If

End Function
</code>```

You could then use that function in your ORDER BY clause:

```<code>SELECT aspect.*
FROM aspect
ORDER BY GetLevel([aspect_id]), aspect_text
</code>```

OwnerDisplayName: Jeroen

Title: MS ACCESS - Hierarchical tree sort

Body:
I'm struggling with a sorting problem.

I've got a table which is as follows:

aspect_id (int)
aspect_text (memo)
root_id (int) which has as a foreign key a aspect_id

I've got a non cyclic tree with the following dummy data:

aspect_id  aspect_text  root_id

1          root         null
2          aspect1      1
3          aspect2      1
4          aspect3      2
5          aspect5      4

In the example the data is sorted correctly, in my database its not. I want to sort that it starts at the root element, then finds a child, output that child and does that recursively.

With CTE it is fairly doable. Access doesn't support this. With CTE it would be something like:

WITH aspectTree (aspect_id, root_id, Level#) AS
(
        Select
            aspect.aspect_id,
            aspect.root_id,
            0
        FROM aspect
        WHERE aspect.aspect_id = 44
    UNION ALL
        SELECT
            aspect.aspect_id,
            aspect.root_id,
            T.Level# + 1
        FROM aspect
        INNER JOIN aspectTree AS T
            On T.aspect_id = aspect.root_id
)
SELECT * FROM aspectTree;

Body:
If performance is not a consideration, this fairly simple solution would work:

Public Function GetLevel(ByVal lngNodeId As Long) As Long

    Dim varRootId As Variant

    varRootId = DLookup("root_id", "aspect", "aspect_id=" & lngNodeId)

    If IsNull(varRootId) Then
        GetLevel = 0
    Else
        GetLevel = GetLevel(varRootId) + 1
    End If

End Function

You could then use that function in your ORDER BY clause:

SELECT aspect.*
FROM aspect
ORDER BY GetLevel([aspect_id]), aspect_text


问:
Scan for iBeacon upon receiving remote notification
I currently have an app setup to receive remote notifications using Azure Notification Hub.
Now, I would like to scan for iBeacons, see if a specific one is close by and if so, the notification should not be shown to the user. However, if the beacon isn't in sight, the user should receive this notification.

Basically I want the beacon to supress the notifications for this app.

How would one go about doing this?

答:
Based on the docs from Azure, when a remote notification comes in, you get a callback like this:

```<code>public class MyHandler extends NotificationsHandler {
  public static final int NOTIFICATION_ID = 1;
  private NotificationManager mNotificationManager;
  NotificationCompat.Builder builder;
  Context ctx;

  @Override
  public void onReceive(Context context, Bundle bundle) {
    ctx = context;
    String nhMessage = bundle.getString("message");
    sendNotification(nhMessage);
    if (MainActivity.isVisible) {
        MainActivity.mainActivity.ToastNotify(nhMessage);
    }
  }

  private void sendNotification(String msg) {
    // put your notification code here
    ...
  }
</code>```

}

If you want to filter the notifications based on what beacons are present, you can add that logic to the onReceive method like this:

```<code>  public void onReceive(Context context, Bundle bundle) {
     if (!(MyApplication)this.getApplication()).isBeaconVisible()) {
        // Suppress notification by returning early from method
        return;
     }
     ...
  }
</code>```

The above isBeaconVisible() could be implemented in a custom Android Application class using the Android Beacon Library with something like below.  You'll need to read more about how to set up that library to make this work.  You'll also need to register the custom Application class in your AndroidManifest.xml.

```<code>public class MyApplication extends Application implements BeaconConsumer, RangeNotifier {

    public Collection<Beacon> mVisibleBeacons;

    public void onCreate() {
        super.onCreate();
        BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
        // TODO: look up the proper I_BEACON_LAYOUT in a google search
        beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout(I_BEACON_LAYOUT));
        beaconManager.addRangeNotifier(this);

    }

    @Override
    public void onBeaconServiceConnect() {
        BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
        try {
            beaconManager.startRangingBeaconsInRegion(new Region("all-beacons", null, null, null));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
        mVisibleBeacons = beacons;
    }

    public boolean isBeaconVisible() {
        return mVisibleBeacons.size() > 0;
    }
}
</code>```

The above logic for isBeaconVisible() returns true if any beacon with any identifier has been seen in the last second.   But you can alter this to make it more sophisticated per your requirements.

Body:
Based on the docs from Azure, when a remote notification comes in, you get a callback like this:

public class MyHandler extends NotificationsHandler {
  public static final int NOTIFICATION_ID = 1;
  private NotificationManager mNotificationManager;
  NotificationCompat.Builder builder;
  Context ctx;

  @Override
  public void onReceive(Context context, Bundle bundle) {
    ctx = context;
    String nhMessage = bundle.getString("message");
    sendNotification(nhMessage);
    if (MainActivity.isVisible) {
        MainActivity.mainActivity.ToastNotify(nhMessage);
    }
  }

  private void sendNotification(String msg) {
    // put your notification code here
    ...
  }

}

If you want to filter the notifications based on what beacons are present, you can add that logic to the onReceive method like this:

  public void onReceive(Context context, Bundle bundle) {
     if (!(MyApplication)this.getApplication()).isBeaconVisible()) {
        // Suppress notification by returning early from method
        return;
     }
     ...
  }

The above isBeaconVisible() could be implemented in a custom Android Application class using the Android Beacon Library with something like below.  You'll need to read more about how to set up that library to make this work.  You'll also need to register the custom Application class in your AndroidManifest.xml.

public class MyApplication extends Application implements BeaconConsumer, RangeNotifier {

    public Collection<Beacon> mVisibleBeacons;

    public void onCreate() {
        super.onCreate();
        BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
        // TODO: look up the proper I_BEACON_LAYOUT in a google search
        beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout(I_BEACON_LAYOUT));
        beaconManager.addRangeNotifier(this);

    }

    @Override
    public void onBeaconServiceConnect() {
        BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);
        try {
            beaconManager.startRangingBeaconsInRegion(new Region("all-beacons", null, null, null));
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
        mVisibleBeacons = beacons;
    }

    public boolean isBeaconVisible() {
        return mVisibleBeacons.size() > 0;
    }
}

The above logic for isBeaconVisible() returns true if any beacon with any identifier has been seen in the last second.   But you can alter this to make it more sophisticated per your requirements.


问:
Assembly Language calculating recursive function
I am trying to implement the below function on assembly as recursive function call.

```<code>Int  f(n)
if (n<=3)   return n;
else        return  2 * f(n-1) + f(n-2);
</code>```

When I ran the code, I receive 1 as a result.
Please advice

```<code>INCLUDE Irvine32.inc
.CODE
main PROC
    push 5
    call RECURSIVE          ; calculate the below function
    call WriteDec
    call Crlf
    exit
main ENDP
;------------------------------
RECURSIVE PROC
; Calculates int f(n)
; if (n<=3) returns n
; else return 2*f(n-1)+f(n-2)
;------------------------------
push ebp
mov ebp,esp
mov eax,[ebp+8]             ;get n
cmp eax,3                   ;n > 3 ?
ja L1                       ; yes, continue
mov eax,1                   ; no, return 1
jmp L2                      ;return to the caller
L1:  dec eax
     push eax
     call RECURSIVE
ReturnFact:mov ebx,[ebp+8]  ;get n-1
           shl ebx,1        ;multiply by 2
           add ebx,[ebp+16] ;add n-2 and save

L2: pop ebp                 ;return eax
    ret 4                   ;clear stack
RECURSIVE ENDP

END main
</code>```

答:
```<code>INCLUDE Irvine32.inc
.CODE
main PROC
    mov ecx, 7
    push ecx
    call RECURSIVE
    call WriteDec
    call Crlf
    exit
main ENDP
;------------------------------
RECURSIVE PROC
; Calculates int f(n)
; if (n<=3) returns n
; else return 2*f(n-1)+f(n-2)
;------------------------------
push ebp
mov ebp,esp
mov eax,[ebp+8]             ;get n
cmp eax,3                   ;n > 3 ?
ja L1                       ; yes, continue
mov eax,[ebp+8]             ; no, return 1
jmp L2                      ;return to the caller
L1:  dec eax
     push eax
     call RECURSIVE

ReturnFact: shl eax,1
            push eax
            mov eax, [ebp+8]
            sub eax, 2
            push eax
            call RECURSIVE
            add eax, [ebp-4]
L2: mov esp, ebp
    pop ebp                 ;return eax
    ret 4                   ;clear stack
RECURSIVE ENDP

END main
</code>```

Body:
I am trying to implement the below function on assembly as recursive function call.

Int  f(n)
if (n<=3)   return n;
else        return  2 * f(n-1) + f(n-2);

When I ran the code, I receive 1 as a result.
Please advice

INCLUDE Irvine32.inc
.CODE
main PROC
    push 5
    call RECURSIVE          ; calculate the below function
    call WriteDec
    call Crlf
    exit
main ENDP
;------------------------------
RECURSIVE PROC
; Calculates int f(n)
; if (n<=3) returns n
; else return 2*f(n-1)+f(n-2)
;------------------------------
push ebp
mov ebp,esp
mov eax,[ebp+8]             ;get n
cmp eax,3                   ;n > 3 ?
ja L1                       ; yes, continue
mov eax,1                   ; no, return 1
jmp L2                      ;return to the caller
L1:  dec eax
     push eax
     call RECURSIVE
ReturnFact:mov ebx,[ebp+8]  ;get n-1
           shl ebx,1        ;multiply by 2
           add ebx,[ebp+16] ;add n-2 and save

L2: pop ebp                 ;return eax
    ret 4                   ;clear stack
RECURSIVE ENDP

END main


问:
Performance Monitoring Counters Threshold
I have a performance monitoring running on Server. It recorded several counters from SQL Server, Server, Web Service Performance, Web Service Cache Performance, IIS Performance, and ASP.NET Performance.
After seeing the results I can't decide whether the Server is running normal or not, because I haven't found the threshold documentation which cover all of counters from Performance Monitoring.
Does any of you could give me some references ?

Any kind of help are really appreciated.
Thank you

答:
Here is the breakdown of top SQL Server memory pressure counters followed by the threshold guidelines:

Page Life Expectancy - you can calculate the threshold based on this formula MAXBP(MB)/1024/4*300, where MAXBP represents the maximum amount of Buffer Pool memory

Buffer Cache hit ratio - this ratio needs to be as high as possible, as reading from memory is several orders of magnitude faster than reading from disks

Page reads / sec - no general guidelines

Page writes / sec - no general guidelines

Lazy writes / sec - shouldn’t exceed 20 on average systems

Memory Grants Pending - should always be less or equal to 1

Total Server Memory - should be at around 100%

Target Server Memory - equal to the current value of Max Server Memory setting

Available Mbytes - it shouldn’t drop below 2 to 4GB for today’s average production servers

Pages / sec - there is a wide range of acceptable values, and ideally this number would tend toward zero

Paging File % Usage - guideline on the values for this measurements, especially for SQL Server dedicated machines, is 0

I found these by reading an article on Top SQL Server Memory Pressure counters https://solutioncenter.apexsql.com/top-sql-server-memory-pressure-counters/ - there is a reference section at the bottom of this article if you'd like to learn more about counters and their desired values.


问:
How do I add the iPhone SDK 3 to the latest version of Xcode?
I just upgraded Xcode, but now I don't have any 3.x SDK for Simulator. How do I add it for testing purposes?</p>

答:
You can try using old versions of XCode (with previous simulators) but the most reliable one is using a device. The iPhone1's latest OS version is 3.1.3. I'm sure you can pick one pretty cheap on eBay or similar.

You will also need to make sure that you drop the minimum OS version to 3.0.


问:
How to override CSS selector?
My page includes a legacy css file which defines a style for the :invalid psuedo-class. I want to use some of the styles from this file, but I do not want invalid inputs to be red by default, I want input fields to use the default styling for input fields defined in the legacy file.

legacy.css

```<code>input:invalid {
  background-color: #F00
}
</code>```

Is there a way to override the style defined in legacy.css, and force it to use some other style from the file? Is there a better option for approaching this?

my.css

```<code>input:invalid {
  // super input:valid
}
</code>```

答:
Have you tried, the initial value for background-color to set background's color to default value ?

```<code>input:invalid{
    background-color: initial;
}
</code>```

If the css file "legacy.css" have some style for this selector, they are not modified normally

Title: How to override CSS selector?

Body:
My page includes a legacy css file which defines a style for the :invalid psuedo-class. I want to use some of the styles from this file, but I do not want invalid inputs to be red by default, I want input fields to use the default styling for input fields defined in the legacy file.

legacy.css

input:invalid {
  background-color: #F00
}

Is there a way to override the style defined in legacy.css, and force it to use some other style from the file? Is there a better option for approaching this?

my.css

input:invalid {
  // super input:valid
}

Body:
Have you tried, the initial value for background-color to set background's color to default value ?

input:invalid{
    background-color: initial;
}

If the css file "legacy.css" have some style for this selector, they are not modified normally


答:
You can use intitial for the property value.

The initial CSS keyword applies the initial value of a property to an element.

Just make sure your selector appears after the original selector.

input:invalid {
  background-color: #F00
}

input:invalid {
  background-color: initial;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="email" name="email" required></code>```

When using !important you artificially increase the properties weight (not exactly specificity, but similar). I would avoid using !important as it is typically bad practice and not required here.

Title: How to override CSS selector?

Body:
You can use intitial for the property value.

The initial CSS keyword applies the initial value of a property to an element.

Just make sure your selector appears after the original selector.

input:invalid {
  background-color: #F00
}

input:invalid {
  background-color: initial;
}

<input type="email" name="email" required>

When using !important you artificially increase the properties weight (not exactly specificity, but similar). I would avoid using !important as it is typically bad practice and not required here.


问:
How to get bounding box based on distance from given point?
I need restrict map area to 5km radius around given point.
How can I get appropriate bounding box using mapbox-gl-js or turf?</p>

答:
You can use http://turfjs.org/docs/#buffer to get a feature in size of the radius that you want and then use http://turfjs.org/docs/#bbox to get the bbox.

var point = turf.point([-90.548630, 14.616599]);
var buffered = turf.buffer(point, 5, {units:'kilometers'});
var bbox = turf.bbox(buffered);
console.log(turf.bboxPolygon(bbox));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://npmcdn.com/@turf/turf/turf.min.js"></script></code>```

Body:
You can use http://turfjs.org/docs/#buffer to get a feature in size of the radius that you want and then use http://turfjs.org/docs/#bbox to get the bbox.

var point = turf.point([-90.548630, 14.616599]);
var buffered = turf.buffer(point, 5, {units:'kilometers'});
var bbox = turf.bbox(buffered);
console.log(turf.bboxPolygon(bbox));

<script src="https://npmcdn.com/@turf/turf/turf.min.js"></script>


问:
SQL Server / select count users per combination of individual items
Users owns licenses, and a plan is a combination of licenses.
Sometimes a user owns an individual license, which is not part of a plan.

I want to count the number of users per plan. In the exemple below, it should return :

```<code>PlanName | Number of Users
P1       | 1
P2       | 2
</code>```

Tables :

```<code>Users                Licenses                Plans
-----------------    ---------------------   ----------------
Username | UserID    LicenseName|LicenseID   PlanName|PlanID
user1    | 1         L1         | 1          P1      | 1
user2    | 2         L2         | 2          P2      | 2
user3    | 3         L3         | 3
user4    | 4         L4         | 4
                     L5         | 5

UsersAndLicenses        PlansAndLicenses
----------------        ----------------
UserID | LicenseID      PlanID | LicenseID
1      | 1              P1     | 1
1      | 2              P1     | 2
1      | 3              P1     | 3
2      | 4              P2     | 4
2      | 5              P2     | 5
3      | 1
4      | 4
4      | 5
</code>```

I started with a select to get the list of users and plans  (I will apply a count on this select) and I get an issue : user3 who has only L1 (he hasn't a plan) is listed in P1 (L1 is part of P1). My select statement is :

```<code>SELECT Plans.PlanName, Users.UserName FROM Users
           INNER JOIN (((Licenses INNER JOIN LicensesPlans ON Licenses.LicenseID = LicensesPlans.LicenseID)
           INNER JOIN Plans ON LicensesPlans.PlanID = Plans.PlanID)
           INNER JOIN UsersLicenses ON Licenses.LicenseID = UsersLicenses.LicenseID) ON Users.UserID = UsersLicenses.UserID
GROUP BY Plans.PlanName, Users.UserName;
</code>```

What is wrong with my select ?

答:
I wasn't able to solve my issue with just a query.

I created a stored procedure which is called for each user.
This stored procedure use a cursor to scroll through all the plans, retrieve the licenses of each plan and compare them (using an EXCEPT statement) with the licences owned by the user.

Body:
Users owns licenses, and a plan is a combination of licenses.
Sometimes a user owns an individual license, which is not part of a plan.

I want to count the number of users per plan. In the exemple below, it should return :

PlanName | Number of Users
P1       | 1
P2       | 2

Tables :

Users                Licenses                Plans
-----------------    ---------------------   ----------------
Username | UserID    LicenseName|LicenseID   PlanName|PlanID
user1    | 1         L1         | 1          P1      | 1
user2    | 2         L2         | 2          P2      | 2
user3    | 3         L3         | 3
user4    | 4         L4         | 4
                     L5         | 5

UsersAndLicenses        PlansAndLicenses
----------------        ----------------
UserID | LicenseID      PlanID | LicenseID
1      | 1              P1     | 1
1      | 2              P1     | 2
1      | 3              P1     | 3
2      | 4              P2     | 4
2      | 5              P2     | 5
3      | 1
4      | 4
4      | 5

I started with a select to get the list of users and plans  (I will apply a count on this select) and I get an issue : user3 who has only L1 (he hasn't a plan) is listed in P1 (L1 is part of P1). My select statement is :

SELECT Plans.PlanName, Users.UserName FROM Users
           INNER JOIN (((Licenses INNER JOIN LicensesPlans ON Licenses.LicenseID = LicensesPlans.LicenseID)
           INNER JOIN Plans ON LicensesPlans.PlanID = Plans.PlanID)
           INNER JOIN UsersLicenses ON Licenses.LicenseID = UsersLicenses.LicenseID) ON Users.UserID = UsersLicenses.UserID
GROUP BY Plans.PlanName, Users.UserName;

What is wrong with my select ?


问:
How to make a variable globally accessible in Prestashop
I'm modifying a module in Prestashop, which has folder structure like this..

```<code>css
translations
index.php
module.php
module.tpl
</code>```

There is a variable $products that has an array of all the products. But it's only accessible to module.tpl which displays all the product on the homepage which I don't like.

I created a controller that redirects to a different page and a template/view/front/products.tpl to display all the products. But that $products variable is undefined in products.tpl file.

答:
You can set Cookie Variable and use it where you want. like :

```<code>$this->context->cookie->products=$products;
</code>```

if you want to print in tpl, in controller you can assign to smarty variable

```<code> $this->context->smarty->assign('products', $this->context->cookie->products);
</code>```

and in tpl use it

Body:
I'm modifying a module in Prestashop, which has folder structure like this..

css
translations
index.php
module.php
module.tpl

There is a variable $products that has an array of all the products. But it's only accessible to module.tpl which displays all the product on the homepage which I don't like.

I created a controller that redirects to a different page and a template/view/front/products.tpl to display all the products. But that $products variable is undefined in products.tpl file.

Body:
You can set Cookie Variable and use it where you want. like :

$this->context->cookie->products=$products;

if you want to print in tpl, in controller you can assign to smarty variable

 $this->context->smarty->assign('products', $this->context->cookie->products);

and in tpl use it


问:
Google maps loading before AJAX requests complete
I'm using Google Maps API with rails 5.0.4.

I'd like the map to center on the user location and fill the latitude, longitude fields with the coordinates. Currently, the lat, lng fields fill correctly, but the map loads before the async calls are completed, making the map position not match the coordinates. It does fix itself after a refresh, but on first load, the async is an issue. I tried to set this up with a promise but could not get it to work.

What is the best way to accomplish this?

```<code>$(document).ready(function(){

      function getUserCoordinates() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(setCoords);
        };
      };

      function setCoords(position) {
        lat = position.coords.latitude;
        lng = position.coords.longitude;
        updateUserLat(lat);
        updateUserLng(lng);
        document.getElementById("latitude").value = lat.toFixed(6);
        document.getElementById("longitude").value = lng.toFixed(6);
      };

      function updateUserLat(lat) {
        $.ajax({
          type: 'PATCH',
          url: '/users/:id',
          data: {'user[latitude]': lat}
        });
      };
      function updateUserLng(lng) {
        $.ajax({
          type: 'PATCH',
          url: '/users/:id',
          data: {'user[longitude]': lng}
        });
      };

      getUserCoordinates();

      function initMap(){
          initialize();
      };

});
</code>```

答:
Move initMap() function from the document ready wrapper. Call initMap directly when you have your lat/long set.

Having it in the document ready wrapper will call to initialize the map when the page loads, which is what you don't want.

Body:
I'm using Google Maps API with rails 5.0.4.

I'd like the map to center on the user location and fill the latitude, longitude fields with the coordinates. Currently, the lat, lng fields fill correctly, but the map loads before the async calls are completed, making the map position not match the coordinates. It does fix itself after a refresh, but on first load, the async is an issue. I tried to set this up with a promise but could not get it to work.

What is the best way to accomplish this?

$(document).ready(function(){

      function getUserCoordinates() {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(setCoords);
        };
      };

      function setCoords(position) {
        lat = position.coords.latitude;
        lng = position.coords.longitude;
        updateUserLat(lat);
        updateUserLng(lng);
        document.getElementById("latitude").value = lat.toFixed(6);
        document.getElementById("longitude").value = lng.toFixed(6);
      };

      function updateUserLat(lat) {
        $.ajax({
          type: 'PATCH',
          url: '/users/:id',
          data: {'user[latitude]': lat}
        });
      };
      function updateUserLng(lng) {
        $.ajax({
          type: 'PATCH',
          url: '/users/:id',
          data: {'user[longitude]': lng}
        });
      };

      getUserCoordinates();

      function initMap(){
          initialize();
      };

});


问:
C# UseVisualStyleBackColor
Is there a way in which I can change the button color and preserve the Windows VisualStyle? I want to create a button that looks like checkBox2 (color and style)

```<code>this.button2.BackColor = System.Drawing.SystemColors.GradientActiveCaption;
this.button2.UseVisualStyleBackColor = false;  //if true, BackColor gets ignored
</code>```

答:
No, not really.  This kind of button background is drawn by VisualStyleRenderer.DrawBackground().  Which in turns pinvokes DrawThemeBackground().  These methods don't take a color.  None is needed because the color is already specified in the theme.

Simulating the appearance with a LinearGradientBrush is your only real hope.  Note that custom drawing a button is quite difficult, all the code is internal and no owner-draw is provided.

Consider using an image.

Title: C# UseVisualStyleBackColor

Body:
Is there a way in which I can change the button color and preserve the Windows VisualStyle? I want to create a button that looks like checkBox2 (color and style)

this.button2.BackColor = System.Drawing.SystemColors.GradientActiveCaption;
this.button2.UseVisualStyleBackColor = false;  //if true, BackColor gets ignored


问:
In python, how can I extract string with regex?
I want to write a simple markdown parser function that will take in a single line of markdown and be translated into the appropriate HTML. To keep it simple, I want to support only one feature of markdown in atx syntax: headers.

Headers are designated by (1-6) hashes followed by a space, followed by text. The number of hashes determines the header level of the HTML output.
Examples

```<code># Header will become <h1>Header</h1>

## Header will become <h2>Header</h2>

###### Header will become <h6>Header</h6>
</code>```

Rules are as follows

Header content should only come after the initial hashtag(s) plus a space character.

Invalid headers should just be returned as the markdown that was recieved, no translation necessary.

Spaces before and after both the header content and the hashtag(s) should be ignored in the resulting output.

This is code I made.

```<code>import re
def markdown_parser(markdown):
    results =''
    pattern = re.compile("#+\s")
    matches = pattern.search(markdown.strip())
    if (matches != None):
        tag = matches[0]
        hashTagLen = len(tag) - 1
        htmlTag = "h" + str(hashTagLen)
        content = markdown.strip()[(hashTagLen + 1):]
        results = "<" + htmlTag + ">" + content + "</" + htmlTag + ">"
    else:
        results = markdown
    return results
</code>```

When I run this code, exception has occurred as follows.

Unhandled Exception: '_sre.SRE_Match' object is not subscriptable

I'm not sure why this error has occurred.

When I run the script on my shell, it works well.
But When I run it on unittest environment (import unittest), the error has occurred.

Please help me.

答:
That code looks quite verbose and a lot of that logic can be performed in regex.

If you look at the original markdown library written in perl, you can see only need one pattern, then, from the first capture group, you can attain what style of header it is.

The original implementation is here

```<code>sub _DoHeaders {
my $text = shift;

# Setext-style headers:
#     Header 1
#     ========
#
#     Header 2
#     --------
#
$text =~ s{ ^(.+)[ \t]*\n=+[ \t]*\n+ }{
    "<h1>"  .  _RunSpanGamut($1)  .  "</h1>\n\n";
}egmx;

$text =~ s{ ^(.+)[ \t]*\n-+[ \t]*\n+ }{
    "<h2>"  .  _RunSpanGamut($1)  .  "</h2>\n\n";
}egmx;

# atx-style headers:
#   # Header 1
#   ## Header 2
#   ## Header 2 with closing hashes ##
#   ...
#   ###### Header 6
#
$text =~ s{
        ^(\#{1,6})  # $1 = string of #'s
        [ \t]*
        (.+?)       # $2 = Header text
        [ \t]*
        \#*         # optional closing #'s (not counted)
        \n+
    }{
        my $h_level = length($1);
        "<h$h_level>"  .  _RunSpanGamut($2)  .  "</h$h_level>\n\n";
    }egmx;

return $text;
</code>```

}

Unless, for some reason you can't, it would be better to use the markdown library as that is an implementation of the original library, warts and all.

You can see how the Markdown-Python library implements it here

```<code>class HashHeaderProcessor(BlockProcessor):
""" Process Hash Headers. """

# Detect a header at start of any line in block
RE = re.compile(r'(^|\n)(?P<level>#{1,6})(?P<header>.*?)#*(\n|$)')

def test(self, parent, block):
    return bool(self.RE.search(block))

def run(self, parent, blocks):
    block = blocks.pop(0)
    m = self.RE.search(block)
    if m:
        before = block[:m.start()]  # All lines before header
        after = block[m.end():]     # All lines after header
        if before:
            # As the header was not the first line of the block and the
            # lines before the header must be parsed first,
            # recursively parse this lines as a block.
            self.parser.parseBlocks(parent, [before])
        # Create header using named groups from RE
        h = util.etree.SubElement(parent, 'h%d' % len(m.group('level')))
        h.text = m.group('header').strip()
        if after:
            # Insert remaining lines as first block for future parsing.
            blocks.insert(0, after)
    else:  # pragma: no cover
        # This should never happen, but just in case...
        logger.warn("We've got a problem header: %r" % block)
</code>```

Body:
I want to write a simple markdown parser function that will take in a single line of markdown and be translated into the appropriate HTML. To keep it simple, I want to support only one feature of markdown in atx syntax: headers.

Headers are designated by (1-6) hashes followed by a space, followed by text. The number of hashes determines the header level of the HTML output.
Examples

# Header will become
Header

## Header will become
Header

###### Header will become
Header

Rules are as follows

Header content should only come after the initial hashtag(s) plus a space character.

Invalid headers should just be returned as the markdown that was recieved, no translation necessary.

Spaces before and after both the header content and the hashtag(s) should be ignored in the resulting output.

This is code I made.

import re
def markdown_parser(markdown):
    results =''
    pattern = re.compile("#+\s")
    matches = pattern.search(markdown.strip())
    if (matches != None):
        tag = matches[0]
        hashTagLen = len(tag) - 1
        htmlTag = "h" + str(hashTagLen)
        content = markdown.strip()[(hashTagLen + 1):]
        results = "<" + htmlTag + ">" + content + "</" + htmlTag + ">"
    else:
        results = markdown
    return results

When I run this code, exception has occurred as follows.

Unhandled Exception: '_sre.SRE_Match' object is not subscriptable

I'm not sure why this error has occurred.

When I run the script on my shell, it works well.
But When I run it on unittest environment (import unittest), the error has occurred.

Please help me.

Body:
That code looks quite verbose and a lot of that logic can be performed in regex.

If you look at the original markdown library written in perl, you can see only need one pattern, then, from the first capture group, you can attain what style of header it is.

The original implementation is here

sub _DoHeaders {
my $text = shift;

# Setext-style headers:
#     Header 1
#     ========
#
#     Header 2
#     --------
#
$text =~ s{ ^(.+)[ \t]*\n=+[ \t]*\n+ }{
    "<h1>"  .  _RunSpanGamut($1)  .  "</h1>\n\n";
}egmx;

$text =~ s{ ^(.+)[ \t]*\n-+[ \t]*\n+ }{
    "<h2>"  .  _RunSpanGamut($1)  .  "</h2>\n\n";
}egmx;

# atx-style headers:
#   # Header 1
#   ## Header 2
#   ## Header 2 with closing hashes ##
#   ...
#   ###### Header 6
#
$text =~ s{
        ^(\#{1,6})  # $1 = string of #'s
        [ \t]*
        (.+?)       # $2 = Header text
        [ \t]*
        \#*         # optional closing #'s (not counted)
        \n+
    }{
        my $h_level = length($1);
        "<h$h_level>"  .  _RunSpanGamut($2)  .  "</h$h_level>\n\n";
    }egmx;

return $text;

}

Unless, for some reason you can't, it would be better to use the markdown library as that is an implementation of the original library, warts and all.

You can see how the Markdown-Python library implements it here

class HashHeaderProcessor(BlockProcessor):
""" Process Hash Headers. """

# Detect a header at start of any line in block
RE = re.compile(r'(^|\n)(?P<level>#{1,6})(?P<header>.*?)#*(\n|$)')

def test(self, parent, block):
    return bool(self.RE.search(block))

def run(self, parent, blocks):
    block = blocks.pop(0)
    m = self.RE.search(block)
    if m:
        before = block[:m.start()]  # All lines before header
        after = block[m.end():]     # All lines after header
        if before:
            # As the header was not the first line of the block and the
            # lines before the header must be parsed first,
            # recursively parse this lines as a block.
            self.parser.parseBlocks(parent, [before])
        # Create header using named groups from RE
        h = util.etree.SubElement(parent, 'h%d' % len(m.group('level')))
        h.text = m.group('header').strip()
        if after:
            # Insert remaining lines as first block for future parsing.
            blocks.insert(0, after)
    else:  # pragma: no cover
        # This should never happen, but just in case...
        logger.warn("We've got a problem header: %r" % block)


问:
Keras-CNTK saving model-v2 format
I'm using CNTK as the backend for Keras. I'm trying to use my model which I have trained using Keras in C++.

I have trained and saved my model using Keras which is in HDF5. How do I now use CNTK API to save it in their model-v2 format?

I tried this:

```<code>model = load_model('model2.h5')
cntk.ops.functions.Function.save(model, 'CNTK_model2.pb')
</code>```

but i got the following error:

```<code>TypeError: save() missing 1 required positional argument: 'filename'
</code>```

If tensorflow were the backend I would have done this:

```<code>model = load_model('model2.h5')
sess = K.get_session()
tf_saver = tf.train.Saver()
tf_saver.save(sess=sess, save_path=checkpoint_path)
</code>```

How can I achieve the same thing?

答:
As per the comments here, I was able to use this:</p>

```<code>import cntk as C
import keras.backend as K

keras_model = K.load_model('my_keras_model.h5')

C.combine(keras_model.model.outputs).save('my_cntk_model')
cntk_model = C.load_model('my_cntk_model')
</code>```

Title: Keras-CNTK saving model-v2 format

Body:
I'm using CNTK as the backend for Keras. I'm trying to use my model which I have trained using Keras in C++.

I have trained and saved my model using Keras which is in HDF5. How do I now use CNTK API to save it in their model-v2 format?

I tried this:

model = load_model('model2.h5')
cntk.ops.functions.Function.save(model, 'CNTK_model2.pb')

but i got the following error:

TypeError: save() missing 1 required positional argument: 'filename'

If tensorflow were the backend I would have done this:

model = load_model('model2.h5')
sess = K.get_session()
tf_saver = tf.train.Saver()
tf_saver.save(sess=sess, save_path=checkpoint_path)

How can I achieve the same thing?

Body:
As per the comments here, I was able to use this:

import cntk as C
import keras.backend as K

keras_model = K.load_model('my_keras_model.h5')

C.combine(keras_model.model.outputs).save('my_cntk_model')
cntk_model = C.load_model('my_cntk_model')


问:
jQuery PATCH request not recognised by Marvin.JsonPatch
I'm trying to send an AJAX PATCH request to a Web API method and have the patched object recognised by Marvin.JsonPatch.

So far, everything I've sent to the server has resulted in an empty request being received.

The Web API controller method looks like this:

```<code>public IHttpActionResult Update(ElementType elementType,
                                long elementId,
                                [FromBody] JsonPatchDocument<TranslationMatchDiscounts> matchDiscountsPatch)
</code>```

And that TranslationMatchDiscounts object is very straightforward:

```<code>public class TranslationMatchDiscounts
{
    public double ContextMatches { get; set; }

    public long ElementId { get; set; }

    public Enumerations.ElementType ElementType { get; set; }

    public double ExactMatches { get; set; }

    public double PerfectMatches { get; set; }

    public double Repetitions { get; set; }
}
</code>```

And my jQuery AJAX request is put together like this:

```<code>$.ajax({
    //contentType: "application/json",
    data: { "Repetitions": 0.15 },
    //data: JSON.stringify({ "Repetitions": 0.15 }),
    dataType: "json",
    //processData: false,
    method: "PATCH",
    url: // my URL
});
</code>```

The commented-out properties show some things I've tried.

The controller does get hit, that's not the problem, and the "Repetitions" property is being sent but the server-side JsonPatchDocument<TranslationMatchDiscounts> parameter is either...

null if I leave the contentType property in-place

has no properties/updates for all other attempts

What is the correct way to send a PATCH request using jQuery's .ajax()?

答:
My fault. I was under the impression that PATCH allowed us to post an object with only the changed properties, i.e....

```<code>{
    "Repetitions": 0.15
}
</code>```

No. What PATCH requires is a JSON patch document. According to the RTF:

A JSON Patch document is a JSON [RFC4627] document that represents an
array of objects.

So my example should really be

```<code>var patchDoc = [ { "op": "replace", "path": "/Repetitions", "value": 0.15 } ];

$.ajax({
    contentType: "application/json",
    data: JSON.stringify(patchDoc),
    dataType: "json",
    method: "PATCH",
    url: // my URL
});
</code>```

Body:
I'm trying to send an AJAX PATCH request to a Web API method and have the patched object recognised by Marvin.JsonPatch.

So far, everything I've sent to the server has resulted in an empty request being received.

The Web API controller method looks like this:

public IHttpActionResult Update(ElementType elementType,
                                long elementId,
                                [FromBody] JsonPatchDocument<TranslationMatchDiscounts> matchDiscountsPatch)

And that TranslationMatchDiscounts object is very straightforward:

public class TranslationMatchDiscounts
{
    public double ContextMatches { get; set; }

    public long ElementId { get; set; }

    public Enumerations.ElementType ElementType { get; set; }

    public double ExactMatches { get; set; }

    public double PerfectMatches { get; set; }

    public double Repetitions { get; set; }
}

And my jQuery AJAX request is put together like this:

$.ajax({
    //contentType: "application/json",
    data: { "Repetitions": 0.15 },
    //data: JSON.stringify({ "Repetitions": 0.15 }),
    dataType: "json",
    //processData: false,
    method: "PATCH",
    url: // my URL
});

The commented-out properties show some things I've tried.

The controller does get hit, that's not the problem, and the "Repetitions" property is being sent but the server-side JsonPatchDocument<TranslationMatchDiscounts> parameter is either...

null if I leave the contentType property in-place

has no properties/updates for all other attempts

What is the correct way to send a PATCH request using jQuery's .ajax()?

Body:
My fault. I was under the impression that PATCH allowed us to post an object with only the changed properties, i.e....

{
    "Repetitions": 0.15
}

No. What PATCH requires is a JSON patch document. According to the RTF:

A JSON Patch document is a JSON [RFC4627] document that represents an
array of objects.

So my example should really be

var patchDoc = [ { "op": "replace", "path": "/Repetitions", "value": 0.15 } ];

$.ajax({
    contentType: "application/json",
    data: JSON.stringify(patchDoc),
    dataType: "json",
    method: "PATCH",
    url: // my URL
});


问:
How to list all the wikis from forks for a specific repository on Github?
I'm interested in an opensource project but it's documentation doesn't cover much of it's details.

The project was forked more that 500 times. One of the forks has an interesting wiki with rich information about the project.

I was thinking about listing the links for all the wikis for forks of that project.

I tried going through some forks manually but it takes time and some forks doesn't have a wiki in the first place !

So is there a way to list forks wikis links for a specific project on Github ?

答:
You can use the GitHub API for that:

1. List all forks for a repo:

https://developer.github.com/v3/repos/forks/#list-forks

```<code>GET /repos/:owner/:repo/forks
</code>```

You'll get back a list of forks looking like this (example from the link, shortened for brevity):

```<code>[
  {
    "id": 1296269,
    "owner": {
      "login": "octocat",
      "id": 1,
      "avatar_url": "https://github.com/images/error/octocat_happy.gif",
      (...)
    },
    "name": "Hello-World",
    "full_name": "octocat/Hello-World",
    "description": "This your first repo!",
    "private": false,
    "fork": true,
    "url": "https://api.github.com/repos/octocat/Hello-World",
    "html_url": "https://github.com/octocat/Hello-World",
    "archive_url": "http://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}",
    "assignees_url": "http://api.github.com/repos/octocat/Hello-World/assignees{/user}",
    "blobs_url": "http://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}",
    "branches_url": "http://api.github.com/repos/octocat/Hello-World/branches{/branch}",
    "clone_url": "https://github.com/octocat/Hello-World.git",
    (...)
    "tags_url": "http://api.github.com/repos/octocat/Hello-World/tags",
    "teams_url": "http://api.github.com/repos/octocat/Hello-World/teams",
    "trees_url": "http://api.github.com/repos/octocat/Hello-World/git/trees{/sha}",
    "homepage": "https://github.com",
    "language": null,
    "forks_count": 9,
    "stargazers_count": 80,
    "watchers_count": 80,
    "size": 108,
    "default_branch": "master",
    "open_issues_count": 0,
    "topics": [
      "octocat",
      "atom",
      "electron",
      "API"
    ],
    "has_issues": true,
    "has_wiki": true,
    "has_pages": false,
    "has_downloads": true,
    "pushed_at": "2011-01-26T19:06:43Z",
    "created_at": "2011-01-26T19:01:12Z",
    "updated_at": "2011-01-26T19:14:43Z",
    "permissions": {
      "admin": false,
      "push": false,
      "pull": true
    },
    "allow_rebase_merge": true,
    "allow_squash_merge": true,
    "allow_merge_commit": true,
    "subscribers_count": 42,
    "network_count": 0
  }
]
</code>```

You can filter the repos which actually have a wiki by looking at the has_wiki property:

```<code>"has_wiki": true
</code>```

2. Getting the wiki URL

Unfortunately, there are a lot of URLs with properties, but the wiki URL is not one of them.

So you need to construct it by yourself.

Fortunately, GitHub's wiki URLs are simple:

```<code>https://github.com/:owner/:repo/wiki
</code>```

So with the example from above, it's just:

https://github.com/octocat/Hello-World -> https://github.com/octocat/Hello-World/wiki

Body:
You can use the GitHub API for that:

1. List all forks for a repo:

https://developer.github.com/v3/repos/forks/#list-forks

GET /repos/:owner/:repo/forks

You'll get back a list of forks looking like this (example from the link, shortened for brevity):

[
  {
    "id": 1296269,
    "owner": {
      "login": "octocat",
      "id": 1,
      "avatar_url": "https://github.com/images/error/octocat_happy.gif",
      (...)
    },
    "name": "Hello-World",
    "full_name": "octocat/Hello-World",
    "description": "This your first repo!",
    "private": false,
    "fork": true,
    "url": "https://api.github.com/repos/octocat/Hello-World",
    "html_url": "https://github.com/octocat/Hello-World",
    "archive_url": "http://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}",
    "assignees_url": "http://api.github.com/repos/octocat/Hello-World/assignees{/user}",
    "blobs_url": "http://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}",
    "branches_url": "http://api.github.com/repos/octocat/Hello-World/branches{/branch}",
    "clone_url": "https://github.com/octocat/Hello-World.git",
    (...)
    "tags_url": "http://api.github.com/repos/octocat/Hello-World/tags",
    "teams_url": "http://api.github.com/repos/octocat/Hello-World/teams",
    "trees_url": "http://api.github.com/repos/octocat/Hello-World/git/trees{/sha}",
    "homepage": "https://github.com",
    "language": null,
    "forks_count": 9,
    "stargazers_count": 80,
    "watchers_count": 80,
    "size": 108,
    "default_branch": "master",
    "open_issues_count": 0,
    "topics": [
      "octocat",
      "atom",
      "electron",
      "API"
    ],
    "has_issues": true,
    "has_wiki": true,
    "has_pages": false,
    "has_downloads": true,
    "pushed_at": "2011-01-26T19:06:43Z",
    "created_at": "2011-01-26T19:01:12Z",
    "updated_at": "2011-01-26T19:14:43Z",
    "permissions": {
      "admin": false,
      "push": false,
      "pull": true
    },
    "allow_rebase_merge": true,
    "allow_squash_merge": true,
    "allow_merge_commit": true,
    "subscribers_count": 42,
    "network_count": 0
  }
]

You can filter the repos which actually have a wiki by looking at the has_wiki property:

"has_wiki": true

2. Getting the wiki URL

Unfortunately, there are a lot of URLs with properties, but the wiki URL is not one of them.

So you need to construct it by yourself.

Fortunately, GitHub's wiki URLs are simple:

https://github.com/:owner/:repo/wiki

So with the example from above, it's just:

https://github.com/octocat/Hello-World -> https://github.com/octocat/Hello-World/wiki


问:
Java generics - ArrayList initialization
It is known that arraylist init. should be like this

```<code>ArrayList<A> a = new ArrayList<A>();
ArrayList<Integer> a = new ArrayList<Number>(); // compile-time error
</code>```

so, why does java allow these ?

```<code>1. ArrayList<? extends Object> a1 = new ArrayList<Object>();
2. ArrayList<?> a2 = new ArrayList<Integer>();
</code>```

then, if they are correct why doesn't allow these ?

```<code>1. a1.add(3);
2. a2.add(3);
</code>```

the compiler message is : The method add(int, capture#1-of ? extends Object) in the type ArrayList is not applicable for the arguments (int)

more general

```<code>  1. a1.add(null e);
  2. a2.add(? e);
</code>```

I read about this but it is good to hear from you. thanks

the other amusing point is :

```<code> ArrayList<ArrayList<?>> a = new ArrayList<ArrayList<?>>(); // correct
 ArrayList<?> a = new ArrayList<?>(); // wrong. I know it's reason but I have some
question in my mind that mentioned above
</code>```

答:
```<code>ArrayList<Integer> a = new ArrayList<Number>();
</code>```

Does not work because the fact that Number is a super class of Integer does not mean that List<Number> is a super class of List<Integer>. Generics are removed during compilation and do not exist on runtime, so parent-child relationship of collections cannot be be implemented: the information about element type is simply removed.

```<code>ArrayList<? extends Object> a1 = new ArrayList<Object>();
a1.add(3);
</code>```

I cannot explain why it does not work. It is really strange but it is a fact. Really syntax <? extends Object> is mostly used for return values of methods. Even in this example Object o = a1.get(0) is valid.

```<code>ArrayList<?> a = new ArrayList<?>()
</code>```

This does not work because you cannot instantiate list of unknown type...

Body:
It is known that arraylist init. should be like this

ArrayList a = new ArrayList();
ArrayList<Integer> a = new ArrayList<Number>(); // compile-time error

so, why does java allow these ?

1. ArrayList<? extends Object> a1 = new ArrayList<Object>();
2. ArrayList<?> a2 = new ArrayList<Integer>();

then, if they are correct why doesn't allow these ?

1. a1.add(3);
2. a2.add(3);

the compiler message is : The method add(int, capture#1-of ? extends Object) in the type ArrayList is not applicable for the arguments (int)

more general

  1. a1.add(null e);
  2. a2.add(? e);

I read about this but it is good to hear from you. thanks

the other amusing point is :

 ArrayList<ArrayList<?>> a = new ArrayList<ArrayList<?>>(); // correct
 ArrayList<?> a = new ArrayList<?>(); // wrong. I know it's reason but I have some
question in my mind that mentioned above

Body:
ArrayList<Integer> a = new ArrayList<Number>();

Does not work because the fact that Number is a super class of Integer does not mean that List<Number> is a super class of List<Integer>. Generics are removed during compilation and do not exist on runtime, so parent-child relationship of collections cannot be be implemented: the information about element type is simply removed.

ArrayList<? extends Object> a1 = new ArrayList<Object>();
a1.add(3);

I cannot explain why it does not work. It is really strange but it is a fact. Really syntax <? extends Object> is mostly used for return values of methods. Even in this example Object o = a1.get(0) is valid.

ArrayList<?> a = new ArrayList<?>()

This does not work because you cannot instantiate list of unknown type...


问:
Pandas df.values does not return index values
I have a multi-indexed table that I want to convert to a list.

Table: (Index Columns - 'adsh', 'report', 'line')

```<code>                                 stmt  inpth rfile                     tag  \
adsh                 report line
0000804753-17-000004 2      20     BS      0     H  AccountsPayableCurrent
0000215466-17-000058 5      19     BS      0     H  AccountsPayableCurrent
0001477932-17-000685 2      10     BS      0     H  AccountsPayableCurrent
0001554795-17-000056 2      11     BS      0     H  AccountsPayableCurrent
0001558370-17-000547 3      19     BS      0     H  AccountsPayableCurrent
</code>```

Input:

```<code>df.values
</code>```

Output:

```<code>array([['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable']], dtype=object)
</code>```

I know that I can run df.index.values to get a list of the index values as well, but what I want is the index values and column values in a single list. What is the best way to accomplish this?

答:
to_records is what you want to use.

```<code>df.to_records()
</code>```

This will return a record array that includes the index of the dataframe.

Body:
I have a multi-indexed table that I want to convert to a list.

Table: (Index Columns - 'adsh', 'report', 'line')

                                 stmt  inpth rfile                     tag  \
adsh                 report line
0000804753-17-000004 2      20     BS      0     H  AccountsPayableCurrent
0000215466-17-000058 5      19     BS      0     H  AccountsPayableCurrent
0001477932-17-000685 2      10     BS      0     H  AccountsPayableCurrent
0001554795-17-000056 2      11     BS      0     H  AccountsPayableCurrent
0001558370-17-000547 3      19     BS      0     H  AccountsPayableCurrent

Input:

df.values

Output:

array([['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable']], dtype=object)

I know that I can run df.index.values to get a list of the index values as well, but what I want is the index values and column values in a single list. What is the best way to accomplish this?

Body:
to_records is what you want to use.

df.to_records()

This will return a record array that includes the index of the dataframe.


问:
How to glue two dependent tables?
I have Customer and Application tables. I want to create select query which provides info about a customer and also to count a number of applications user has in the system.

```<code>select distinct c.id, c.region, c.city, count(a.customer_id_id)
from customers c
join applications a on c.id=a.customer_id_id
group by c.id;
</code>```

But I get an error that I need to group by region and city but I want to display info about each application not to group by region and city. Because in such a way I will get not a number of applications for each user but for each group of users.
I read that it's possible to do with nested queries and full outer join but I tried and it didn't work. Can you explain to me how to do that?

答:
Not sure what your problem is. I assume that region and city are functionally dependent of id (that is id is a candidate key). Newer versions of postgresql will therefor accept your query. However, if you're on an older version you can expand your group by clause to:

```<code>select c.id, c.region, c.city, count(a.customer_id_id)
from customers c
join applications a
    on c.id=a.customer_id_id
group by c.id, c.region, c.city;
</code>```

You say that you would like to display information about each application, but why are you then counting the number of applications per customer? Do you mean something like:

```<code>select c.id, c.region, c.city, a.customer_id_id, a.<other attributes>
from customers c
join applications a
    on c.id=a.customer_id_id;
</code>```

Title: How to glue two dependent tables?

Body:
I have Customer and Application tables. I want to create select query which provides info about a customer and also to count a number of applications user has in the system.

select distinct c.id, c.region, c.city, count(a.customer_id_id)
from customers c
join applications a on c.id=a.customer_id_id
group by c.id;

But I get an error that I need to group by region and city but I want to display info about each application not to group by region and city. Because in such a way I will get not a number of applications for each user but for each group of users.
I read that it's possible to do with nested queries and full outer join but I tried and it didn't work. Can you explain to me how to do that?

Body:
Not sure what your problem is. I assume that region and city are functionally dependent of id (that is id is a candidate key). Newer versions of postgresql will therefor accept your query. However, if you're on an older version you can expand your group by clause to:

select c.id, c.region, c.city, count(a.customer_id_id)
from customers c
join applications a
    on c.id=a.customer_id_id
group by c.id, c.region, c.city;

You say that you would like to display information about each application, but why are you then counting the number of applications per customer? Do you mean something like:

select c.id, c.region, c.city, a.customer_id_id, a.<other attributes>
from customers c
join applications a
    on c.id=a.customer_id_id;