问:
How to extend hbase command line timeout period
I'm trying to debug a problem and I'm trying to run manual scans to figure out what's going on.

However, it seems like some scans work but most fail for whatever reason.

The keys in our hbase table are setup as hash_servername_timestamp, e.g.

```<code>123_servername.domain.com_1234567890.  The hash can run from 0 to 199.
</code>```

When I run:

scan 'server_based_data', {FILTER => "KeyOnlyFilter() AND
  (PrefixFilter('0_'))", COLUMNS => 'raw_data:top', TIMERANGE =>
  [1498514400000, 1498515000000]}

I get some rows returned:

```<code>ROW                                            COLUMN+CELL
 0_app128021.sjc6.mydomain.com_1498514460   column=raw_data:top, timestamp=1498514502321, value=
 0_app128021.sjc6.mydomain.com_1498514580   column=raw_data:top, timestamp=1498514622400, value=
<snip snip>
<snip snip>
 0_app128021.sjc6.mydomain.com_1498514700   column=raw_data:top, timestamp=1498514742839, value=
179 row(s) in 177.4260 seconds
</code>```

However, if I run:

scan 'server_based_data', {FILTER => "KeyOnlyFilter() AND
  (PrefixFilter('1_'))", COLUMNS => 'raw_data:top', TIMERANGE =>
  [1498514400000, 1498515000000]}

I get an error

```<code>ROW                                            COLUMN+CELL

ERROR: Call id=86, waitTime=60002, operationTimeout=60000 expired.
Here is some help for this command:
Scan a table; pass table name and optionally a dictionary of scanner
specifications.  Scanner specifications may include one or more of:
<snip snip>
<snip snip>
</code>```

I assume "0_" works because lexiconically, it's first, compared to "1_" or "199_" but I'm confused why "1_" doesn't work.  Can someone explain to me why this doesn't work?

I also assume if I increase the timeout period that it might help make it work.  Can someone tell me how to increase the timeout period for a scan from the hbase shell?

答:
To change the timeout period from HBase shell, you can use below commands for hbase.client.operation.timeout or hbase.client.scanner.timeout.period:

```<code>001:0> @shell.hbase.configuration.get("hbase.client.scanner.timeout.period")
=> "60000"
002:0> @shell.hbase.configuration.setInt("hbase.client.scanner.timeout.period", 120000)
003:0> @shell.hbase.configuration.get("hbase.client.scanner.timeout.period")
=> "120000"
</code>```

Alternatively (not from shell), you can edit the value in hbase-site.xml however it will require a cluster restart for HBase to notice the change. Such as:

```<code><property>
 <name>hbase.client.scanner.timeout.period</name>
 <value>120000</value>
</property>
</code>```

Body:
I'm trying to debug a problem and I'm trying to run manual scans to figure out what's going on.

However, it seems like some scans work but most fail for whatever reason.

The keys in our hbase table are setup as hash_servername_timestamp, e.g.

123_servername.domain.com_1234567890.  The hash can run from 0 to 199.

When I run:

scan 'server_based_data', {FILTER => "KeyOnlyFilter() AND
  (PrefixFilter('0_'))", COLUMNS => 'raw_data:top', TIMERANGE =>
  [1498514400000, 1498515000000]}

I get some rows returned:

ROW                                            COLUMN+CELL
 0_app128021.sjc6.mydomain.com_1498514460   column=raw_data:top, timestamp=1498514502321, value=
 0_app128021.sjc6.mydomain.com_1498514580   column=raw_data:top, timestamp=1498514622400, value=
<snip snip>
<snip snip>
 0_app128021.sjc6.mydomain.com_1498514700   column=raw_data:top, timestamp=1498514742839, value=
179 row(s) in 177.4260 seconds

However, if I run:

scan 'server_based_data', {FILTER => "KeyOnlyFilter() AND
  (PrefixFilter('1_'))", COLUMNS => 'raw_data:top', TIMERANGE =>
  [1498514400000, 1498515000000]}

I get an error

ROW                                            COLUMN+CELL

ERROR: Call id=86, waitTime=60002, operationTimeout=60000 expired.
Here is some help for this command:
Scan a table; pass table name and optionally a dictionary of scanner
specifications.  Scanner specifications may include one or more of:
<snip snip>
<snip snip>

I assume "0_" works because lexiconically, it's first, compared to "1_" or "199_" but I'm confused why "1_" doesn't work.  Can someone explain to me why this doesn't work?

I also assume if I increase the timeout period that it might help make it work.  Can someone tell me how to increase the timeout period for a scan from the hbase shell?

Body:
To change the timeout period from HBase shell, you can use below commands for hbase.client.operation.timeout or hbase.client.scanner.timeout.period:

001:0> @shell.hbase.configuration.get("hbase.client.scanner.timeout.period")
=> "60000"
002:0> @shell.hbase.configuration.setInt("hbase.client.scanner.timeout.period", 120000)
003:0> @shell.hbase.configuration.get("hbase.client.scanner.timeout.period")
=> "120000"

Alternatively (not from shell), you can edit the value in hbase-site.xml however it will require a cluster restart for HBase to notice the change. Such as:

<property>
 <name>hbase.client.scanner.timeout.period</name>
 <value>120000</value>
</property>


来源: stackexchange

问:
Error When Adding Custom Content Type to Sharepoint List
I am setting up a SharePoint app/list to house my business team's project proposals for the next budget year.  I've created a custom content type (named CostProject) that has several columns in it that describe our cost projects.

Because we plan on using this process for years to come, I'm envisioning a structure where CostProject is the generic content type, with sub-content types for each budget year (2018 CostProject, 2019 CostProject, etc.).  So I created another custom content type (named 2018 CostProject) that inherits all of the columns from CostProject.

Now I'm trying to create a list of all of these cost projects.  So I added a new app (type: Custom List) and named it ITDD Cost Projects.  I went into list settings >> advanced settings and checked the option to "Allow management of content types."  Back on the list settings, I scrolled down to the content types section and clicked "Add from existing site content types."

This brought up a form where I could select various content types, so I selected 2018 CostProject from the available content types and clicked "Add >" then clicked "OK."  After clicking OK, this is the error I get every time:

"The formula cannot refer to another column.  Check the formula for
  spelling mistakes or update the formula to reference only this
  column."

Thinking this might have something to do with the syntax of one of my calculated columns, I went back the CostProject content type and removed all of the calculated columns (copied their formulas, etc. into a document so I can come back to them later).  However I still get the same error message every time I try to add the content type to the list.

Any idea what I'm missing here?  I'm pretty new to SharePoint so perhaps it's something basic--any help would be greatly appreciated!

THANK YOU!!!

答:
So for the sake of people not reading comments. When you encounter an error which states that:

The formula cannot refer to another column. Check the formula for
  spelling mistakes or update the formula to reference only this
  column.

You should check your validation formulas on columns.

It may occur in different situations, but the core issue is that field cannot be added to list:

Here is reported bug when creating list from template and this is possible workaround.

ContentLicense: CC BY-SA 3.0


问:
Filtering any email address
I have an authorizer function which needs to check email rules with wildcards e.g.

mike.12@*.myapp.com

p*@*.in

julia.admin@myapp.*

so e.g.

peter@gmail.com => false

peter@myapp.it => true (3rd. rule)

pete@someapp.in => true (2nd rule)

I am a bit stuck on how to best construct a regex - or maybe there are other out of the box solutions?
Appreciate any help!
Thanks

答:
Try this regex ([a-zA-Z0-9-_\.]*)\@(.*?.in|.*?myapp.*)

Demo https://regex101.com/r/D6thOr/1

Title: Filtering any email address


问:
NetSuite SuiteScript 1.0 email attachment
I am fairly new to NetSuite scripting and have the following issue.

I am trying to send an email from SuiteScript 1.0. The Script is linked to the AFTER SUBMIT function of Sales Orders.

My code:

```<code>function OnAfterSubmit(record) {
    var fromId = -5; //Authors' Internal ID
    var sbj = 'subject';
    var msg = '';

    //load File from netSuite Document Repository with ID of 123
    var orderid = nlapiGetRecordId();
    var search = nlapiSearchRecord('salesorder', orderid);
    var fileObj = nlapiLoadRecord(search.getRecordType(), search.getId());
    //var detail = getOrderDetail(fileObj);
    //Single Attachment - Attach File ID 123
    //nlapiSendEmail(fromId, 'xyz@test1.example', sbj, msg, null, null, null, fileObj);

    //multiple Attachments
    //build Array of file objects
    var attach = [fileObj];
    //pass attach array as attachment parameter
    nlapiSendEmail(fromId, 'charl@email.example', sbj, msg, null, null, null, attach);
}
</code>```

I am trying to send the record that has been created by the user, via email.

The record parameter doesn't seem to be what I expect. The error I receive says "invalid search". When I used record.id, the error simply said "id". I also tried record.internalId.

答:
function OnAfterSubmit(type) {

    var fromId = -5; //Authors' Internal ID
    var toEmail = 'charl@email.example';
    var sbj = 'subject';
    var msg = '';

    var newRecord = nlapiGetNewRecord();
    var recordAsJSON = JSON.stringify(newRecord);
    var fileObj = nlapiCreateFile('salesorder.json', 'JSON', recordAsJSON);

    nlapiSendEmail(fromId, toEmail, sbj, msg, null, null, null, fileObj);

}
```

Body:
I am fairly new to NetSuite scripting and have the following issue.

I am trying to send an email from SuiteScript 1.0. The Script is linked to the AFTER SUBMIT function of Sales Orders.

My code:

function OnAfterSubmit(record) {
    var fromId = -5; //Authors' Internal ID
    var sbj = 'subject';
    var msg = '';

    //load File from netSuite Document Repository with ID of 123
    var orderid = nlapiGetRecordId();
    var search = nlapiSearchRecord('salesorder', orderid);
    var fileObj = nlapiLoadRecord(search.getRecordType(), search.getId());
    //var detail = getOrderDetail(fileObj);
    //Single Attachment - Attach File ID 123
    //nlapiSendEmail(fromId, 'xyz@test1.example', sbj, msg, null, null, null, fileObj);

    //multiple Attachments
    //build Array of file objects
    var attach = [fileObj];
    //pass attach array as attachment parameter
    nlapiSendEmail(fromId, 'charl@email.example', sbj, msg, null, null, null, attach);
}

I am trying to send the record that has been created by the user, via email.

The record parameter doesn't seem to be what I expect. The error I receive says "invalid search". When I used record.id, the error simply said "id". I also tried record.internalId.


问:
Java Server socket stuck on accept call (Android Client, Java Server)
Below I have put a fragment of code to help understand my problem. I have a server code, works fine for the first time the client loads and sends a packet. After the first packet is received, the server is stuck on "accept".

I have wireshark configured for this port, and the server is getting those packets. I just wonder why accept wont return more than once. Its driving me nuts.

Server Code

```<code> public class DAPool implements Runnable {
 private ServerSocket serverSocket;
 private ArrayList<DA> pool;
 private LinkedList<Socket> clientConnQ;
 public DAPool(int newPoolSize, int serverPort) {
  try {
     serverSocket = new ServerSocket(serverPort, 500, InetAddress.getByName("127.0.0.1"));
  } catch (IOException e) {
     e.printStackTrace();
     return;
  }
  poolSize = newPoolSize;
  clientConnQ = new LinkedList<Socket>();
  pool = new ArrayList<DA>(poolSize);
                DA deviceThread;
  for (int threads = 0; threads < poolSize; threads++) {
     deviceThread = new DA();
     connPool.add(deviceThread);
     deviceThread.start();
  }
 }
 public void run() {
    while (true) {
       Socket incomingSocket;
       try {
           incomingSocket = serverSocket.accept();
       } catch (IOException e) {
           e.printStackTrace();
       return;
     }
     insertNewConnToQ(incomingSocket);
  }
 }

 private class DA extends Thread {
  private Socket clientSocket;
  private ObjectInputStream inputObjectStream;
  public DA() {
  }
  public void run() {
   while (true) {

    while (clientConnQ.isEmpty()) {
     synchronized (clientConnQ) {
      try {
       clientConnQ.wait();
      } catch (InterruptedException ignored) {
       ignored.printStackTrace();
      }
     }
    }
    synchronized (clientConnQ) {
     clientSocket = (Socket) clientConnQ.removeFirst();
     try {
      inputObjectStream = new ObjectInputStream(clientSocket.getInputStream());
     } catch (IOException e) {
      e.printStackTrace();
      return;
     }
        // Do something useful here
                                    }
    }
   }
  }
 }
</code>```

Client Code

```<code>public class SendQueue extends Thread {
 LinkedList<Message> requestQ;
 Message sendRequest, requestMessage;

 Socket clientSocket;
 OutputStream outputStream;
 ObjectOutputStream objectOutputStream;

 public SendQueue(Socket newClientSocket) {
  requestQ = new LinkedList<Message>();
  clientSocket = newClientSocket;
 }

 public void run() {
  while (true) {
   synchronized (requestQ) {
    while (requestQ.isEmpty()) {
     try {
      requestQ.wait();
     } catch (InterruptedException ignored) {
      ignored.printStackTrace();
     }
    }
    sendRequest = requestQ.removeFirst();
   }
   try {
    outputStream = clientSocket.getOutputStream();
    objectOutputStream = new ObjectOutputStream(outputStream);
    objectOutputStream.writeObject(sendRequest);
    objectOutputStream.flush();
    outputStream.flush();
   } catch (IOException e) {
    e.printStackTrace();
   } catch (RuntimeException e) {
    e.printStackTrace();
   }
  }
 }

 public int sendRequest(Message message) {
  synchronized (requestQ) {
   requestQ.addLast(message);
   requestQ.notify();
  }
  return 0;
 }
}
</code>```

答:
I don't see a timeout being set on the serverSocket.

ServerSocket.accept() is a blocking operation so it will block until either an error occurs, a timeout occurs, or a connection is accepted.

Try

```<code>SererSocket.setSOTimeout(10000)
</code>```

You also don't seem to be closing your streams when your finished.

Body:
Below I have put a fragment of code to help understand my problem. I have a server code, works fine for the first time the client loads and sends a packet. After the first packet is received, the server is stuck on "accept".

I have wireshark configured for this port, and the server is getting those packets. I just wonder why accept wont return more than once. Its driving me nuts.

Server Code

 public class DAPool implements Runnable {
 private ServerSocket serverSocket;
 private ArrayList<DA> pool;
 private LinkedList<Socket> clientConnQ;
 public DAPool(int newPoolSize, int serverPort) {
  try {
     serverSocket = new ServerSocket(serverPort, 500, InetAddress.getByName("127.0.0.1"));
  } catch (IOException e) {
     e.printStackTrace();
     return;
  }
  poolSize = newPoolSize;
  clientConnQ = new LinkedList<Socket>();
  pool = new ArrayList<DA>(poolSize);
                DA deviceThread;
  for (int threads = 0; threads < poolSize; threads++) {
     deviceThread = new DA();
     connPool.add(deviceThread);
     deviceThread.start();
  }
 }
 public void run() {
    while (true) {
       Socket incomingSocket;
       try {
           incomingSocket = serverSocket.accept();
       } catch (IOException e) {
           e.printStackTrace();
       return;
     }
     insertNewConnToQ(incomingSocket);
  }
 }

 private class DA extends Thread {
  private Socket clientSocket;
  private ObjectInputStream inputObjectStream;
  public DA() {
  }
  public void run() {
   while (true) {

    while (clientConnQ.isEmpty()) {
     synchronized (clientConnQ) {
      try {
       clientConnQ.wait();
      } catch (InterruptedException ignored) {
       ignored.printStackTrace();
      }
     }
    }
    synchronized (clientConnQ) {
     clientSocket = (Socket) clientConnQ.removeFirst();
     try {
      inputObjectStream = new ObjectInputStream(clientSocket.getInputStream());
     } catch (IOException e) {
      e.printStackTrace();
      return;
     }
        // Do something useful here
                                    }
    }
   }
  }
 }

Client Code

public class SendQueue extends Thread {
 LinkedList<Message> requestQ;
 Message sendRequest, requestMessage;

 Socket clientSocket;
 OutputStream outputStream;
 ObjectOutputStream objectOutputStream;

 public SendQueue(Socket newClientSocket) {
  requestQ = new LinkedList<Message>();
  clientSocket = newClientSocket;
 }

 public void run() {
  while (true) {
   synchronized (requestQ) {
    while (requestQ.isEmpty()) {
     try {
      requestQ.wait();
     } catch (InterruptedException ignored) {
      ignored.printStackTrace();
     }
    }
    sendRequest = requestQ.removeFirst();
   }
   try {
    outputStream = clientSocket.getOutputStream();
    objectOutputStream = new ObjectOutputStream(outputStream);
    objectOutputStream.writeObject(sendRequest);
    objectOutputStream.flush();
    outputStream.flush();
   } catch (IOException e) {
    e.printStackTrace();
   } catch (RuntimeException e) {
    e.printStackTrace();
   }
  }
 }

 public int sendRequest(Message message) {
  synchronized (requestQ) {
   requestQ.addLast(message);
   requestQ.notify();
  }
  return 0;
 }
}

Body:
I don't see a timeout being set on the serverSocket.

ServerSocket.accept() is a blocking operation so it will block until either an error occurs, a timeout occurs, or a connection is accepted.

Try

SererSocket.setSOTimeout(10000)

You also don't seem to be closing your streams when your finished.

ContentLicense: CC BY-SA 2.5


问:
Make a div transparent but not the image inside
I want to have a div that has an image inside, but with the div and background being completely transparent, giving the impression the image exists alone, with the elements behind the background of the div appearing.

I've tried using rgba in several ways, such as background: rgba(204, 204, 204, 0.5); but all of these end up leaving a white background on the div when set to total transparency.

How can I implement this?

EDIT
Here is a picture:

How can I make the red button appear as normal, but be able to see what is behind the white part?

My HTML is as such:

```<code><div id="transparent-background">
    <img src="./images/ui/chat.gif" class="arrow-button"/>
</div>
</code>```

Thanks,

答:
Just use this CSS for your DIV:</p>

```<code>#transparent-background {
  background: transparent;
}
</code>```

Body:
I want to have a div that has an image inside, but with the div and background being completely transparent, giving the impression the image exists alone, with the elements behind the background of the div appearing.

I've tried using rgba in several ways, such as background: rgba(204, 204, 204, 0.5); but all of these end up leaving a white background on the div when set to total transparency.

How can I implement this?

EDIT
Here is a picture:

How can I make the red button appear as normal, but be able to see what is behind the white part?

My HTML is as such:

Thanks,

Body:
Just use this CSS for your DIV:

#transparent-background {
  background: transparent;
}


问:
Why is javascript looping through elements but executing jQuery function on all of them simultaneously?
I have a text "HELLO" and I want to loop through every letter and animate it so it fades in and out.Here's my code.

EDIT: I put the answer in the snippet to see it in action.

Code:

$(document).ready(function() {
  var $letters = $('p[id^="letter-"');
  $letters.each(function(index) {
    $(this).css({
      'animation': 'pulse 500ms ' + index * 500 + 'ms' + ' linear'
    })
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  font-size: 45px;
}

p {
  position: absolute;
  left: 400px;
  top: 100px;
  color: rgba(0, 0, 0, 0);
}

@keyframes pulse {
  0% {
    color: rgba(0, 0, 0, 0);
  }
  25% {
    color: rgba(0, 0, 0, 0.5);
  }
  50% {
    color: rgba(0, 0, 0, 1);
  }
  75% {
    color: rgba(0, 0, 0, 0.5);
  }
  100% {
    color: rgba(0, 0, 0, 0);
  }
}</code>```

H

E

L

L

O
```

And here's a link to a pen.
Instead of doing the animation one letter at a time, it's animating the whole thing at once.How can this be fixed? Shouldn't a loop finish executing all the commands and then move on to the next step? Maybe there's a better approach to this that I don't know of?

答:
One thing you should definitely correct is the naming of your ids. A single number is not a valid id.

A better option might be to name them something like letter-0, letter-1, etc.

Next, you can use the animation-delay property to offset the start of each animation. We'll use the shorthand animation property. To do this, we'll find each element with an id starting with letter-, then loop through them. For each consecutive letter we'll add the animation, and include an animation delay of 500ms * its position index in the string. For example, the first letter (index 0) will have an animation delay of 0ms. The second letter (index 1) will have an animation delay of 500ms, and so on.

$(document).ready(function() {
  var $letters = $('p[id^="letter-"');
  $letters.each(function(index) {
    $(this).css({
      'animation': 'pulse 500ms ' + index * 500 + 'ms' + ' linear'
    })
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  font-size: 45px;
}

p {
  position: absolute;
  left: 400px;
  top: 100px;
  color: rgba(0, 0, 0, 0);
}

@keyframes pulse {
  0% {
    color: rgba(0, 0, 0, 0);
  }
  25% {
    color: rgba(0, 0, 0, 0.5);
  }
  50% {
    color: rgba(0, 0, 0, 1);
  }
  75% {
    color: rgba(0, 0, 0, 0.5);
  }
  100% {
    color: rgba(0, 0, 0, 0);
  }
}</code>```

H

E

L

L

O
```

ContentLicense: CC BY-SA 4.0

Body:
I have a text "HELLO" and I want to loop through every letter and animate it so it fades in and out.Here's my code.

EDIT: I put the answer in the snippet to see it in action.

Code:

$(document).ready(function() {
  var $letters = $('p[id^="letter-"');
  $letters.each(function(index) {
    $(this).css({
      'animation': 'pulse 500ms ' + index * 500 + 'ms' + ' linear'
    })
  });
});

html,
body {
  font-size: 45px;
}

p {
  position: absolute;
  left: 400px;
  top: 100px;
  color: rgba(0, 0, 0, 0);
}

@keyframes pulse {
  0% {
    color: rgba(0, 0, 0, 0);
  }
  25% {
    color: rgba(0, 0, 0, 0.5);
  }
  50% {
    color: rgba(0, 0, 0, 1);
  }
  75% {
    color: rgba(0, 0, 0, 0.5);
  }
  100% {
    color: rgba(0, 0, 0, 0);
  }
}

H

E

L

L

O

And here's a link to a pen.
Instead of doing the animation one letter at a time, it's animating the whole thing at once.How can this be fixed? Shouldn't a loop finish executing all the commands and then move on to the next step? Maybe there's a better approach to this that I don't know of?

Body:
One thing you should definitely correct is the naming of your ids. A single number is not a valid id.

A better option might be to name them something like letter-0, letter-1, etc.

Next, you can use the animation-delay property to offset the start of each animation. We'll use the shorthand animation property. To do this, we'll find each element with an id starting with letter-, then loop through them. For each consecutive letter we'll add the animation, and include an animation delay of 500ms * its position index in the string. For example, the first letter (index 0) will have an animation delay of 0ms. The second letter (index 1) will have an animation delay of 500ms, and so on.

$(document).ready(function() {
  var $letters = $('p[id^="letter-"');
  $letters.each(function(index) {
    $(this).css({
      'animation': 'pulse 500ms ' + index * 500 + 'ms' + ' linear'
    })
  });
});

html,
body {
  font-size: 45px;
}

p {
  position: absolute;
  left: 400px;
  top: 100px;
  color: rgba(0, 0, 0, 0);
}

@keyframes pulse {
  0% {
    color: rgba(0, 0, 0, 0);
  }
  25% {
    color: rgba(0, 0, 0, 0.5);
  }
  50% {
    color: rgba(0, 0, 0, 1);
  }
  75% {
    color: rgba(0, 0, 0, 0.5);
  }
  100% {
    color: rgba(0, 0, 0, 0);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='letter-0'>H</p>
<p id='letter-1'>E</p>
<p id='letter-2'>L</p>
<p id='letter-3'>L</p>
<p id='letter-4'>O</p>


问:
How do I get TypeScript to bundle a 3rd party lib from node_modules?
I would like the TypeScript Compiler to use node_modules/firebase/firebase.d.ts to typecheck my code and also bundle node_modules/firebase/firebase.js into some of the files where I import things from firebase. I understand there are many options which will do this for me, but I'd like to keep a minimal dev environment.

I have set "moduleResolution": "node" in my tsconfig.json, which imports the definitions and type checks my code as I want. I've also added  "isolatedModules": true in an attempt to have it bundle the actual code into each of my targets, but the generated code does not bundle firebase.js as I would like. Is there a "module" compiler option which will do this for me, or should I be adding something else?

If I absolutely need another tool in my dev process, what is the simplest addition to tsc which will bundle each of my JS files + their dependencies into a single js file bundle?

答:
tsc is a compiler, not a bundler. This question expounds on bundling a bit.

While developing in TypeScript, gulp + gulp-browserify can provide a watcher and bundler.

With "module": "umd" in the compiler options, this gulpfile.js will do the rest:

```<code>var gulp = require('gulp');
var ts = require('gulp-typescript');
var browserify = require('gulp-browserify');

gulp.task('default', function () {
  return gulp.src('src/*.ts')
    .pipe(ts.createProject('tsconfig.json')())
    .pipe(browserify())
    .pipe(gulp.dest('dist/gen'));
});

gulp.task('watch', ['default'], function () {
  gulp.watch('src/*.ts', ['default']);
});
</code>```

Body:
tsc is a compiler, not a bundler. This question expounds on bundling a bit.

While developing in TypeScript, gulp + gulp-browserify can provide a watcher and bundler.

With "module": "umd" in the compiler options, this gulpfile.js will do the rest:

var gulp = require('gulp');
var ts = require('gulp-typescript');
var browserify = require('gulp-browserify');

gulp.task('default', function () {
  return gulp.src('src/*.ts')
    .pipe(ts.createProject('tsconfig.json')())
    .pipe(browserify())
    .pipe(gulp.dest('dist/gen'));
});

gulp.task('watch', ['default'], function () {
  gulp.watch('src/*.ts', ['default']);
});


问:
Can't see permissions for new model in Django's admin interface
I registered a new model in Django's admin interface but I can't see any permissions related to it that I can assign to users or groups.

Could it be related to the fact that my models come from a different database?

答:
I fixed a very similar issue today where I couldn't assign Users permissions concerning tables that were created in multiple databases because those tables didn't appear in the list of "available permissions."

It appears that I accidentally migrated the model creation migrations to the default database before I correctly used the --database DATABASE flag with manage.py migrate. So I had the same table names in both the default and auxiliary databases. I dropped the tables in the default database, leaving only the tables in the auxiliary database, and then the tables appeared in the permissions list.


问:
Converting stored procedures PL/SQL to Java
Is anyone aware of an opensource tool to convert PL/SQL to Java. Or if you have any suggestions to prepare making this tool.</p>

答:
Check out for a commercial one: http://www.io64.com/plsql-to-java-migration/

In demo, generated code is also executed.


问:
Converting for loops to while loops
I am having problems converting this for loop into a while loop. I am using python 3.6. It is supposed to print out something that looks like this when it has a constant of 3.

```<code>        |../\..../\..|
        |./\/\../\/\.|
        |/\/\/\/\/\/\|
</code>```

But my problem is that I can't quite figure out how to convert the for loops into while loops.

```<code>    def triangle(constant):
        for a in range (1, constant+1):
            print ("|", end='')
            for b in range (1,(constant-a+1)):
                print (".",end= '')
            for c in range (1, a+1):
                print ("/\\", end= '')
            for d in range (1, (constant-a+1)):
                print ("..", end= '')
            for e in range (1, a+1):
                print ("/\\", end= '')
            for f in range (1,constant-a+1):
                print (".", end='')
            print ("|")
</code>```

The main problem I am having is that nesting while loops constantly leaves me with either a constantly looping program or a program that doesn't loop enough as it ends too early.

```<code>a = 1
while (a < constant+1):
    print ("|", end='')
    while (a < constant-a+1):
        print (".",end= '')
        print ("/\\", end= '')
        print ("..", end= '')
        print ("/\\", end= '')
        print (".", end='')
        a += 1
    print ("|")
    a += 1
</code>```

This is my first attempt and I was wondering if I need to declare another variable to use to end the original while loop or if there is a way to still use a.

答:
```<code>a = 1
while a < constant+1:
    ...
    a += 1
</code>```

Title: Converting for loops to while loops

Body:
I am having problems converting this for loop into a while loop. I am using python 3.6. It is supposed to print out something that looks like this when it has a constant of 3.

        |../\..../\..|
        |./\/\../\/\.|
        |/\/\/\/\/\/\|

But my problem is that I can't quite figure out how to convert the for loops into while loops.

    def triangle(constant):
        for a in range (1, constant+1):
            print ("|", end='')
            for b in range (1,(constant-a+1)):
                print (".",end= '')
            for c in range (1, a+1):
                print ("/\\", end= '')
            for d in range (1, (constant-a+1)):
                print ("..", end= '')
            for e in range (1, a+1):
                print ("/\\", end= '')
            for f in range (1,constant-a+1):
                print (".", end='')
            print ("|")

The main problem I am having is that nesting while loops constantly leaves me with either a constantly looping program or a program that doesn't loop enough as it ends too early.

a = 1
while (a < constant+1):
    print ("|", end='')
    while (a < constant-a+1):
        print (".",end= '')
        print ("/\\", end= '')
        print ("..", end= '')
        print ("/\\", end= '')
        print (".", end='')
        a += 1
    print ("|")
    a += 1

This is my first attempt and I was wondering if I need to declare another variable to use to end the original while loop or if there is a way to still use a.

Body:
a = 1
while a < constant+1:
    ...
    a += 1


问:
android view not updated from another class and another thread
I am trying to update TextView in an activity, the method which updates the view is in the main activity (normal situation), but calling this method is from another class (and another thread).

This is the method which updates the view, this method is in the main activity,
 (please note that all logs are printed correctly and in the correct order):

```<code>    public void getDataFromFiles() {
    String new_text = JsonReader.readTextData(dataName,activityName, this);
    Log.i("Loading", "loaded text " + new_text  );
    if (new_text != null) {
        TextView introText = (TextView) findViewById(R.id.loading_introTxt);
        introText.setText(new_text);
    }

}
</code>```

This is where it is called from another class called LoadingThread, and it has reference (loadingActivity) :

```<code>            activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.i("LoadingThread", "Will update loading screen");
                loadingActivity.getDataFromFiles();

            }
        });
</code>```

Also note how the LoadingThread class is called from main activity

```<code>    LoadingThread loadingThread = LoadingThread.getInstance(this);
    Thread thread = new Thread(loadingThread);
    loadingThread.setActivity(this);
    thread.start();
</code>```

so this is the flow:
the main activity starts the LoadingThread which then after that call a method in the main activity again which is supposed to update the view, but this does not happen, but when closing the app and reopening it again, the updates are there then.

答:
I found the problem, it was in

```<code>LoadingThread loadingThread = LoadingThread.getInstance(this);
Thread thread = new Thread(loadingThread);
loadingThread.setActivity(this);
</code>```

while getInstance() is:

```<code>    if (instance == null) {
        instance = new LoadingThread();
        instance.loadingActivity = loadingActivity;

    }
    return instance;
</code>```

when closing and reopening the app, the instance is not null so returning the previous activity which is not here any more because the reference on loading activity was not updated, so I changed it like that

```<code>    if (instance == null) {
        instance = new LoadingThread();
    }
    instance.loadingActivity = loadingActivity;
    return instance;
</code>```

and now it works!

Body:
I am trying to update TextView in an activity, the method which updates the view is in the main activity (normal situation), but calling this method is from another class (and another thread).

This is the method which updates the view, this method is in the main activity,
 (please note that all logs are printed correctly and in the correct order):

    public void getDataFromFiles() {
    String new_text = JsonReader.readTextData(dataName,activityName, this);
    Log.i("Loading", "loaded text " + new_text  );
    if (new_text != null) {
        TextView introText = (TextView) findViewById(R.id.loading_introTxt);
        introText.setText(new_text);
    }

}

This is where it is called from another class called LoadingThread, and it has reference (loadingActivity) :

            activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.i("LoadingThread", "Will update loading screen");
                loadingActivity.getDataFromFiles();

            }
        });

Also note how the LoadingThread class is called from main activity

    LoadingThread loadingThread = LoadingThread.getInstance(this);
    Thread thread = new Thread(loadingThread);
    loadingThread.setActivity(this);
    thread.start();

so this is the flow:
the main activity starts the LoadingThread which then after that call a method in the main activity again which is supposed to update the view, but this does not happen, but when closing the app and reopening it again, the updates are there then.

Body:
I found the problem, it was in

LoadingThread loadingThread = LoadingThread.getInstance(this);
Thread thread = new Thread(loadingThread);
loadingThread.setActivity(this);

while getInstance() is:

    if (instance == null) {
        instance = new LoadingThread();
        instance.loadingActivity = loadingActivity;

    }
    return instance;

when closing and reopening the app, the instance is not null so returning the previous activity which is not here any more because the reference on loading activity was not updated, so I changed it like that

    if (instance == null) {
        instance = new LoadingThread();
    }
    instance.loadingActivity = loadingActivity;
    return instance;

and now it works!


问:
ComponenWillMount happening after render for some reason in react native
```<code>    componentDidMount() {
    const refi = database.ref("highscores");

    // Pushing sorted data to highscoreArray.
    refi.orderByChild("highscore").limitToLast(3).on("value", function(snapshot) {
        sortedHighscores = [];
        snapshot.forEach(function(child) {
            sortedHighscores.push({
                "username" : child.val().username,
                "score" : child.val().highscore
            });
        });

        sortedHighscores.sort(function(a,b) {
            return a.score - b.score;
        });
        this.setState({highscoreArray : sortedHighscores.reverse()});
    });
    console.log("highscore is:", this.state.highscoreArray);
}
</code>```

I am trying to get data from database and put it inside highscoreArray. Then I am trying to put it as a text in render. Some reason it is empty or null. This means that componentWillMount() happens after render()

Can someone explain or make this work? I am so frustrated.

I have changed the code as people have assisted me but still it is giving error:

```<code>undefined is not a function (evaluating 'this.setState({ highscoreArray:sortedHighscores.reverse()})')
</code>```

答:
Data stored in a Firebase Realtime Database is retrieved by attaching an asynchronous listener to a database reference

According to the documentation.

So until the result is not know, the following code this.state.highscoreArray[0]["score"].toString() will return an error. Before to display result, check if highscoreArray contains some items.

Moreover, it is not a good practice to retrieve data. Take a look to the React component lifecycle:

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state synchronously in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method

Body:
    componentDidMount() {
    const refi = database.ref("highscores");

    // Pushing sorted data to highscoreArray.
    refi.orderByChild("highscore").limitToLast(3).on("value", function(snapshot) {
        sortedHighscores = [];
        snapshot.forEach(function(child) {
            sortedHighscores.push({
                "username" : child.val().username,
                "score" : child.val().highscore
            });
        });

        sortedHighscores.sort(function(a,b) {
            return a.score - b.score;
        });
        this.setState({highscoreArray : sortedHighscores.reverse()});
    });
    console.log("highscore is:", this.state.highscoreArray);
}

I am trying to get data from database and put it inside highscoreArray. Then I am trying to put it as a text in render. Some reason it is empty or null. This means that componentWillMount() happens after render()

Can someone explain or make this work? I am so frustrated.

I have changed the code as people have assisted me but still it is giving error:

undefined is not a function (evaluating 'this.setState({ highscoreArray:sortedHighscores.reverse()})')


问:
No Id, No name. How to click this button?
I am using selenium webdriver with python to navigate through a site and I can not figure out how to select this button.

```<code><button onclick="addAutoTrade();blur();" type="button" style="background-
color:#c7c7c7;">Add</button>
</code>```

The button is surrounded by a class but within the class are 2 buttons.
I have tried using

```<code>driver.find_element_by_link_text("Add")
driver.find_element_by_partial_link_text("Add")
driver.find_element_by_name("Add")
</code>```

There is no obvious id so I am stuck and I apologize if this is trivial. How can I click this button?

答:
try this, hope this works for you:

```<code>from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

buttonXpath = "//button[contains(.,'Add')]"

element = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,buttonXpath)))
element.click()
</code>```

You can learn more about waits here and check selenium expected_conditions. these are quite usefull.

You can also see these topics about selecting buttons by text, they might help:

topic 1

topic 2

Body:
I am using selenium webdriver with python to navigate through a site and I can not figure out how to select this button.

<button onclick="addAutoTrade();blur();" type="button" style="background-
color:#c7c7c7;">Add</button>

The button is surrounded by a class but within the class are 2 buttons.
I have tried using

driver.find_element_by_link_text("Add")
driver.find_element_by_partial_link_text("Add")
driver.find_element_by_name("Add")

There is no obvious id so I am stuck and I apologize if this is trivial. How can I click this button?

Body:
try this, hope this works for you:

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

buttonXpath = "//button[contains(.,'Add')]"

element = WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,buttonXpath)))
element.click()

You can learn more about waits here and check selenium expected_conditions. these are quite usefull.

You can also see these topics about selecting buttons by text, they might help:

topic 1

topic 2


问:
Specializing a template member function of a template class?
I have a template class that has a template member function that needs to be specialized, as in:

```<code>template <typename T>
class X
{
public:
    template <typename U>
    void Y() {}

    template <>
    void Y<int>() {}
};
</code>```

Altough VC handles this correctly, apperantly this isn't standard and GCC complains: explicit specialization in non-namespace scope 'class X<T>'

I tried:

```<code>template <typename T>
class X
{
public:
    template <typename U>
    void Y() {}
};

template <typename T>
// Also tried `template<>` here
void X<T>::Y<int>() {}
</code>```

But this causes both VC and GCC to complain.

What's the right way to do this?

答:
Use a Helper class to remove the class specialization

Example 1

```<code>namespace {
/* Make this work
template <typename T>
class X
{
public:
    template <typename U>
    void Y() {}

    template <>
    void Y<int>() {}
};
*/

template <typename  K>
struct IntegerHelper {
    static bool isInteger() { return false; }
};

template <>
inline bool IntegerHelper<int>::isInteger() {
    return true;
}

template <typename T>
class TestX {

public:
    template <typename K>
    static bool isInteger() {
        return IntegerHelper<K>::isInteger();
    }
};

}

TEST(TestTemplateMethodSpecialization, Basic) {
    EXPECT_TRUE(TestX<double>::isInteger<int>());
    EXPECT_FALSE(TestX<double>::isInteger<double>());
}
</code>```

Example 2

```enum class Side {
   BUY = 0,
   SELL
};

using PriceType = int64_t;

class BookHelper {

public:

BookHelper(
   PriceType insideBuyPrice,
   PriceType insideSellPrice)
:
   insideBuyPrice_{insideBuyPrice},
   insideSellPrice_{insideSellPrice}
{ }

template <Side SideV>
PriceType insidePrice() const;

template <Side SideV>
void insidePrice(PriceType price);

private:
   PriceType insideBuyPrice_;
   PriceType insideSellPrice_;

};

template <>
inline void BookHelper::insidePrice<Side::BUY>(PriceType price) {
   insideBuyPrice_ = price;
}

template <>
inline void BookHelper::insidePrice<Side::SELL>(PriceType price) {
   insideSellPrice_ = price;
}

template <>
inline PriceType BookHelper::insidePrice<Side::BUY>() const {
   return insideBuyPrice_;
}
                                                                                template <>
inline PriceType BookHelper::insidePrice<Side::SELL>() const {
   return insideSellPrice_;
}

template <typename BookT>
class Book {

public:
   Book();

   template <Side SideV>
   PriceType insidePrice() const;

   template <Side SideV>
   void insidePrice(PriceType price);

private:
   std::unique_ptr<BookHelper> helper_;

};

template<typename BookT>
Book<BookT>::Book() :
   helper_{new BookHelper{std::numeric_limits<PriceType>::min(), std::numeric_limits<PriceType>::max()}}
{}

template <typename BookT>
template <Side SideV>
PriceType Book<BookT>::insidePrice() const {
   return helper_->insidePrice<SideV>();
}

template <typename BookT>
template <Side SideV>
void Book<BookT>::insidePrice(PriceType price) {
   helper_->insidePrice<SideV>(price);
}

class TestBook { };

int main() {
   Book<TestBook> test;
   test.insidePrice<Side::SELL>(1230046);
   test.insidePrice<Side::BUY>(1230045);

   std::cout << " inside SELL price : " << test.insidePrice<Side::SELL>() << std::endl;
   std::cout << " inside BUY price : " << test.insidePrice<Side::BUY>() << std::endl;
}
```

Body:
I have a template class that has a template member function that needs to be specialized, as in:

template <typename T>
class X
{
public:
    template <typename U>
    void Y() {}

    template <>
    void Y<int>() {}
};

Altough VC handles this correctly, apperantly this isn't standard and GCC complains: explicit specialization in non-namespace scope 'class X<T>'

I tried:

template <typename T>
class X
{
public:
    template <typename U>
    void Y() {}
};

template <typename T>
// Also tried `template<>` here
void X<T>::Y<int>() {}

But this causes both VC and GCC to complain.

What's the right way to do this?

Body:
Use a Helper class to remove the class specialization

Example 1

namespace {
/* Make this work
template <typename T>
class X
{
public:
    template <typename U>
    void Y() {}

    template <>
    void Y<int>() {}
};
*/

template <typename  K>
struct IntegerHelper {
    static bool isInteger() { return false; }
};

template <>
inline bool IntegerHelper<int>::isInteger() {
    return true;
}

template <typename T>
class TestX {

public:
    template <typename K>
    static bool isInteger() {
        return IntegerHelper<K>::isInteger();
    }
};

}

TEST(TestTemplateMethodSpecialization, Basic) {
    EXPECT_TRUE(TestX<double>::isInteger<int>());
    EXPECT_FALSE(TestX<double>::isInteger<double>());
}

Example 2

enum class Side {
   BUY = 0,
   SELL
};

using PriceType = int64_t;

class BookHelper {

public:

BookHelper(
   PriceType insideBuyPrice,
   PriceType insideSellPrice)
:
   insideBuyPrice_{insideBuyPrice},
   insideSellPrice_{insideSellPrice}
{ }

template <Side SideV>
PriceType insidePrice() const;

template <Side SideV>
void insidePrice(PriceType price);

private:
   PriceType insideBuyPrice_;
   PriceType insideSellPrice_;

};

template <>
inline void BookHelper::insidePrice<Side::BUY>(PriceType price) {
   insideBuyPrice_ = price;
}

template <>
inline void BookHelper::insidePrice<Side::SELL>(PriceType price) {
   insideSellPrice_ = price;
}

template <>
inline PriceType BookHelper::insidePrice<Side::BUY>() const {
   return insideBuyPrice_;
}
                                                                                template <>
inline PriceType BookHelper::insidePrice<Side::SELL>() const {
   return insideSellPrice_;
}

template <typename BookT>
class Book {

public:
   Book();

   template <Side SideV>
   PriceType insidePrice() const;

   template <Side SideV>
   void insidePrice(PriceType price);

private:
   std::unique_ptr<BookHelper> helper_;

};

template<typename BookT>
Book<BookT>::Book() :
   helper_{new BookHelper{std::numeric_limits<PriceType>::min(), std::numeric_limits<PriceType>::max()}}
{}

template <typename BookT>
template <Side SideV>
PriceType Book<BookT>::insidePrice() const {
   return helper_->insidePrice<SideV>();
}

template <typename BookT>
template <Side SideV>
void Book<BookT>::insidePrice(PriceType price) {
   helper_->insidePrice<SideV>(price);
}

class TestBook { };

int main() {
   Book<TestBook> test;
   test.insidePrice<Side::SELL>(1230046);
   test.insidePrice<Side::BUY>(1230045);

   std::cout << " inside SELL price : " << test.insidePrice<Side::SELL>() << std::endl;
   std::cout << " inside BUY price : " << test.insidePrice<Side::BUY>() << std::endl;
}


问:
What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?
Can anybody give a clear explanation of how variable assignment really works in Makefiles.

What is the difference between :

```<code> VARIABLE = value
 VARIABLE ?= value
 VARIABLE := value
 VARIABLE += value
</code>```

I have read the section in GNU Make's manual, but it still doesn't make sense to me.

答:
Lazy Set

```<code>VARIABLE = value
</code>```

Normal setting of a variable, but any other variables mentioned with the value field are recursively expanded with their value at the point at which the variable is used, not the one it had when it was declared

Immediate Set

```<code>VARIABLE := value
</code>```

Setting of a variable with simple expansion of the values inside - values within it are expanded at declaration time.

Lazy Set If Absent

```<code>VARIABLE ?= value
</code>```

Setting of a variable only if it doesn't have a value. value is always evaluated when VARIABLE is accessed. It is equivalent to

```<code>ifeq ($(origin VARIABLE), undefined)
  VARIABLE = value
endif
</code>```

See the documentation for more details.

Append

```<code>VARIABLE += value
</code>```

Appending the supplied value to the existing value (or setting to that value if the variable didn't exist)

OwnerDisplayName: mmoris

Body:
Can anybody give a clear explanation of how variable assignment really works in Makefiles.

What is the difference between :

 VARIABLE = value
 VARIABLE ?= value
 VARIABLE := value
 VARIABLE += value

I have read the section in GNU Make's manual, but it still doesn't make sense to me.

Body:
Lazy Set

VARIABLE = value

Normal setting of a variable, but any other variables mentioned with the value field are recursively expanded with their value at the point at which the variable is used, not the one it had when it was declared

Immediate Set

VARIABLE := value

Setting of a variable with simple expansion of the values inside - values within it are expanded at declaration time.

Lazy Set If Absent

VARIABLE ?= value

Setting of a variable only if it doesn't have a value. value is always evaluated when VARIABLE is accessed. It is equivalent to

ifeq ($(origin VARIABLE), undefined)
  VARIABLE = value
endif

See the documentation for more details.

Append

VARIABLE += value

Appending the supplied value to the existing value (or setting to that value if the variable didn't exist)

OwnerDisplayName: Alnitak


问:
How can an array value be SIX chars long and echoing nothing (string(6) " ")?
This is really weird. Look what is on my screen right now :

```<code>$albumGenre : array(6) {
  [0]=>
  string(5) "Noise"
  [1]=>
  string(6) " "
  [2]=>
  string(5) "Blues"
  [3]=>
  string(5) "Blues"
  [4]=>
  string(5) "Blues"
  [5]=>
  string(5) "Blues"
}
</code>```

This is just the output of :

```<code>var_dump($albumGenre);
</code>```

Can you see where it says [1]=>  string(6) " " ??? How can it be that an array value is SIX chars long, but is only seen as " " ?

I know what this value is. It's an "Unknown" mp3 tag. Fine, it's unknow, I just want to get rid of it then. But I can't test for it, if PHP can't reliably tell me what the hell this array value really IS to HIM, see ?

I guess my question really is : How can I really know what's inside an array ? Is'nt var_dump($array) the correct way to know everything about $array ?

答:
var_dump can only print the printable characters it sees. If you really want to know what's in the variable, it might be an idea to install something like xdebug.

As a low-fi technique, you could of course attempt to print the individual characters, although this might go awry if the string is in unicode, etc.

Body:
This is really weird. Look what is on my screen right now :

$albumGenre : array(6) {
  [0]=>
  string(5) "Noise"
  [1]=>
  string(6) " "
  [2]=>
  string(5) "Blues"
  [3]=>
  string(5) "Blues"
  [4]=>
  string(5) "Blues"
  [5]=>
  string(5) "Blues"
}

This is just the output of :

var_dump($albumGenre);

Can you see where it says [1]=>  string(6) " " ??? How can it be that an array value is SIX chars long, but is only seen as " " ?

I know what this value is. It's an "Unknown" mp3 tag. Fine, it's unknow, I just want to get rid of it then. But I can't test for it, if PHP can't reliably tell me what the hell this array value really IS to HIM, see ?

I guess my question really is : How can I really know what's inside an array ? Is'nt var_dump($array) the correct way to know everything about $array ?


问:
MQ TLS communication with Weblogic using foreign JMS
I am trying to connect to MQ from weblogic 12c server using foreign JMS( using .bindings file). But not able to figure out where to configure cipher suite in Weblogic for SSL/TLS communication. I know how to do it in java code. But have no clue how to specify it in Weblogic resources.

Any help will be highly appreciated.

答: You put the MQ SSL/TLS information in the bindings file.</p>


问:
Cheapest way to keep an accurate count of something on AWS, fault tolerant, accurately and without an RDS Instance
I am reasonably familiar with AWS, I use a stack of ASP.NET MVC and MySQL, as well as Redis for caching/messaging.

Normally to keep a count of something, I would use a MySQL table to keep a count of something, for an action on my website.  I can easily execute the following from within my code:

```<code>UPDATE mycounts SET mycount = mycount + 1 WHERE id = @countId
</code>```

I can guarantee that this is executed ATOMIC-ally, so I can pretty much guarantee that if the table is up that the count will go up by exactly one for each call.

My problem with this implementation is that:

It requires a database instance, this is expensive

It requires the database to be up at all times, any down time and I'm going to lose counts

What is the cheapest way to keep a count of something on the AWS platform, without having to have an RDS database?  That is both fault tolerant and accurate...

答: You could provision an absolute minimum throughput dynamoDB table and use atomic counters there. It'll be dirt cheap.

Body:
I am reasonably familiar with AWS, I use a stack of ASP.NET MVC and MySQL, as well as Redis for caching/messaging.

Normally to keep a count of something, I would use a MySQL table to keep a count of something, for an action on my website.  I can easily execute the following from within my code:

UPDATE mycounts SET mycount = mycount + 1 WHERE id = @countId

I can guarantee that this is executed ATOMIC-ally, so I can pretty much guarantee that if the table is up that the count will go up by exactly one for each call.

My problem with this implementation is that:

It requires a database instance, this is expensive

It requires the database to be up at all times, any down time and I'm going to lose counts

What is the cheapest way to keep a count of something on the AWS platform, without having to have an RDS database?  That is both fault tolerant and accurate...


问:
Can Adobe AIR app communicate with iPhone calendar
Hey all,
I'm mighty new to Adobe AIR and Flex, Flash etc

I've been looking through the Adobe AIR APIs, and could not find a class that will allow a Flex\Flash app to communicate to the calendar,
(more specifically, the iPhone calendar via the iPhone packager)

am i missing out something here?
or has adobe not implemented an API for the Flex apps to communicate to the calendar?

Are there other iPhone specific APIs that Adobe has not implemented?

Thanks!

答:
i've found the answer right here:
http://labs.adobe.com/wiki/index.php/Applications_for_iPhone:Developer_FAQ#Which_native_iOS_APIs_and_functionality_are_supported_when_using_Flash_tooling.3F

it also shads light on some of the discussions that had taken place in the comments here
for instance:

one can develop in Flex, and deploy using the iPhone Packager, but Adobe discourage that at this point

exactly what APIs are exposed via AIR

Thanks all for your comments


问:
Step through code in AngularJS - controller
https://plnkr.co/edit/mBiv4r3JoHxKtDtRR2qM?p=preview

```<code>var myApp=angular.module('my',[]);
</code>```

Above is the code. Can someone please explain the flow of the statements such that why in the console line 12 gets executed before line 6 in script.js.

Thanks

答:
searchPeople isn't dependent on any Angular setup, so it runs pretty much right away. Your controller constructor depends on all manner of time-consuming angular setup (module instantiation, dependency injection, ...) and only fires once those tasks are complete.

The code you write only sets up that controller function. It's Angular behind the scenes that actually invokes it.

Body:
https://plnkr.co/edit/mBiv4r3JoHxKtDtRR2qM?p=preview

var myApp=angular.module('my',[]);

Above is the code. Can someone please explain the flow of the statements such that why in the console line 12 gets executed before line 6 in script.js.

Thanks


问:
DTD download/caching
I have the following directive on top of my master page

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
</code>```

As per the following article from W3C they are starting to block DTD download based on a per User Agent string pattern.

Which is the best way to cache the DTD locally or, better more, download it once and then reference a local copy?

I am using IIS 7.5.

答: You could use a proxy server like squid to serve it locally -- depending on what "locally" means for you.</p>

Title: DTD download/caching

Body:
I have the following directive on top of my master page

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

As per the following article from W3C they are starting to block DTD download based on a per User Agent string pattern.

Which is the best way to cache the DTD locally or, better more, download it once and then reference a local copy?

I am using IIS 7.5.


问:
Facebook oEmbed endpoint CORS Error
I am trying to make an XHR request to facebook's oembed but hitting a CORS error. Anybody knows if this is because Facebook doesn't allow CORS requests to the oembed endpoint? If that's the case why would it not be allowed? Is the endpoint supposed to be used outside the browser?

```<code>XMLHttpRequest cannot load https://apps.facebook.com/plugins/
post/oembed.json/?url=https://www.facebook.com/notes/mark-zuckerberg/
a-letter-to-our-daughter/10153375081581634.

No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8000' is therefore not allowed access.
</code>```

I am also hitting the same thing with other providers: YouTube, Twitter, Vine, Instagram. Some seems to allow it: Vimeo and Soundcloud.

答: Most of oEmbed providers does not allow cross origin resource sharing AFAIK. Hence to avoid this you can make a call to oEmbed end point from your server instead of making it from browser/ mobile client so that you can escape from CORS.

Title: Facebook oEmbed endpoint CORS Error

Body:
I am trying to make an XHR request to facebook's oembed but hitting a CORS error. Anybody knows if this is because Facebook doesn't allow CORS requests to the oembed endpoint? If that's the case why would it not be allowed? Is the endpoint supposed to be used outside the browser?

XMLHttpRequest cannot load https://apps.facebook.com/plugins/
post/oembed.json/?url=https://www.facebook.com/notes/mark-zuckerberg/
a-letter-to-our-daughter/10153375081581634.

No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8000' is therefore not allowed access.

I am also hitting the same thing with other providers: YouTube, Twitter, Vine, Instagram. Some seems to allow it: Vimeo and Soundcloud.


问:
"Uncaught TypeError: csv.replace is not a function" when using csv jquery plugin, how do I fix this?
In the following code:

```<code>  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", "file://csvFileName.csv", true);
  console.log(rawFile);
  var input = $.csv.toObjects(rawFile);
  console.log(input);
</code>```

I'm trying to convert a .csv file into a readable file, and then I'm trying to run a .toObjects command on it to produce a csv file that's easier to work with, but I keep running into an "Uncaught TypeError: csv.replace is not a function" error on the fourth line. I'm using the most upvoted answer to this question as a basis.

I've read through the documentation but I can't seem to find a particular answer to this error, does anyone know of a fix?

edit: this isn't my entire code, I have a script link to the jquery plugin in my html header. This is just the section where the error is. link looks like:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
</code>```

答:
You need to send the AJAX request, and call $.csv.toObjects() in the callback function. Its argument needs to be the string from the AJAX response.

```<code>var rawFile = new XMLHttpRequest();
rawFile.open("GET", "file://csvFileName.csv", true);
rawFile.onload = function() {
    var input = $.csv.toObjects(this.responseText);
    console.log(input);
};
</code>```

Body:
In the following code:

  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", "file://csvFileName.csv", true);
  console.log(rawFile);
  var input = $.csv.toObjects(rawFile);
  console.log(input);

I'm trying to convert a .csv file into a readable file, and then I'm trying to run a .toObjects command on it to produce a csv file that's easier to work with, but I keep running into an "Uncaught TypeError: csv.replace is not a function" error on the fourth line. I'm using the most upvoted answer to this question as a basis.

I've read through the documentation but I can't seem to find a particular answer to this error, does anyone know of a fix?

edit: this isn't my entire code, I have a script link to the jquery plugin in my html header. This is just the section where the error is. link looks like:

Body:
You need to send the AJAX request, and call $.csv.toObjects() in the callback function. Its argument needs to be the string from the AJAX response.

var rawFile = new XMLHttpRequest();
rawFile.open("GET", "file://csvFileName.csv", true);
rawFile.onload = function() {
    var input = $.csv.toObjects(this.responseText);
    console.log(input);
};


问:
how can i parse a url json code to delete items an a listview
i need some help  please... In my popup menu i have a delete option to delete items in a listview

how can i parse this url json to delete the items in the listview

this is the result of my  list view

```<code>    @Override
    protected void onPostExecute(String result) {
        if (pDialog.isShowing())
            pDialog.dismiss();
        super.onPostExecute(result);

        codigo.setText(recode);
        nombre.setText(reNombre);
        nroComprobante.setText(reNumero);

        final ListAdapter adapter = new SimpleAdapter(Compra.this, prod,
                R.layout.item_carrito, new String[]{"renglon", "codigo", "descrip", "precio"},
                new int[]{R.id.tvreglon, R.id.tvcode, R.id.tvdescrip, R.id.tvprec});
        lista_eligida.setAdapter(adapter);
        Log.d("ADAP", String.valueOf(adapter));
        registerForContextMenu(lista_eligida);

    }

}
</code>```

and this is my popup menu code...

```<code>  public boolean onContextItemSelected(final MenuItem item) {

    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    int id = info.position;
    switch (item.getItemId()) {
        case R.id.del:
            String url = "http://www.air-intra.com/apps/air-app/agregar.php?token=" + Token_Recibido + "&codiart=" + codigo + "&oper=Q&renglon=" + reglo + "";
</code>```

// what can i do??... should i parse the new json again.?..
//i just want to delete a item when i clicked on delete option on my popup menu thank you

答:
Replace your API call code given above with this:

```<code>new AsyncTask<Void, Void, String>()
    {
        ProgressDialog progressDialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setCancelable(true);
            progressDialog.show();
        }

        @Override
        protected String doInBackground(Void... params)
        {

             String url = "http://www.air-intra.com/apps/air-app/agregar.php?token=" + Token_Recibido + "&codiart=" + codigo + "&oper=Q&renglon=" + reglo + "";
        HttpHandler she = new HttpHandler();
        String jsonStr = she.makeServiceCall(url);

        try {
            JSONObject    jsonObj = new JSONObject(jsonStr);
            JSONArray contacts = jsonObj.getJSONArray("PRR");

           prop.clear(); \\Add this line in your code here.

            for (int i = 0; i < contacts.length(); i++) {
                JSONObject c = contacts.getJSONObject(i);

                String codig = c.getString("codigo");
                String des = c.getString("descrip");
                String prec = c.getString("precio");
                String reglon = c.getString("renglon");

                Log.d("REGLON", String.valueOf(reglon));

                HashMap<String, String> contacto = new HashMap<>();
                contacto.put("codigo", codig);
                contacto.put("descrip", des);
                contacto.put("precio", prec);
                contacto.put("renglon", reglon);
                reg = "" + reglon;
                prod.add(contacto);

            if(jsonStr != null) {
                System.out.println("success");
            } else {
                System.out.println("failed");
            }

            return jsonStr;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            progressDialog.dismiss();

            System.out.println("result=="+result);
        }
    }.execute();
</code>```

The issue I guess is that you are trying to make the API call on Main Thread that is not allowed. So I have put it in background. I have just put your given code in my code. Your code doesn't seem complete. SO complete your code before executing.

Body:
i need some help  please... In my popup menu i have a delete option to delete items in a listview

how can i parse this url json to delete the items in the listview

this is the result of my  list view

    @Override
    protected void onPostExecute(String result) {
        if (pDialog.isShowing())
            pDialog.dismiss();
        super.onPostExecute(result);

        codigo.setText(recode);
        nombre.setText(reNombre);
        nroComprobante.setText(reNumero);

        final ListAdapter adapter = new SimpleAdapter(Compra.this, prod,
                R.layout.item_carrito, new String[]{"renglon", "codigo", "descrip", "precio"},
                new int[]{R.id.tvreglon, R.id.tvcode, R.id.tvdescrip, R.id.tvprec});
        lista_eligida.setAdapter(adapter);
        Log.d("ADAP", String.valueOf(adapter));
        registerForContextMenu(lista_eligida);

    }

}

and this is my popup menu code...

  public boolean onContextItemSelected(final MenuItem item) {

    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    int id = info.position;
    switch (item.getItemId()) {
        case R.id.del:
            String url = "http://www.air-intra.com/apps/air-app/agregar.php?token=" + Token_Recibido + "&codiart=" + codigo + "&oper=Q&renglon=" + reglo + "";

// what can i do??... should i parse the new json again.?..
//i just want to delete a item when i clicked on delete option on my popup menu thank you

Body:
Replace your API call code given above with this:

new AsyncTask<Void, Void, String>()
    {
        ProgressDialog progressDialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setCancelable(true);
            progressDialog.show();
        }

        @Override
        protected String doInBackground(Void... params)
        {

             String url = "http://www.air-intra.com/apps/air-app/agregar.php?token=" + Token_Recibido + "&codiart=" + codigo + "&oper=Q&renglon=" + reglo + "";
        HttpHandler she = new HttpHandler();
        String jsonStr = she.makeServiceCall(url);

        try {
            JSONObject    jsonObj = new JSONObject(jsonStr);
            JSONArray contacts = jsonObj.getJSONArray("PRR");

           prop.clear(); \\Add this line in your code here.

            for (int i = 0; i < contacts.length(); i++) {
                JSONObject c = contacts.getJSONObject(i);

                String codig = c.getString("codigo");
                String des = c.getString("descrip");
                String prec = c.getString("precio");
                String reglon = c.getString("renglon");

                Log.d("REGLON", String.valueOf(reglon));

                HashMap<String, String> contacto = new HashMap<>();
                contacto.put("codigo", codig);
                contacto.put("descrip", des);
                contacto.put("precio", prec);
                contacto.put("renglon", reglon);
                reg = "" + reglon;
                prod.add(contacto);

            if(jsonStr != null) {
                System.out.println("success");
            } else {
                System.out.println("failed");
            }

            return jsonStr;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            progressDialog.dismiss();

            System.out.println("result=="+result);
        }
    }.execute();

The issue I guess is that you are trying to make the API call on Main Thread that is not allowed. So I have put it in background. I have just put your given code in my code. Your code doesn't seem complete. SO complete your code before executing.


问:
sql syntax error when loading mysqldump file
I am receiving a syntax error when I try to load a mysqldump file.

My question has a couple parts:

(1) Why is mysql unable to properly read the file that mysqldump output?

(2) How can I make mysql read in the relevant data from a file?

Heres some details:

mysqldump -u username -p dbname > mydumpfile.sql goes fine (apparently)

mysql -u testuser -p testdbname < mydumpfile.sql gets through only part (about 1/3) of the file, then gives a syntax  error:

ERROR 1064 (42000) at line 249: You have an error in your SQL syntax;
  check the manual that corresponds to your MySQL server version for the
  right syntax to use near
  'randomimproperlydisplayingjapanesetext',''),(508715,134707' at line 1

The text shown as the syntax error is shortly after the beginning of a new insert statement.

The (big) insert statement statement on the previous line is not being entered into the database.

The data is from a database with Japanese text, and the column has utf8_general_ci collation.

MySQL Version 5.6.23 on windows xp.

Here are the other relevant variables (I think):

```<code>mysql> show variables like '%char%';
+--------------------------+------------------------------+
| Variable_name            | Value                        |
+--------------------------+------------------------------+
| character_set_client     | sjis                         |
| character_set_connection | sjis                         |
| character_set_database   | sjis                         |
| character_set_filesystem | binary                       |
| character_set_results    | sjis                         |
| character_set_server     | sjis                         |
| character_set_system     | utf8                         |
| character_sets_dir       | C:\mysql\share\charsets\     |
+--------------------------+------------------------------+
</code>```

Edit Based on the answer below, I determined that there was a SET NAMES line in the mysqldump for setting it as utf8.

Here is the SHOW CREATE TABLE trouble_table RESULTS:

```<code>CREATE TABLE `trouble_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `version_id` int(11) DEFAULT NULL,
  `myutf8column` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
  `mysjisenumcolumn` enum('一式','＊',[a few other japanese charactes]) CHARACTER SET sjis DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `version_id` (`version_id`)
) ENGINE=InnoDB AUTO_INCREMENT=946033 DEFAULT CHARSET=utf16 `
</code>```

So, table character set utf16 (I forgot why), one utf8 column, and one sjis column.
In the msyqldump file I can read all values though so it seems that in the dump file all are encoded the same way.

SELECT HEX(mytuf8column) seems to confirm that myutf8column has utf8 encoding (starts with the codes mentioned below, i.e. E383xx,Ewxxyy), and mysjiscolumn has  hex values starting with 95 so I guess its probably sjis.

Also, after reading this SOV question, I checked and set the max_allowed_packet to be 33554432, instead of the default, but this did not change the problem.

The part of the table that does load has no noticeable problems with the inserted data, but theres too much data for me to really look through either the db data or the mysqldump file and notice any 'weird' characters that may be causing to mysql to get choked up.  (The mysqldump file is over 50MB, so its not enormous by db standards but big enough to be very troublesome to read, Notepad++ and emacs seem helpless with it)

One more thing, Im nervous about changing the column collation because I dont want to lose any data (if the current encoding is wrong, is it safe to change it to another encoding?). It took a long time to parse in the original data, hence I am trying to make a backup copy. Edit Based on answer below, I am no longer nervous about changing collation because it is only a rule for comparsion, rather I am nervous about changing the character sets.

By the way it is not a big deal if mysql needs to simply skip a few problematic rows.

答: In my case it was caused by a version difference between the exporting and importing mysql versions. My exporting mysql was 5.7.x (Ubuntu 16.04), but the importing was 5.5.x (Ubuntu 14.04). After upgrading the importing to 5.7.x by following this guide, it worked.</p>

Body:
I am receiving a syntax error when I try to load a mysqldump file.

My question has a couple parts:

(1) Why is mysql unable to properly read the file that mysqldump output?

(2) How can I make mysql read in the relevant data from a file?

Heres some details:

mysqldump -u username -p dbname > mydumpfile.sql goes fine (apparently)

mysql -u testuser -p testdbname < mydumpfile.sql gets through only part (about 1/3) of the file, then gives a syntax  error:

ERROR 1064 (42000) at line 249: You have an error in your SQL syntax;
  check the manual that corresponds to your MySQL server version for the
  right syntax to use near
  'randomimproperlydisplayingjapanesetext',''),(508715,134707' at line 1

The text shown as the syntax error is shortly after the beginning of a new insert statement.

The (big) insert statement statement on the previous line is not being entered into the database.

The data is from a database with Japanese text, and the column has utf8_general_ci collation.

MySQL Version 5.6.23 on windows xp.

Here are the other relevant variables (I think):

mysql> show variables like '%char%';
+--------------------------+------------------------------+
| Variable_name            | Value                        |
+--------------------------+------------------------------+
| character_set_client     | sjis                         |
| character_set_connection | sjis                         |
| character_set_database   | sjis                         |
| character_set_filesystem | binary                       |
| character_set_results    | sjis                         |
| character_set_server     | sjis                         |
| character_set_system     | utf8                         |
| character_sets_dir       | C:\mysql\share\charsets\     |
+--------------------------+------------------------------+

Edit Based on the answer below, I determined that there was a SET NAMES line in the mysqldump for setting it as utf8.

Here is the SHOW CREATE TABLE trouble_table RESULTS:

CREATE TABLE `trouble_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `version_id` int(11) DEFAULT NULL,
  `myutf8column` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
  `mysjisenumcolumn` enum('一式','＊',[a few other japanese charactes]) CHARACTER SET sjis DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `version_id` (`version_id`)
) ENGINE=InnoDB AUTO_INCREMENT=946033 DEFAULT CHARSET=utf16 `

So, table character set utf16 (I forgot why), one utf8 column, and one sjis column.
In the msyqldump file I can read all values though so it seems that in the dump file all are encoded the same way.

SELECT HEX(mytuf8column) seems to confirm that myutf8column has utf8 encoding (starts with the codes mentioned below, i.e. E383xx,Ewxxyy), and mysjiscolumn has  hex values starting with 95 so I guess its probably sjis.

Also, after reading this SOV question, I checked and set the max_allowed_packet to be 33554432, instead of the default, but this did not change the problem.

The part of the table that does load has no noticeable problems with the inserted data, but theres too much data for me to really look through either the db data or the mysqldump file and notice any 'weird' characters that may be causing to mysql to get choked up.  (The mysqldump file is over 50MB, so its not enormous by db standards but big enough to be very troublesome to read, Notepad++ and emacs seem helpless with it)

One more thing, Im nervous about changing the column collation because I dont want to lose any data (if the current encoding is wrong, is it safe to change it to another encoding?). It took a long time to parse in the original data, hence I am trying to make a backup copy. Edit Based on answer below, I am no longer nervous about changing collation because it is only a rule for comparsion, rather I am nervous about changing the character sets.

By the way it is not a big deal if mysql needs to simply skip a few problematic rows.


问:
SQL - Crossing 'Crossed' Tables
The title is not good, but it is the way I've found to differentiate my issue from a simple table crossing since my previous researches always get me to these kind of topics.

I have several tables - for simplification, let's name them in only 3: A, B, C. I want to crossing them all in a single table, beeing A the main table.

However, the header in Table B is correlated also with keys in Table C. That is how it looks like my tables:

```<code>Table A
KEY.1      KEY.2       A.HEADER
A          NULL         X
B          NULL         X
NULL       AA           X
NULL       BB           X
C          NULL         X
A          NULL         X
NULL       AA           X

Table B
KEY.1      B.HEADER
A          1
B          2
C          3
D          4
E          5
F          6

Table C
KEY.2       KEY.1
AA          D
BB          E
CC          F
</code>```

I want:

```<code>Final Table
    KEY.1     KEY.2      B.HEADER  A.HEADER
    A         NULL       1         X
    B         NULL       2         X
    D         AA         4         X
    E         BB         5         X
    C         NULL       3         X
</code>```

Can someone help me?

答:
I finnaly was able to find a solution for my problem with the help provided here. The query should be:</p>

```<code>SELECT DISTINCT
    coalesce(A.KEY1, C.KEY1) as KEY1,
    A.KEY2,
    B.HEADER,
    A.HEADER
FROM A
    LEFT JOIN C ON (A.KEY2 = C.KEY2)
    LEFT JOIN B ON (coalesce(A.KEY1, C.KEY1) = B.KEY1)
</code>```

Title: SQL - Crossing 'Crossed' Tables

Body:
The title is not good, but it is the way I've found to differentiate my issue from a simple table crossing since my previous researches always get me to these kind of topics.

I have several tables - for simplification, let's name them in only 3: A, B, C. I want to crossing them all in a single table, beeing A the main table.

However, the header in Table B is correlated also with keys in Table C. That is how it looks like my tables:

Table A
KEY.1      KEY.2       A.HEADER
A          NULL         X
B          NULL         X
NULL       AA           X
NULL       BB           X
C          NULL         X
A          NULL         X
NULL       AA           X

Table B
KEY.1      B.HEADER
A          1
B          2
C          3
D          4
E          5
F          6

Table C
KEY.2       KEY.1
AA          D
BB          E
CC          F

I want:

Final Table
    KEY.1     KEY.2      B.HEADER  A.HEADER
    A         NULL       1         X
    B         NULL       2         X
    D         AA         4         X
    E         BB         5         X
    C         NULL       3         X

Can someone help me?

Body:
I finnaly was able to find a solution for my problem with the help provided here. The query should be:

SELECT DISTINCT
    coalesce(A.KEY1, C.KEY1) as KEY1,
    A.KEY2,
    B.HEADER,
    A.HEADER
FROM A
    LEFT JOIN C ON (A.KEY2 = C.KEY2)
    LEFT JOIN B ON (coalesce(A.KEY1, C.KEY1) = B.KEY1)


问:
Problem with LaTeX hyperref
i have an url with cyrilic characters:

```<code>http://www.pravoslavie.bg/Възпитание/Духовно-и-светско-образование
</code>```

when i compile the document, i get following as url:

```<code>http://www.pravoslavie.bg/%5CT2A%5CCYRV%20%5CT2A%5Ccyrhrdsn%20%5CT2A%5Ccyrz%20%5CT2A%5Ccyrp%20%5CT2A%5Ccyri%20%5CT2A%5Ccyrt%20%5CT2A%5Ccyra%20%5CT2A%5Ccyrn%20%5CT2A%5Ccyri%20%5CT2A%5Ccyre%20/%5CT2A%5CCYRD%20%5CT2A%5Ccyru%20%5CT2A%5Ccyrh%20%5CT2A%5Ccyro%20%5CT2A%5Ccyrv%20%5CT2A%5Ccyrn%20%5CT2A%5Ccyro%20-%5CT2A%5Ccyri%20-%5CT2A%5Ccyrs%20%5CT2A%5Ccyrv%20%5CT2A%5Ccyre%20%5CT2A%5Ccyrt%20%5CT2A%5Ccyrs%20%5CT2A%5Ccyrk%20%5CT2A%5Ccyro%20-%5CT2A%5Ccyro%20%5CT2A%5Ccyrb%20%5CT2A%5Ccyrr%20%5CT2A%5Ccyra%20%5CT2A%5Ccyrz%20%5CT2A%5Ccyro%20%5CT2A%5Ccyrv%20%5CT2A%5Ccyra%20%5CT2A%5Ccyrn%20%5CT2A%5Ccyri%20%5CT2A%5Ccyre
</code>```

and that ist not the same. Can I set the encoding to utf8 for hyperref? Or how can i solve the problem?

答:
I had a similar problem with the pdftitle field.

splitting use declaration and setup made it work correctly

```<code>\usepackage{hyperref}
\hypersetup{
pdftitle=Priorità
}
</code>```

Title: Problem with LaTeX hyperref

Body:
i have an url with cyrilic characters:

http://www.pravoslavie.bg/Възпитание/Духовно-и-светско-образование

when i compile the document, i get following as url:

http://www.pravoslavie.bg/%5CT2A%5CCYRV%20%5CT2A%5Ccyrhrdsn%20%5CT2A%5Ccyrz%20%5CT2A%5Ccyrp%20%5CT2A%5Ccyri%20%5CT2A%5Ccyrt%20%5CT2A%5Ccyra%20%5CT2A%5Ccyrn%20%5CT2A%5Ccyri%20%5CT2A%5Ccyre%20/%5CT2A%5CCYRD%20%5CT2A%5Ccyru%20%5CT2A%5Ccyrh%20%5CT2A%5Ccyro%20%5CT2A%5Ccyrv%20%5CT2A%5Ccyrn%20%5CT2A%5Ccyro%20-%5CT2A%5Ccyri%20-%5CT2A%5Ccyrs%20%5CT2A%5Ccyrv%20%5CT2A%5Ccyre%20%5CT2A%5Ccyrt%20%5CT2A%5Ccyrs%20%5CT2A%5Ccyrk%20%5CT2A%5Ccyro%20-%5CT2A%5Ccyro%20%5CT2A%5Ccyrb%20%5CT2A%5Ccyrr%20%5CT2A%5Ccyra%20%5CT2A%5Ccyrz%20%5CT2A%5Ccyro%20%5CT2A%5Ccyrv%20%5CT2A%5Ccyra%20%5CT2A%5Ccyrn%20%5CT2A%5Ccyri%20%5CT2A%5Ccyre

and that ist not the same. Can I set the encoding to utf8 for hyperref? Or how can i solve the problem?

Body:
I had a similar problem with the pdftitle field.

splitting use declaration and setup made it work correctly

\usepackage{hyperref}
\hypersetup{
pdftitle=Priorità
}


问:
Using MySQL with group_concat variables to create a new row
I'd like to select some values from a MySQL table like below. I want to concat the tactical and ID variables only when the koords values match. The output of the query should have all rows in the table, replacing the duplicates with just one row.
In short I want to combine two rows into one if the two match on there latitude and longitude values. And concatenate several of the values into columns.
Is this possible?

Original table columns are: ID, netID, tactical, Name, latitude, longitude.

```<code>SELECT ID, tactical
            ,CONCAT(latitude, ", ", longitude) as koords
            ,GROUP_CONCAT(tactical SEPARATOR '-')  as newtact
            ,GROUP_CONCAT(ID SEPARATOR '-') as newID
FROM `NetLog`
WHERE netID = 276
</code>```

The goal is to create a marker in Google Maps that contains the information for the duplicate records. The mapping part is done, I just need to combine duplicates at this point.

答:
I think you want group by:

```<code>SELECT CONCAT(latitude, ', ', longitude) as koords,
       GROUP_CONCAT(tactical SEPARATOR '-')  as newtact,
       GROUP_CONCAT(ID SEPARATOR '-') as newID
FROM `NetLog`
WHERE netID = 276
GROUP BY latitude, longitude;
</code>```

Why the designers of MySQL would let a query such as yours run with no error is beyond me.  It is not standard SQL, because you have unaggregated columns in the SELECT along with aggregation functions.

Body:
I'd like to select some values from a MySQL table like below. I want to concat the tactical and ID variables only when the koords values match. The output of the query should have all rows in the table, replacing the duplicates with just one row.
In short I want to combine two rows into one if the two match on there latitude and longitude values. And concatenate several of the values into columns.
Is this possible?

Original table columns are: ID, netID, tactical, Name, latitude, longitude.

SELECT ID, tactical
            ,CONCAT(latitude, ", ", longitude) as koords
            ,GROUP_CONCAT(tactical SEPARATOR '-')  as newtact
            ,GROUP_CONCAT(ID SEPARATOR '-') as newID
FROM `NetLog`
WHERE netID = 276

The goal is to create a marker in Google Maps that contains the information for the duplicate records. The mapping part is done, I just need to combine duplicates at this point.

Body:
I think you want group by:

SELECT CONCAT(latitude, ', ', longitude) as koords,
       GROUP_CONCAT(tactical SEPARATOR '-')  as newtact,
       GROUP_CONCAT(ID SEPARATOR '-') as newID
FROM `NetLog`
WHERE netID = 276
GROUP BY latitude, longitude;

Why the designers of MySQL would let a query such as yours run with no error is beyond me.  It is not standard SQL, because you have unaggregated columns in the SELECT along with aggregation functions.


问:
Get list of MySQL databases with python
I'm trying to get the names of all databases associated with my MySQL server via python (2.7), but am instead just getting the number of databases.

I looked around, and it seems like the only answer may be to use sys for a command line call, get the name of the databases, and proceed from there, but I can't believe that's the only way.

Current Code:

```<code>import MySQLdb

serv = MySQLdb.connect(host = "localhost", user = "root", passwd = "abcdefg")

c = serv.cursor()

print c.execute("SHOW DATABASES")
</code>```

Output:

```<code>4
</code>```

Thanks in advance for the help.

答:
I am not sure if mysql connector is same as your library, but using msyql connector your answer would be something like this:</p>

```<code>import mysql.connector
conn = mysql.connector.connect (user='user', password='password',
                               host='server_address',buffered=True)
cursor = conn.cursor()
databases = ("show databases")
cursor.execute(databases)
for (databases) in cursor:
     print databases[0]
</code>```

Title: Get list of MySQL databases with python

Body:
I'm trying to get the names of all databases associated with my MySQL server via python (2.7), but am instead just getting the number of databases.

I looked around, and it seems like the only answer may be to use sys for a command line call, get the name of the databases, and proceed from there, but I can't believe that's the only way.

Current Code:

import MySQLdb

serv = MySQLdb.connect(host = "localhost", user = "root", passwd = "abcdefg")

c = serv.cursor()

print c.execute("SHOW DATABASES")

Output:

4

Thanks in advance for the help.

Body:
I am not sure if mysql connector is same as your library, but using msyql connector your answer would be something like this:

import mysql.connector
conn = mysql.connector.connect (user='user', password='password',
                               host='server_address',buffered=True)
cursor = conn.cursor()
databases = ("show databases")
cursor.execute(databases)
for (databases) in cursor:
     print databases[0]


问:
Using second momentum as part of new cost function? (Tensorflow and/or keras)
I'm currently trying to take Adam's second order moment term, v_t, and use that as an additional term in my cost function. How can I implement something like this:

```<code>Cost = Cross Entropy + v_t*some_function(weights)
</code>```

Can this be accomplished within python? Or do I have to write my own C++ code to accomplish this? Also is this easily accomplished in a framework like Keras?
Here's the code for the cost function that I'm trying to add into keras:

```<code>def my_loss(y_pred, y_true, current_weights, v_t):
     normal_loss=K.categorial_cross_entropy(y_pred,y_true)
     additional_term=K.dot(K.square(current_weights - K.some_function(current_weights)), v_t)
     return normal_loss + additional_term
</code>```

答:
This would be problematic, regardless of what framework you did this with. Specifically, we have from the ADAM paper the relevant lines:

```<code>g_t = d Cost / d weights
v_t = beta2 * v_{t-1} + (1 - beta2) g_t^2
</code>```

Now, if you were to include v_t into Cost, this would be an implicit equation:

```<code>g_t = d Cross Entropy / d weights + d (v_t*some_function) / d weights
v_t = beta2 * v_{t-1} + (1 - beta2) g_t^2
</code>```

Notice how v_t appears in both equations. We can expand it as such for greater clarity

```<code>v_t = beta2 * v_{t-1} + (1 - beta2) [d Cross Entropy / d weights + d (v_t*some_function) / d weights]^2
</code>```

You could attempt to solve this exactly, but in doing so you would have to use some form of implicit solver, which will be very computationally costly. One way would be fixed point iteration.

Body:
I'm currently trying to take Adam's second order moment term, v_t, and use that as an additional term in my cost function. How can I implement something like this:

Cost = Cross Entropy + v_t*some_function(weights)

Can this be accomplished within python? Or do I have to write my own C++ code to accomplish this? Also is this easily accomplished in a framework like Keras?
Here's the code for the cost function that I'm trying to add into keras:

def my_loss(y_pred, y_true, current_weights, v_t):
     normal_loss=K.categorial_cross_entropy(y_pred,y_true)
     additional_term=K.dot(K.square(current_weights - K.some_function(current_weights)), v_t)
     return normal_loss + additional_term

Body:
This would be problematic, regardless of what framework you did this with. Specifically, we have from the ADAM paper the relevant lines:

g_t = d Cost / d weights
v_t = beta2 * v_{t-1} + (1 - beta2) g_t^2

Now, if you were to include v_t into Cost, this would be an implicit equation:

g_t = d Cross Entropy / d weights + d (v_t*some_function) / d weights
v_t = beta2 * v_{t-1} + (1 - beta2) g_t^2

Notice how v_t appears in both equations. We can expand it as such for greater clarity

v_t = beta2 * v_{t-1} + (1 - beta2) [d Cross Entropy / d weights + d (v_t*some_function) / d weights]^2

You could attempt to solve this exactly, but in doing so you would have to use some form of implicit solver, which will be very computationally costly. One way would be fixed point iteration.


问:
SQL: How to get the element from a delimited string by its index?
I have this function (credit: searchsqlserver):

```<code>CREATE FUNCTION dbo.fnSplit(
    @sInputList VARCHAR(8000)             -- List of delimited items
    , @sDelimiter VARCHAR(8000) = ','     -- delimiter that separates items
 ) RETURNS @List TABLE (item VARCHAR(8000))
     BEGIN
     DECLARE @sItem VARCHAR(8000)
     WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
         BEGIN
         SELECT
         @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,
            @sInputList,0)-1))),
         @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,
            @sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
         IF LEN(@sItem) > 0
            INSERT INTO @List SELECT @sItem
         END

     IF LEN(@sInputList)> 0
     INSERT INTO @List SELECT @sInputList -- Put the last item in
     RETURN
     END
 GO
</code>```

It takes as parameters a string and a delimiter and returns the delimited elements one by one.

```<code>select * from fnSplit('1,22,333', ',')    --   returns 1 22 333
</code>```

I'll confess that I`m new to SQL and I simply can't follow the whole logic behind this function. What I'm trying to achieve is a function that has a third parameter(an index) and returns the element on the position mention by the index. For example:

```<code>select * from fnSplit('1 22 333 444 5555 666', ' ' , 2 ) --  333

select * from fnSplit('1 22 333 444 5555 666', ' ' , 0 ) --  1
</code>```

答:
You could change your split string function to include a row number:</p>

```<code>    CREATE FUNCTION dbo.fnSplit2(
    @sInputList VARCHAR(8000)             -- List of delimited items
    , @sDelimiter VARCHAR(8000) = ','     -- delimiter that separates items
 ) RETURNS @List TABLE (item VARCHAR(8000))
     BEGIN
     DECLARE @sItem VARCHAR(8000),
             @RowNumber int

     set @RowNumber = 0

     WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
         BEGIN

             SELECT
             @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,
                @sInputList,0)-1))),
             @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,
                @sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
             IF LEN(@sItem) > 0
                INSERT INTO @List SELECT @sItem, @RowNumber

            set @RowNumber = @RowNumber + 1
         END

     set @RowNumber = @RowNumber + 1

     IF LEN(@sInputList)> 0
     INSERT INTO @List SELECT @sInputList, @RowNumber -- Put the last item in
     RETURN
     END
</code>```

Body:
I have this function (credit: searchsqlserver):

CREATE FUNCTION dbo.fnSplit(
    @sInputList VARCHAR(8000)             -- List of delimited items
    , @sDelimiter VARCHAR(8000) = ','     -- delimiter that separates items
 ) RETURNS @List TABLE (item VARCHAR(8000))
     BEGIN
     DECLARE @sItem VARCHAR(8000)
     WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
         BEGIN
         SELECT
         @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,
            @sInputList,0)-1))),
         @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,
            @sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
         IF LEN(@sItem) > 0
            INSERT INTO @List SELECT @sItem
         END

     IF LEN(@sInputList)> 0
     INSERT INTO @List SELECT @sInputList -- Put the last item in
     RETURN
     END
 GO

It takes as parameters a string and a delimiter and returns the delimited elements one by one.

select * from fnSplit('1,22,333', ',')    --   returns 1 22 333

I'll confess that I`m new to SQL and I simply can't follow the whole logic behind this function. What I'm trying to achieve is a function that has a third parameter(an index) and returns the element on the position mention by the index. For example:

select * from fnSplit('1 22 333 444 5555 666', ' ' , 2 ) --  333

select * from fnSplit('1 22 333 444 5555 666', ' ' , 0 ) --  1

Body:
You could change your split string function to include a row number:

    CREATE FUNCTION dbo.fnSplit2(
    @sInputList VARCHAR(8000)             -- List of delimited items
    , @sDelimiter VARCHAR(8000) = ','     -- delimiter that separates items
 ) RETURNS @List TABLE (item VARCHAR(8000))
     BEGIN
     DECLARE @sItem VARCHAR(8000),
             @RowNumber int

     set @RowNumber = 0

     WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
         BEGIN

             SELECT
             @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,
                @sInputList,0)-1))),
             @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,
                @sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
             IF LEN(@sItem) > 0
                INSERT INTO @List SELECT @sItem, @RowNumber

            set @RowNumber = @RowNumber + 1
         END

     set @RowNumber = @RowNumber + 1

     IF LEN(@sInputList)> 0
     INSERT INTO @List SELECT @sInputList, @RowNumber -- Put the last item in
     RETURN
     END