问:
Angular.js and Node.js get a GET instead of a POST
I want to do a POST but I still have a GET on the browser.I'm using node and angular.
This is my HTML with the form.

HTML

```<code><form ng-app="formApp" ng-controller="formCtrl">
  nome:<input type="text" ng-model="nome" name="nome"><br>
  cognome:<input type="text" name="cognome"><br>
  ragioneSociale:<input type="text" name="regioneSociale"><br>
  partitaIva:<input type="text" name="partitaIva"><br>
<input type="submit" value="Submit" ng-click="send()">
</form>
</code>```

angular

this is my angular function:

```<code><script>
var fmApp = angualr.module('formApp', []);
fmApp.controller('formCtrl',  function($scope){
  $scope.send = function($http){
    var data = $.params(){
      soggetto: JSON.stringify({
      nome: $scope.nome,
      cognome: $scope.cognome,
      regioneSociale: $scope.regioneSociale,
      partitaIva: $scope.partitaIva
      });
      console.log('ok');
      $http({
        method: "POST",
        url: "/ins/sogg",
        data:'data',
        dataType: 'json'
      }).then(function successCallback(response) {
          console.log("sent")
        }, function errorCallback(response) {
          // called asynchronously if an error occurs
          // or server returns response with an error status.
        });
      // $http.post('/inserimento/soggetto', data).success function(data, status) {
      //   console.log('status');

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

答:
> Solved in this way

HTML

```<code>    <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>inserimento Dati</title>
  </head>
  <body>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<h1>Inserimento</h1>
<h2>Soggetto</h2>

<form ng-app="formApp" ng-controller="formCtrl">
  nome:<input type="text" ng-model="nome"/><br>
  cognome:<input type="text" ng-model="cognome"/><br>
  ragioneSociale:<input type="text" ng-model="ragioneSociale"/><br>
  partitaIva:<input type="text" ng-model="partitaIva"/><br>
<input type="button" value="Submit" ng-click="send(nome, cognome, ragioneSociale, partitaIva)"/>
</code>```

Angular

```<code>    <script>
    var fmApp = angular.module('formApp', []);
    fmApp.controller('formCtrl',  function($scope, $http){
      $scope.nome,
      $scope.cognome,
      $scope.ragioneSociale,
      $scope.partitaIva,
      $scope.send = function(nome, cognome, ragioneSociale, partitaIva){
        var data = {
            "nome": nome,
            "cognome": cognome,
            "ragioneSociale": ragioneSociale,
            "partitaIva": partitaIva,
          }; // fine JSON
        var str = JSON.stringify(data);
        console.log(data);
        $http({
          method: "POST",
          url: "/ins/sogg",
          data: data,
        }).then(
            function successCallback(response){
              console.log("sent")},
            function errorCallback(response) {
               // called asynchronously if an error occurs
                // or server returns response with an error status.
              });
          // $http.post('/inserimento/soggetto', data).success function(data, status) {
          //   console.log('status');
        };
    });
</script>
</code>```

Server.js

```<code>    app.get('/inserimento', function(req, res){
  res.sendFile(__dirname + '/public/inserimento.html');
});

app.post('/ins/sogg', function(req, res){
  var sog = req.body; //arriva il dato
  app.use(bodyParser.json(sog));//dato in json ordinato
  console.log(sog);
  client.connect(function (err){
    if (err) throw err;
  });
  var query = client.query('INSERT INTO "Soggetto" (nome, cognome, "regSociale", "partIVA") VALUES($1, $2, $3, $4)', [sog.nome, sog.cognome, sog.ragioneSociale, sog.partitaIva], function(err, result){
    if(err){
      console.log("Errore");
      return onError(err);
    }
    res.writeHead(200, {'content-type': 'text/plain'});
    res.end('Insert ok');
  });
});
</code>```

Body:
I want to do a POST but I still have a GET on the browser.I'm using node and angular.
This is my HTML with the form.

HTML

<form ng-app="formApp" ng-controller="formCtrl">
  nome:<input type="text" ng-model="nome" name="nome">

  cognome:<input type="text" name="cognome">

  ragioneSociale:<input type="text" name="regioneSociale">

  partitaIva:<input type="text" name="partitaIva">

<input type="submit" value="Submit" ng-click="send()">
</form>

angular

this is my angular function:

Body:
> Solved in this way

HTML

    <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>inserimento Dati</title>
  </head>
  <body>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<h1>Inserimento</h1>
<h2>Soggetto</h2>

<form ng-app="formApp" ng-controller="formCtrl">
  nome:<input type="text" ng-model="nome"/><br>
  cognome:<input type="text" ng-model="cognome"/><br>
  ragioneSociale:<input type="text" ng-model="ragioneSociale"/><br>
  partitaIva:<input type="text" ng-model="partitaIva"/><br>
<input type="button" value="Submit" ng-click="send(nome, cognome, ragioneSociale, partitaIva)"/>

Angular

    <script>
    var fmApp = angular.module('formApp', []);
    fmApp.controller('formCtrl',  function($scope, $http){
      $scope.nome,
      $scope.cognome,
      $scope.ragioneSociale,
      $scope.partitaIva,
      $scope.send = function(nome, cognome, ragioneSociale, partitaIva){
        var data = {
            "nome": nome,
            "cognome": cognome,
            "ragioneSociale": ragioneSociale,
            "partitaIva": partitaIva,
          }; // fine JSON
        var str = JSON.stringify(data);
        console.log(data);
        $http({
          method: "POST",
          url: "/ins/sogg",
          data: data,
        }).then(
            function successCallback(response){
              console.log("sent")},
            function errorCallback(response) {
               // called asynchronously if an error occurs
                // or server returns response with an error status.
              });
          // $http.post('/inserimento/soggetto', data).success function(data, status) {
          //   console.log('status');
        };
    });
</script>

Server.js

    app.get('/inserimento', function(req, res){
  res.sendFile(__dirname + '/public/inserimento.html');
});

app.post('/ins/sogg', function(req, res){
  var sog = req.body; //arriva il dato
  app.use(bodyParser.json(sog));//dato in json ordinato
  console.log(sog);
  client.connect(function (err){
    if (err) throw err;
  });
  var query = client.query('INSERT INTO "Soggetto" (nome, cognome, "regSociale", "partIVA") VALUES($1, $2, $3, $4)', [sog.nome, sog.cognome, sog.ragioneSociale, sog.partitaIva], function(err, result){
    if(err){
      console.log("Errore");
      return onError(err);
    }
    res.writeHead(200, {'content-type': 'text/plain'});
    res.end('Insert ok');
  });
});


来源: stackexchange

问:
Show value of formula with Spreadsheet gem in Rails
I am trying to show an excel spreadsheet inside a RoR application. I started using the Spreadsheet gem, which works wonderfully. However, when I don't know how to show a cell which has a formula (I want to show the resulting value). There is a Spreadsheet::Formula class which has a value method that seems for that, but I don't know how to instantiate or use this class. Any help will be appreciated.</p>

答:
Silly me. Just use the value method on the cell :-)</p>

```<code>sheet = book.worksheet 0
sheet[1,2].value
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Silly me. Just use the value method on the cell :-)

sheet = book.worksheet 0
sheet[1,2].value


问:
Get the solution for analyzer
I'm creating na analyzer for Visual Studio, and I need the Solution property required by SymbolFinder.FindSourceDefinitionAsync(ISymbol, Solution) to ensure that I'm really operating over the type I want.

```<code>public static async Task<ITypeSymbol> GetBaseScenario(ITypeSymbol type)
    {
        if (type == null)
            return null;

        var origType = await SymbolFinder.FindSourceDefinitionAsync(type, _solution);
        if (BaseScnSymbols.Contains(origType) || BaseVersionScnSymbols.Contains(origType))
            return origType as ITypeSymbol;

        return null;
    }
</code>```

I can get the Semantic Model, the compilation, but I can't get the solution.
How can I get the solution? Is there a better approach for this problem?

答: As far as I know the only way to get a solution symbol is to load it via its physical path with MSBuildWorkspace.OpenSolutionAsync.</p>

ContentLicense: CC BY-SA 3.0

Title: Get the solution for analyzer

Body:
I'm creating na analyzer for Visual Studio, and I need the Solution property required by SymbolFinder.FindSourceDefinitionAsync(ISymbol, Solution) to ensure that I'm really operating over the type I want.

public static async Task<ITypeSymbol> GetBaseScenario(ITypeSymbol type)
    {
        if (type == null)
            return null;

        var origType = await SymbolFinder.FindSourceDefinitionAsync(type, _solution);
        if (BaseScnSymbols.Contains(origType) || BaseVersionScnSymbols.Contains(origType))
            return origType as ITypeSymbol;

        return null;
    }

I can get the Semantic Model, the compilation, but I can't get the solution.
How can I get the solution? Is there a better approach for this problem?


问:
Google tag manager error sumome iframe
This code is Google tag manager in my site:

```<code><!-- Google Tag Manager (GTM) -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-xxx"
                  height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
        new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
        j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
        '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,'script','dataLayer','GTM-xxx');</script>
<!-- End Google Tag Manager (GTM) -->
</code>```

I get this notice at the bottom on frontend:
More than one instance of Sumo is attempting to start on this page. Please check that you are only loading Sumo once per page.

I checked and I can see it has two

```<code><iframe id="sumome-jquery-iframe" style="display: none;"></iframe>
</code>```

Why do I get this error? Thanks very much for any help.

答:
This is not per se a problem with GTM. The problem is, as stated in your error message, that your are starting more than one instance of SumoMe.

If this started after you installed GTM this probably because you have configured Sumo via GTM and accidentally fire the tag more than once per page. Check your tags and triggers, or set the Sumo tag to "fire only once per page" in the advanced tag settings.

Title: Google tag manager error sumome iframe

Body:
This code is Google tag manager in my site:

I get this notice at the bottom on frontend:
More than one instance of Sumo is attempting to start on this page. Please check that you are only loading Sumo once per page.

I checked and I can see it has two

Why do I get this error? Thanks very much for any help.


问:
Type inference in TS is too basic, or isn't it?
Here is the code:

```<code>var a; // it is typed "any".
a = 33; // No inference
a = true; // compiles without errors.
</code>```

It won't infer the type by first usage.

In Haxe:

```<code>var a; // it is now an "Unknown" kinda type, "monomorph"
a = 33; // Here it became int
a = true; // compiler error, unable to set int to bool.
</code>```

Am I doing anything wrong? Is it possible to do it in TypeScript?

As far as I see, it's not possible. So this question could be a great warning for all OCaml or Haxe developers: you should initialize your variable immediately in TS.

答:
Am I doing anything wrong?

Types in TypeScript are inferred when a variable is declared, not afterward. What you're doing wrong is expecting them to be inferred after the fact.

How to make TS really infer types?

Do this:

```<code>var a = 33;
a=true; // error
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is the code:

var a; // it is typed "any".
a = 33; // No inference
a = true; // compiles without errors.

It won't infer the type by first usage.

In Haxe:

var a; // it is now an "Unknown" kinda type, "monomorph"
a = 33; // Here it became int
a = true; // compiler error, unable to set int to bool.

Am I doing anything wrong? Is it possible to do it in TypeScript?

As far as I see, it's not possible. So this question could be a great warning for all OCaml or Haxe developers: you should initialize your variable immediately in TS.

Body:
Am I doing anything wrong?

Types in TypeScript are inferred when a variable is declared, not afterward. What you're doing wrong is expecting them to be inferred after the fact.

How to make TS really infer types?

Do this:

var a = 33;
a=true; // error


问:
Cool tricks and expressive snippets with ruby collections/enumerables
What are your favorite code snippets with ruby collections? Preferably they should be discovery for you, be expressive, readable and introduce some fun in your coding practice.

Pattern-matching in arrays (for local variables and parameters):

```<code>(a, b), c = [[:a, :b], :c]
[a,b,c]
=> [:a, :b, :c]

(a,), = [[:a]]
a
=> :a
</code>```

Assigning from non-arrays to multiple variables:

```<code>abc, a, b =* "abc".match(/(a)(b)./)
=> ["abc", "a", "b"]

nil1, =* "abc".match(/xyz/)
=> []
</code>```

Initialize array elements with the same expression:

```<code>5.times.map { 1 }
=> [1,1,1,1]

Array.new(5) { 1 }
=> [1,1,1,1,1]
</code>```

Initialize array with the same value:

```<code>[2]*5
=>[2,2,2,2,2]

Array.new 5, 2
=>[2,2,2,2,2]
</code>```

Sum elements of an array:

```<code>[1,2,3].reduce(0, &:+)

=> 6
</code>```

Find all indices that match condition:

```<code>a.each_with_index.find_all { |e, i| some_predicate(e) }.map(&:last)
</code>```

Alternate CSS classes:

```<code>(1..4).zip(%w[cls1 cls2].cycle)

=> [[1, "cls1"], [2, "cls2"], [3, "cls1"], [4, "cls2"]]
</code>```

Unzipping:

```<code>keys, values = {a: 1, b: 2}.to_a.transpose
keys
=> [:a, :b]
</code>```

Exploring boolean member methods of a string:

```<code>"".methods.sort.grep(/\?/)
</code>```

Exploring string-specific methods:

```<code>"".methods.sort - [].methods
</code>```

答:
Lazy Fibonacci series with memoization, taken from Neeraj Singh:

```<code>fibs = { 0 => 0, 1 => 1 }.tap do |fibs|
  fibs.default_proc = ->(fibs, n) { fibs[n] = fibs[n-1] + fibs[n-2] }
end

fibs.take(10).map(&:last).each(&method(:puts))
</code>```

An implementation of Counting Sort:

```<code>module Enumerable
  def counting_sort(k)
    reduce(Array.new(k+1, 0)) {|counting, n| counting.tap { counting[n] += 1 }}.
    map.with_index {|count, n| [n] * count }.flatten
  end
end
</code>```

An implementation of sum aka prefix sum:

```<code>module Enumerable
  def scan(initial=nil, sym=nil, &block)
    args = if initial then [initial] else [] end
    unless block_given?
      args, sym, initial = [], initial, first unless sym
      block = ->(acc, el) { acc.send(sym, el) }
    end
    [initial || first].tap {|res|
      reduce(*args) {|acc, el|
        block.(acc, el).tap {|e|
          res << e
        }
      }
    }
  end
end
</code>```

Here, I experimented with having Hash#each yield KeyValuePairs instead of two-element Arrays. It's quite surprising, how much code still works, after doing such a brutal monkey-patch. Yay, duck typing!

```<code>class Hash
  KeyValuePair = Struct.new(:key, :value) do
    def to_ary
      return key, value
    end
  end

  old_each = instance_method(:each)
  define_method(:each) do |&blk|
    old_each.bind(self).() do |k, v|
      blk.(KeyValuePair.new(k, v))
    end
  end
end
</code>```

Something I have been playing around with is making Enumerable#=== perform recursive structural pattern matching. I have no idea if this is in any way useful. I don't even know if it actually works.

```<code>module Enumerable
  def ===(other)
    all? {|el|
      next true if el.nil?
      begin
        other.any? {|other_el| el === other_el }
      rescue NoMethodError => e
        raise unless e.message =~ /any\?/
        el === other
      end
    }
  end
end
</code>```

Another thing I toyed around with recently was re-implementing all methods in Enumerable, but using reduce instead of each as the basis. In this case, I know it doesn't actually work properly.

```<code>module Enumerable
  def all?
    return reduce(true) {|res, el| break false unless res; res && el } unless block_given?
    reduce(true) {|res, el| break false unless res; res && yield(el) }
  end

  def any?
    return reduce(false) {|res, el| break true if res || el } unless block_given?
    reduce(false) {|res, el| break true if res || yield(el) }
  end

  def collect
    reduce([]) {|res, el| res << yield(el) }
  end
  alias_method :map, :collect

  def count(item=undefined = Object.new)
    return reduce(0) {|res, el| res + 1 if el == item } unless undefined.equal?(item)
    unless block_given?
      return size if respond_to? :size
      return reduce(0) {|res, el| res + 1 }
    end
    reduce(0) {|res, el| res + 1 if yield el }
  end

  def detect(ifnone=nil)
    reduce(ifnone) {|res, el| if yield el then el end unless res }
  end
  alias_method :find, :detect

  def drop(n=1)
    reduce([]) {|res, el| res.tap { res << el unless n -= 1 >= 0 }}
  end

  def drop_while
    reduce([]) {|res, el| res.tap { res << el unless yield el }}
  end

  def each
    tap { reduce(nil) {|_, el| yield el }}
  end

  def each_with_index
    tap { reduce(-1) {|i, el| (i+1).tap {|i| yield el, i }}}
  end

  def find_all
    reduce([]) {|res, el| res.tap {|res| res << el if yield el }}
  end
  alias_method :select, :find_all

  def find_index(item=undefined = Object.new)
    return reduce(-1) {|res, el| break res + 1 if el == item } unless undefined.equals?(item)
    reduce(-1) {|res, el| break res + 1 if yield el }
  end

  def grep(pattern)
    return reduce([]) {|res, el| res.tap {|res| res << el if pattern === el }} unless block_given?
    reduce([]) {|res, el| res.tap {|res| res << yield(el) if pattern === el }}
  end

  def group_by
    reduce(Hash.new {|hsh, key| hsh[key] = [] }) {|res, el| res.tap { res[yield el] = el }}
  end

  def include?(obj)
    reduce(false) {|res, el| break true if res || el == obj }
  end

  def reject
    reduce([]) {|res, el| res.tap {|res| res << el unless yield el }}
  end
end
</code>```

Body:
What are your favorite code snippets with ruby collections? Preferably they should be discovery for you, be expressive, readable and introduce some fun in your coding practice.

Pattern-matching in arrays (for local variables and parameters):

(a, b), c = [[:a, :b], :c]
[a,b,c]
=> [:a, :b, :c]

(a,), = [[:a]]
a
=> :a

Assigning from non-arrays to multiple variables:

abc, a, b =* "abc".match(/(a)(b)./)
=> ["abc", "a", "b"]

nil1, =* "abc".match(/xyz/)
=> []

Initialize array elements with the same expression:

5.times.map { 1 }
=> [1,1,1,1]

Array.new(5) { 1 }
=> [1,1,1,1,1]

Initialize array with the same value:

[2]*5
=>[2,2,2,2,2]

Array.new 5, 2
=>[2,2,2,2,2]

Sum elements of an array:

[1,2,3].reduce(0, &:+)

=> 6

Find all indices that match condition:

a.each_with_index.find_all { |e, i| some_predicate(e) }.map(&:last)

Alternate CSS classes:

(1..4).zip(%w[cls1 cls2].cycle)

=> [[1, "cls1"], [2, "cls2"], [3, "cls1"], [4, "cls2"]]

Unzipping:

keys, values = {a: 1, b: 2}.to_a.transpose
keys
=> [:a, :b]

Exploring boolean member methods of a string:

"".methods.sort.grep(/\?/)

Exploring string-specific methods:

"".methods.sort - [].methods

Body:
Lazy Fibonacci series with memoization, taken from Neeraj Singh:

fibs = { 0 => 0, 1 => 1 }.tap do |fibs|
  fibs.default_proc = ->(fibs, n) { fibs[n] = fibs[n-1] + fibs[n-2] }
end

fibs.take(10).map(&:last).each(&method(:puts))

An implementation of Counting Sort:

module Enumerable
  def counting_sort(k)
    reduce(Array.new(k+1, 0)) {|counting, n| counting.tap { counting[n] += 1 }}.
    map.with_index {|count, n| [n] * count }.flatten
  end
end

An implementation of sum aka prefix sum:

module Enumerable
  def scan(initial=nil, sym=nil, &block)
    args = if initial then [initial] else [] end
    unless block_given?
      args, sym, initial = [], initial, first unless sym
      block = ->(acc, el) { acc.send(sym, el) }
    end
    [initial || first].tap {|res|
      reduce(*args) {|acc, el|
        block.(acc, el).tap {|e|
          res << e
        }
      }
    }
  end
end

Here, I experimented with having Hash#each yield KeyValuePairs instead of two-element Arrays. It's quite surprising, how much code still works, after doing such a brutal monkey-patch. Yay, duck typing!

class Hash
  KeyValuePair = Struct.new(:key, :value) do
    def to_ary
      return key, value
    end
  end

  old_each = instance_method(:each)
  define_method(:each) do |&blk|
    old_each.bind(self).() do |k, v|
      blk.(KeyValuePair.new(k, v))
    end
  end
end

Something I have been playing around with is making Enumerable#=== perform recursive structural pattern matching. I have no idea if this is in any way useful. I don't even know if it actually works.

module Enumerable
  def ===(other)
    all? {|el|
      next true if el.nil?
      begin
        other.any? {|other_el| el === other_el }
      rescue NoMethodError => e
        raise unless e.message =~ /any\?/
        el === other
      end
    }
  end
end

Another thing I toyed around with recently was re-implementing all methods in Enumerable, but using reduce instead of each as the basis. In this case, I know it doesn't actually work properly.

module Enumerable
  def all?
    return reduce(true) {|res, el| break false unless res; res && el } unless block_given?
    reduce(true) {|res, el| break false unless res; res && yield(el) }
  end

  def any?
    return reduce(false) {|res, el| break true if res || el } unless block_given?
    reduce(false) {|res, el| break true if res || yield(el) }
  end

  def collect
    reduce([]) {|res, el| res << yield(el) }
  end
  alias_method :map, :collect

  def count(item=undefined = Object.new)
    return reduce(0) {|res, el| res + 1 if el == item } unless undefined.equal?(item)
    unless block_given?
      return size if respond_to? :size
      return reduce(0) {|res, el| res + 1 }
    end
    reduce(0) {|res, el| res + 1 if yield el }
  end

  def detect(ifnone=nil)
    reduce(ifnone) {|res, el| if yield el then el end unless res }
  end
  alias_method :find, :detect

  def drop(n=1)
    reduce([]) {|res, el| res.tap { res << el unless n -= 1 >= 0 }}
  end

  def drop_while
    reduce([]) {|res, el| res.tap { res << el unless yield el }}
  end

  def each
    tap { reduce(nil) {|_, el| yield el }}
  end

  def each_with_index
    tap { reduce(-1) {|i, el| (i+1).tap {|i| yield el, i }}}
  end

  def find_all
    reduce([]) {|res, el| res.tap {|res| res << el if yield el }}
  end
  alias_method :select, :find_all

  def find_index(item=undefined = Object.new)
    return reduce(-1) {|res, el| break res + 1 if el == item } unless undefined.equals?(item)
    reduce(-1) {|res, el| break res + 1 if yield el }
  end

  def grep(pattern)
    return reduce([]) {|res, el| res.tap {|res| res << el if pattern === el }} unless block_given?
    reduce([]) {|res, el| res.tap {|res| res << yield(el) if pattern === el }}
  end

  def group_by
    reduce(Hash.new {|hsh, key| hsh[key] = [] }) {|res, el| res.tap { res[yield el] = el }}
  end

  def include?(obj)
    reduce(false) {|res, el| break true if res || el == obj }
  end

  def reject
    reduce([]) {|res, el| res.tap {|res| res << el unless yield el }}
  end
end


问:
INSERT into table with foreign key - PHP PDO
I have one database called "Profiles".
This database contains two tables called "users" and "profiles":

Users:

user_id

name

email

password

Profiles:

profile_id

first_name

last_name

summary

I am working on a CRUD scenario using PHP and PDO. Currently, I'm trying to "add" (create) a new profile entry. The assignment states: "Make sure to mark the entry with the foreign key user_id of the currently logged in user. (create)".

I don't understand how to connect the two tables together in PDO. I am getting the following error:

Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity       constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (profiles.profile, CONSTRAINT profile_ibfk_2 FOREIGN KEY (user_id) REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE CASCADE) in /websites-mamp/asmt-profile/add.php:32 Stack trace: #0 /websites-mamp/asmt-profile/add.php(32): PDOStatement->execute(Array) #1 {main} thrown in /websites-mamp/asmt-profile/add.php on line 32

Also, what does CONSTRAINT profile_ibfk_2 mean?

My code is:

```<code><?php
session_start();
require_once "pdo.php";

// Validate field entries
if ( isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['summary'])) {

    $sql = "INSERT INTO profile (first_name, last_name, summary)
               VALUES (:first_name, :last_name, :summary)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array(
        ':first_name' => $_POST['first_name'],
        ':last_name' => $_POST['last_name'],
        ':summary' => $_POST['summary']
        ));
    $_SESSION['success'] = "Record added";
    header("Location: index.php");
    return;
}

?>

<!DOCTYPE html>
<html>
<head>
<title>Add</title>
</head>
<body>

 <div class="container">

    <form method="post">
        <p>First Name:
        <input type="text" name="first_name" /></p>
        <p>Last Name:
        <input type="text" name="last_name" /></p>
        <p>Summary:
        <textarea type="text" name="summary"></textarea></p>
        <input type="submit" value="Add">
        <input type="submit" name="logout" value="Cancel">
    </form>

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

Where in the code do I connect to the foreign key? I've tried WHERE clauses, but that isn't helping. Can someone explain this easily? I've been exploring StackOverflow here for similar issues, but most of it is above my head or it's not PDO. Any help is appreciated, thank you.

答:
profile_ibfk_2 is the name of the foreign key. You're trying to adf a row into your profile table, but you do not set the user_id too. So change your INSERT statement:

```<code>$sql = "INSERT INTO profile (first_name, last_name, summary, user_id)
           VALUES (:first_name, :last_name, :summary, :user_id)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
    ':first_name' => $_POST['first_name'],
    ':last_name' => $_POST['last_name'],
    ':summary' => $_POST['summary'],
    ':user_id' => $whatEverToGetTheCurrentUserID,
    ));
</code>```

Body:
I have one database called "Profiles".
This database contains two tables called "users" and "profiles":

Users:

user_id

name

email

password

Profiles:

profile_id

first_name

last_name

summary

I am working on a CRUD scenario using PHP and PDO. Currently, I'm trying to "add" (create) a new profile entry. The assignment states: "Make sure to mark the entry with the foreign key user_id of the currently logged in user. (create)".

I don't understand how to connect the two tables together in PDO. I am getting the following error:

Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity       constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (profiles.profile, CONSTRAINT profile_ibfk_2 FOREIGN KEY (user_id) REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE CASCADE) in /websites-mamp/asmt-profile/add.php:32 Stack trace: #0 /websites-mamp/asmt-profile/add.php(32): PDOStatement->execute(Array) #1 {main} thrown in /websites-mamp/asmt-profile/add.php on line 32

Also, what does CONSTRAINT profile_ibfk_2 mean?

My code is:

<?php
session_start();
require_once "pdo.php";

// Validate field entries
if ( isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['summary'])) {

    $sql = "INSERT INTO profile (first_name, last_name, summary)
               VALUES (:first_name, :last_name, :summary)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(array(
        ':first_name' => $_POST['first_name'],
        ':last_name' => $_POST['last_name'],
        ':summary' => $_POST['summary']
        ));
    $_SESSION['success'] = "Record added";
    header("Location: index.php");
    return;
}

?>

<!DOCTYPE html>

<title>Add</title>

    <form method="post">

First Name:
        <input type="text" name="first_name" />

Last Name:
        <input type="text" name="last_name" />

Summary:
        <textarea type="text" name="summary"></textarea>

        <input type="submit" value="Add">
        <input type="submit" name="logout" value="Cancel">
    </form>

Where in the code do I connect to the foreign key? I've tried WHERE clauses, but that isn't helping. Can someone explain this easily? I've been exploring StackOverflow here for similar issues, but most of it is above my head or it's not PDO. Any help is appreciated, thank you.

Body:
profile_ibfk_2 is the name of the foreign key. You're trying to adf a row into your profile table, but you do not set the user_id too. So change your INSERT statement:

$sql = "INSERT INTO profile (first_name, last_name, summary, user_id)
           VALUES (:first_name, :last_name, :summary, :user_id)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
    ':first_name' => $_POST['first_name'],
    ':last_name' => $_POST['last_name'],
    ':summary' => $_POST['summary'],
    ':user_id' => $whatEverToGetTheCurrentUserID,
    ));


问:
MS Access Query - Total Week Hours Worked
looking for some access query help.

Im trying to make a total hours worked in a week query.

TotalHours: (([FinishAM]-[StartAM]+[FinishPM]-[StartPM])*24 & " Hours")

Here's the query for the daily hours worked..

Im quite new to access.

cheers.

答:
You can use:

```<code>' Specify begin and end time of daily working hours.
Const cdatWorkTimeStart   As Date = #8:00:00 AM#
Const cdatWorkTimeStop    As Date = #4:00:00 PM#
Const cbytWorkdaysOfWeek  As Byte = 5

Dim TotalHours As Integer

TotalHours = DateDiff("h", cdatWorkTimeStart, cdatWorkTimeStop) * cbytWorkdaysOfWeek
</code>```

For an extended count of hours for any count of days, you can use the full function here:

```<code>Public Function ISO_WorkTimeDiff( _
  ByVal datDateTimeFrom As Date, _
  ByVal datDateTimeTo As Date, _
  Optional ByVal booNoHours As Boolean) _
  As Long

' Purpose: Calculate number of working minutes between date/times datDateTimeFrom and datDateTimeTo.
' Assumes: 5 or 6 working days per week. Weekend is (Saturday and) Sunday.
' Returns: "Working minutes". Divide by 60 to obtain working hours.
' Limitation: Does not count for public holidays.
'
' May be freely used and distributed.
' 2001-06-26. Gustav Brock, Cactus Data ApS, Copenhagen
'
' If booNoHours is True, time values are ignored.

  ' Specify begin and end time of daily working hours.
  Const cdatWorkTimeStart   As Date = #8:00:00 AM#
  Const cdatWorkTimeStop    As Date = #4:00:00 PM#
  Const cbytWorkdaysOfWeek  As Byte = 5

  Dim bytSunday             As Byte
  Dim intWeekdayDateFrom    As Integer
  Dim intWeekdayDateTo      As Integer
  Dim datTimeFrom           As Date
  Dim datTimeTo             As Date
  Dim lngDays               As Long
  Dim lngMinutes            As Long
  Dim lngWorkMinutesDaily   As Long

  ' No special error handling.
  On Error Resume Next

  If DateDiff("n", datDateTimeFrom, datDateTimeTo) <= 0 Then
    ' Nothing to do. Return zero.
  Else

    ' Calculate number of daily "working minutes".
    lngWorkMinutesDaily = DateDiff("n", cdatWorkTimeStart, cdatWorkTimeStop)

    ' Find ISO weekday for Sunday.
    bytSunday = Weekday(vbSunday, vbMonday)

    ' Find weekdays for the dates.
    intWeekdayDateFrom = Weekday(datDateTimeFrom, vbMonday)
    intWeekdayDateTo = Weekday(datDateTimeTo, vbMonday)

    ' Compensate weekdays' value for non-working days (weekends).
    intWeekdayDateFrom = intWeekdayDateFrom + (intWeekdayDateFrom = bytSunday)
    intWeekdayDateTo = intWeekdayDateTo + (intWeekdayDateTo = bytSunday)

    ' Calculate number of working days between the weeks of the two dates.
    lngDays = (cbytWorkdaysOfWeek * DateDiff("w", datDateTimeFrom, datDateTimeTo, vbMonday, vbFirstFourDays))
    ' Add number of working days between the two weekdays, ignoring number of weeks.
    lngDays = lngDays + intWeekdayDateTo - intWeekdayDateFrom - (cbytWorkdaysOfWeek * (intWeekdayDateTo < intWeekdayDateFrom))

    If Not booNoHours = True Then
      ' Extract begin and stop hour (time) for the working period.
      datTimeFrom = TimeSerial(Hour(datDateTimeFrom), Minute(datDateTimeFrom), Second(datDateTimeFrom))
      datTimeTo = TimeSerial(Hour(datDateTimeTo), Minute(datDateTimeTo), Second(datDateTimeTo))
      ' Adjust times before or after daily working hours to boundaries of working hours.
      If DateDiff("n", datTimeFrom, cdatWorkTimeStart) > 0 Then
        datTimeFrom = cdatWorkTimeStart
      ElseIf DateDiff("n", datTimeFrom, cdatWorkTimeStop) < 0 Then
        datTimeFrom = cdatWorkTimeStop
      End If
      If DateDiff("n", datTimeTo, cdatWorkTimeStart) > 0 Then
        datTimeTo = cdatWorkTimeStart
      ElseIf DateDiff("n", datTimeTo, cdatWorkTimeStop) < 0 Then
        datTimeTo = cdatWorkTimeStop
      End If

      ' Calculate number of working minutes between the two days, ignoring number of days.
      lngMinutes = DateDiff("n", datTimeFrom, datTimeTo)
    End If

    ' Calculate number of working minutes between the two days using the workday count.
    lngMinutes = lngMinutes + (lngDays * lngWorkMinutesDaily)

  End If

  ISO_WorkTimeDiff = lngMinutes

End Function
</code>```

Body:
You can use:

' Specify begin and end time of daily working hours.
Const cdatWorkTimeStart   As Date = #8:00:00 AM#
Const cdatWorkTimeStop    As Date = #4:00:00 PM#
Const cbytWorkdaysOfWeek  As Byte = 5

Dim TotalHours As Integer

TotalHours = DateDiff("h", cdatWorkTimeStart, cdatWorkTimeStop) * cbytWorkdaysOfWeek

For an extended count of hours for any count of days, you can use the full function here:

Public Function ISO_WorkTimeDiff( _
  ByVal datDateTimeFrom As Date, _
  ByVal datDateTimeTo As Date, _
  Optional ByVal booNoHours As Boolean) _
  As Long

' Purpose: Calculate number of working minutes between date/times datDateTimeFrom and datDateTimeTo.
' Assumes: 5 or 6 working days per week. Weekend is (Saturday and) Sunday.
' Returns: "Working minutes". Divide by 60 to obtain working hours.
' Limitation: Does not count for public holidays.
'
' May be freely used and distributed.
' 2001-06-26. Gustav Brock, Cactus Data ApS, Copenhagen
'
' If booNoHours is True, time values are ignored.

  ' Specify begin and end time of daily working hours.
  Const cdatWorkTimeStart   As Date = #8:00:00 AM#
  Const cdatWorkTimeStop    As Date = #4:00:00 PM#
  Const cbytWorkdaysOfWeek  As Byte = 5

  Dim bytSunday             As Byte
  Dim intWeekdayDateFrom    As Integer
  Dim intWeekdayDateTo      As Integer
  Dim datTimeFrom           As Date
  Dim datTimeTo             As Date
  Dim lngDays               As Long
  Dim lngMinutes            As Long
  Dim lngWorkMinutesDaily   As Long

  ' No special error handling.
  On Error Resume Next

  If DateDiff("n", datDateTimeFrom, datDateTimeTo) <= 0 Then
    ' Nothing to do. Return zero.
  Else

    ' Calculate number of daily "working minutes".
    lngWorkMinutesDaily = DateDiff("n", cdatWorkTimeStart, cdatWorkTimeStop)

    ' Find ISO weekday for Sunday.
    bytSunday = Weekday(vbSunday, vbMonday)

    ' Find weekdays for the dates.
    intWeekdayDateFrom = Weekday(datDateTimeFrom, vbMonday)
    intWeekdayDateTo = Weekday(datDateTimeTo, vbMonday)

    ' Compensate weekdays' value for non-working days (weekends).
    intWeekdayDateFrom = intWeekdayDateFrom + (intWeekdayDateFrom = bytSunday)
    intWeekdayDateTo = intWeekdayDateTo + (intWeekdayDateTo = bytSunday)

    ' Calculate number of working days between the weeks of the two dates.
    lngDays = (cbytWorkdaysOfWeek * DateDiff("w", datDateTimeFrom, datDateTimeTo, vbMonday, vbFirstFourDays))
    ' Add number of working days between the two weekdays, ignoring number of weeks.
    lngDays = lngDays + intWeekdayDateTo - intWeekdayDateFrom - (cbytWorkdaysOfWeek * (intWeekdayDateTo < intWeekdayDateFrom))

    If Not booNoHours = True Then
      ' Extract begin and stop hour (time) for the working period.
      datTimeFrom = TimeSerial(Hour(datDateTimeFrom), Minute(datDateTimeFrom), Second(datDateTimeFrom))
      datTimeTo = TimeSerial(Hour(datDateTimeTo), Minute(datDateTimeTo), Second(datDateTimeTo))
      ' Adjust times before or after daily working hours to boundaries of working hours.
      If DateDiff("n", datTimeFrom, cdatWorkTimeStart) > 0 Then
        datTimeFrom = cdatWorkTimeStart
      ElseIf DateDiff("n", datTimeFrom, cdatWorkTimeStop) < 0 Then
        datTimeFrom = cdatWorkTimeStop
      End If
      If DateDiff("n", datTimeTo, cdatWorkTimeStart) > 0 Then
        datTimeTo = cdatWorkTimeStart
      ElseIf DateDiff("n", datTimeTo, cdatWorkTimeStop) < 0 Then
        datTimeTo = cdatWorkTimeStop
      End If

      ' Calculate number of working minutes between the two days, ignoring number of days.
      lngMinutes = DateDiff("n", datTimeFrom, datTimeTo)
    End If

    ' Calculate number of working minutes between the two days using the workday count.
    lngMinutes = lngMinutes + (lngDays * lngWorkMinutesDaily)

  End If

  ISO_WorkTimeDiff = lngMinutes

End Function


问:
Error Uncaught SyntaxError: Invalid or unexpected token? :( special character
I have code of file html example

Click here```
</div>
</div>
</p>

<p>I replace char <code>'</code> to <code>'</code> . After I run this file.</p>

<p>Tab console of The browse show this error. When I check element in browser, it show </p>

```Click here // this is not correct
```

I want to show It's hot in alert box but I don't want to use 'It\'s hot' or "It's hot" in my code.

It only is example to use ' or " of text in JavaScript.

Is there another way?

答:
Yes, there is. You can use ' and " instead of ' and " respectively. These are unintuitive if you ask me, but they are perfectly usable. However, if you get a text which was created outside your control, then you will need to replace all apostrophes and quotes to achieve what you want, like this:

```<code>function getSomeText(input) {
    return input.split('"').join('&quote;').split("'").join(''');
}
</code>```

Body:
I have code of file html example

Click here

I replace char ' to ' . After I run this file.

Tab console of The browse show this error. When I check element in browser, it show

Click here // this is not correct

I want to show It's hot in alert box but I don't want to use 'It\'s hot' or "It's hot" in my code.

It only is example to use ' or " of text in JavaScript.

Is there another way?

Body:
Yes, there is. You can use &apos; and &quot; instead of ' and " respectively. These are unintuitive if you ask me, but they are perfectly usable. However, if you get a text which was created outside your control, then you will need to replace all apostrophes and quotes to achieve what you want, like this:

function getSomeText(input) {
    return input.split('"').join('&quote;').split("'").join('&apos;');
}


问:
Exact use of finally block in java if we can handle it in if else block with a flag defined in try catch
For the last few days I am trying to dig deep in java, I came across try catch finally exception handling.

I know finally executes no matters what, but I want to know "WHY" we can also handle the exception in catch or after catch, why finally?

I came up with an answer

https://stackoverflow.com/a/23537289/7794329

```<code>public class tryCatch {
    public static void main(String[] args) {

        double p = 1.0D;
        String str = "bla";
        try{
            p = Double.valueOf(str);
        }
        catch(Exception ex){
            System.out.println("Exception Happened");
            return;  //return statement here!!!
        }finally{
            System.out.println("Finally");
        }
        System.out.println("After finally");

        System.out.println("again finally");
    }
}
</code>```

output

```<code>Exception Happened
Finally
</code>```

what if i remove that return; and handle after the code of finally. It will run.. so why we need finally only because of return statement? is it like i am doing mistakes by returing the code and forcefully handling it in finally.I can also make a flag in catch and put it in a if else block to handle the exception in catch

Why do we use finally blocks?

I really completely didn't understand can someone let me understand in plain language? Why do we use finally if we can handle it from try catch or even catch fails we can handle it in if else like if catch got exception run this... else...

答: If an exception is thrown, the finally block runs after the catch block and then the control flow goes to wherever the catch block decided, which was the return. If you get rid of the return statement, you'll find those other things print.</p>

Body:
For the last few days I am trying to dig deep in java, I came across try catch finally exception handling.

I know finally executes no matters what, but I want to know "WHY" we can also handle the exception in catch or after catch, why finally?

I came up with an answer

https://stackoverflow.com/a/23537289/7794329

public class tryCatch {
    public static void main(String[] args) {

        double p = 1.0D;
        String str = "bla";
        try{
            p = Double.valueOf(str);
        }
        catch(Exception ex){
            System.out.println("Exception Happened");
            return;  //return statement here!!!
        }finally{
            System.out.println("Finally");
        }
        System.out.println("After finally");

        System.out.println("again finally");
    }
}

output

Exception Happened
Finally

what if i remove that return; and handle after the code of finally. It will run.. so why we need finally only because of return statement? is it like i am doing mistakes by returing the code and forcefully handling it in finally.I can also make a flag in catch and put it in a if else block to handle the exception in catch

Why do we use finally blocks?

I really completely didn't understand can someone let me understand in plain language? Why do we use finally if we can handle it from try catch or even catch fails we can handle it in if else like if catch got exception run this... else...


问:
C# Do I need TRY/CATCH in order to throw?
If all I want to do is throw the exception up a level when it occurs?

```<code>private void TryCatch()
{
   try
   {
       foo();
   }
   catch (Exception ex)
   {
       throw;
   }
}

private void NoTryCatch()
{
   foo();
}
</code>```

Aren't these two methods the same?

If an exception occurs in TryCatch it will be thrown up a level and if an exception occurs in NoTryCatch, the exception will also be thrown up a level.

This question came about after using ReSharper and noticing that it suggested to remove the try/catch block as it was redundant.

答: Yes, the try catch block is redundant. The stack will just be unwound until a try/catch is found to handle the exception.</p>

OwnerDisplayName: Petrolios

LastEditorDisplayName: Jon Skeet

Body:
If all I want to do is throw the exception up a level when it occurs?

private void TryCatch()
{
   try
   {
       foo();
   }
   catch (Exception ex)
   {
       throw;
   }
}

private void NoTryCatch()
{
   foo();
}

Aren't these two methods the same?

If an exception occurs in TryCatch it will be thrown up a level and if an exception occurs in NoTryCatch, the exception will also be thrown up a level.

This question came about after using ReSharper and noticing that it suggested to remove the try/catch block as it was redundant.

OwnerDisplayName: Kevin Loney


问:
Tell `string::operator==` to start comparing at the back of the string
Is it possible/(relatively) easy/std™ to start comparing at the back of a string or should I write my own function for that? It would be relatively straightforward of course, but still, I would trust a standard library implementation over mine any day.

The end of the string is almost unique, and the front is quite common, that's the only reason I need this "optimization".

Thanks!

答:
If you want to reverse it first, I would suggest reverse() from  to reverse the string first, then start comparing using string.compare() or use your own algorithm. However, reverse() does take a while, and is processor intensive, so I do suggest your own function to handle this one. Start a loop with i equal to the string.length(), and then count back using --i and compare.</p>

```<code>function stringCompFromBack(string str1, string str2)
{
    if (str1.length() != str2.length)
    {return false;}

    for(int i = str1.length() ; i > 0; --i)
    {
        if(str1[i] != str2 [i])
        {return false;}
    }
    return true;
}

string str1 = "James Madison";
string str2 = "James Ford";
bool same = stringCompFromBack(str1, str2);
</code>```

Body:
If you want to reverse it first, I would suggest reverse() from  to reverse the string first, then start comparing using string.compare() or use your own algorithm. However, reverse() does take a while, and is processor intensive, so I do suggest your own function to handle this one. Start a loop with i equal to the string.length(), and then count back using --i and compare.

function stringCompFromBack(string str1, string str2)
{
    if (str1.length() != str2.length)
    {return false;}

    for(int i = str1.length() ; i > 0; --i)
    {
        if(str1[i] != str2 [i])
        {return false;}
    }
    return true;
}

string str1 = "James Madison";
string str2 = "James Ford";
bool same = stringCompFromBack(str1, str2);


问:
How to play flv video in ios webview?
I have real time flv format video on my web page. I want to use webview to load this page in my ios app. But for flv is not a HTML5 support video format, so it cannot played directly without flash. I also try to use flv.js, flv.js is written in pure JavaScript without Flash. Then video can play in web page without flash, but still cannot paly in my app. In my app, I used WKwebview.</p>

答:
According to the FLV.JS readme for livestreaming (see: Compatibility at bottom) :

(updated March 17 2017)

Due to IO restrictions, flv.js can support HTTP FLV live stream on
  Chrome 43+, FireFox 42+ and Edge 15.15048+ for now.

HTTP FLV live stream relies on stream IO, which has been introduced in
  fetch and stream spec. but FetchStreamLoader only works well on a few
  browsers for now:

Safari: fetch has not been supported on current version 10, but available in Safari Technology
  Preview

This may be what is affecting the ability to playback FLV video on iOS via WKwebview.

It seems iOS SDK (eg: Swift) itself can use the fetch protocol but here in your project you're relying only on the WebKit browser renderer (which may not yet support this feature?).

Title: How to play flv video in ios webview?


问:
AWS s3 file upload in express js: whats the difference between upload vs multipart upload
I am trying to upload a file to AWS s3 using express js,instead of putObject i am using upload http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property function

```<code>       var options ={
            partSize: 5242880, queueSize: 1
        };
        console.time('Uploadtime');
        s3.upload(params,options,function(err, data) {
            if (err) console.log(err, err.stack); // an error occurred
            else     {
                console.timeEnd('Uploadtime');
                console.log("uploaded",data);
                res.json({
                    'status':'Uploaded'
                });
            }           // successful response
        });
</code>```

I think upload and multipart upload do the same thing(am i correct??)
My question is do i need to use multi part upload or stay with upload method.

From the docs i can't get the similarities between upload and multipartupload

答:
upload and multipart upload perform the same action but there are the few advantage of multipart upload

You can upload parts in parallel to improve throughput.

Smaller part size minimizes the impact of restarting a failed upload
due to a network error.

You can upload object parts over time. Once you initiate a multipart
upload

there is no expiry; you must explicitly complete or abort the
multipart upload.

You can upload an object as you are creating it.

So you can decide which one you should go with according to your need , multipart is recommended when the object you are uploading is big in size .

Body:
I am trying to upload a file to AWS s3 using express js,instead of putObject i am using upload http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property function

       var options ={
            partSize: 5242880, queueSize: 1
        };
        console.time('Uploadtime');
        s3.upload(params,options,function(err, data) {
            if (err) console.log(err, err.stack); // an error occurred
            else     {
                console.timeEnd('Uploadtime');
                console.log("uploaded",data);
                res.json({
                    'status':'Uploaded'
                });
            }           // successful response
        });

I think upload and multipart upload do the same thing(am i correct??)
My question is do i need to use multi part upload or stay with upload method.

From the docs i can't get the similarities between upload and multipartupload


问:
REPLACE a given occurance of a string in a column
I have a column like this:

```<code>vars
-----------
|A|B|A|D|AB|B...
</code>```

I want to replace one var (e.g: the one in 3rd position, which happens to be A) but keep any other A's. The position is determined by a variable. So I should get:

```<code>vars
-----------
|A|B|D|AB|B...
</code>```

I know I should use REPLACE and possibly SUBSTRING_INDEX, but I can't figure out how. Here's what I've tried:
Let's say :pos=3;

```<code>vars = REPLACE(vars, (SUBSTRING_INDEX(SUBSTRING_INDEX(vars, '|', :pos), '|', -1)), '')
</code>```

But this actually replaces all other characters and keeps the one I need replaced.

UPDATE: Mind that I don't know what var I want to replace, only its position.

UPDATE 2:

```<code>vars = Concat(substring(vars ,1,:pos-1), substring(vars,:pos+2))
</code>```

This does the trick but I forgot to mention the vars are not always |A and |B etc., but also |AB, |AC... So the position shouldn't always move by one character, but until the next |.

答:
As @Zohar said, I agree your model is broken. Yet, if you want to achieve, here's an example with locate, substring, concat:

First locate the index of first |A the second |A will always be after it.

locate('|A','|A|B|A|D|G|B', locate('|A','|A|B|A|D|G|B')+1)

-- here +1 denotes after first index

Second find the sub-string after the second occurrence of |A

substring('|A|B|A|D|G|B',locate('|A','|A|B|A|D|G|B', locate('|A','|A|B|A|D|G|B')+1)+2)

--here +2 denotes the length of your string with is |A

Third find the sub-string before the second occurrence of |A

substring('|A|B|A|D|G|B',locate('|A','|A|B|A|D|G|B', 1,locate('|A','|A|B|A|D|G|B')+1)-1)

-- here -1 denotes any thing from the beginning to the charecter before |A

Fourth, concat the string after and before the second occurrence of |A

```<code>Concat(
  substring('|A|B|A|D|G|B',locate('|A','|A|B|A|D|G|B',1,locate('|A','|A|B|A|D|G|B')+1)-1),
  substring('|A|B|A|D|G|B',locate('|A','|A|B|A|D|G|B', locate('|A','|A|B|A|D|G|B')+1)+2)
)
</code>```

EDIT 1: Like in your update if you ready know the position you can simply do:

```<code>vars = Concat(substring(vars ,1,:pos-1), substring(vars,:pos+2))
</code>```

EDIT 2:

With your comment if you need to replace till next | you can do use both location and substring something like:

```<code>vars = CONCAT(SUBSTRING(vars ,1,:pos-1), SUBSTRING(vars,LOCATE('|',vars, :pos+1)))
</code>```

DEMO

Body:
I have a column like this:

vars
-----------
|A|B|A|D|AB|B...

I want to replace one var (e.g: the one in 3rd position, which happens to be A) but keep any other A's. The position is determined by a variable. So I should get:

vars
-----------
|A|B|D|AB|B...

I know I should use REPLACE and possibly SUBSTRING_INDEX, but I can't figure out how. Here's what I've tried:
Let's say :pos=3;

vars = REPLACE(vars, (SUBSTRING_INDEX(SUBSTRING_INDEX(vars, '|', :pos), '|', -1)), '')

But this actually replaces all other characters and keeps the one I need replaced.

UPDATE: Mind that I don't know what var I want to replace, only its position.

UPDATE 2:

vars = Concat(substring(vars ,1,:pos-1), substring(vars,:pos+2))

This does the trick but I forgot to mention the vars are not always |A and |B etc., but also |AB, |AC... So the position shouldn't always move by one character, but until the next |.

Body:
As @Zohar said, I agree your model is broken. Yet, if you want to achieve, here's an example with locate, substring, concat:

First locate the index of first |A the second |A will always be after it.

locate('|A','|A|B|A|D|G|B', locate('|A','|A|B|A|D|G|B')+1)

-- here +1 denotes after first index

Second find the sub-string after the second occurrence of |A

substring('|A|B|A|D|G|B',locate('|A','|A|B|A|D|G|B', locate('|A','|A|B|A|D|G|B')+1)+2)

--here +2 denotes the length of your string with is |A

Third find the sub-string before the second occurrence of |A

substring('|A|B|A|D|G|B',locate('|A','|A|B|A|D|G|B', 1,locate('|A','|A|B|A|D|G|B')+1)-1)

-- here -1 denotes any thing from the beginning to the charecter before |A

Fourth, concat the string after and before the second occurrence of |A

Concat(
  substring('|A|B|A|D|G|B',locate('|A','|A|B|A|D|G|B',1,locate('|A','|A|B|A|D|G|B')+1)-1),
  substring('|A|B|A|D|G|B',locate('|A','|A|B|A|D|G|B', locate('|A','|A|B|A|D|G|B')+1)+2)
)

EDIT 1: Like in your update if you ready know the position you can simply do:

vars = Concat(substring(vars ,1,:pos-1), substring(vars,:pos+2))

EDIT 2:

With your comment if you need to replace till next | you can do use both location and substring something like:

vars = CONCAT(SUBSTRING(vars ,1,:pos-1), SUBSTRING(vars,LOCATE('|',vars, :pos+1)))

DEMO


问:
How to parse json value from server, and display it in tableview cell
```<code>  "Names":[
  {
     "type":"Name",
     "id":{
        "type":"Point",
        "coordinates":[
           80.26483,
           13.08891
        ]
     },
     "properties":{
       "region":"Tamil Nadu",
        "region_gid":"whosonfirst:region:85672245",
        "county":"Chennai",
        "county_gid":"whosonfirst:county:890505403",
        "label":"Chennai, India"
     }
  },
  {
     "type":"Name",
     "id":{
        "type":"Point",
        "coordinates":[
           80.27847,
           13.08784
        ]
     },

 for(NSDictionary * dict in autocompletedata)
             {
                 Autodata *data = [[Autodata alloc]init];

                 NSMutableArray *coordinates =[dict valueForKey:@"geometry"];
                 NSMutableArray *propertiesarray = [dict valueForKey:@"properties"];

                 for(NSDictionary *properties_dict in propertiesarray)
                 {
                     data.searchterm = [properties_dict objectForKey:@"label"];
                 }
                 NSLog(@"searchterm%@",coordinates);
                  NSLog(@"coordinates%@",propertiesarray);

                 [autodataarray addObject:data];

             }
</code>```

Parse json value from server and display it in tableview cell.

I need to show the label and coordinates, region in tableview cell.

However, I have an error. I don't know how to parse it. I was thinking perhaps I can save the id and properties in different array, and from that I can get value of coordinates and label.

答:
success from webservice

```<code>yourArray=[dictDashboardData objectForKey:@"Names"];

[yourTableView reloadData];
</code>```

table veiw method

```<code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return yourArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

//...

NSDictionary *dictData = [yourArray objectAtIndex:indexPath.row];

cell.yourLabel.text=[dictData objectForKey:@"type"];
cell.yourLabel.text=[dictData objectForKey:@"id"];
    cell.yourLabel.text=[[dictData objectForKey:@"id"]objectForKey:@"type"];
cell.yourLabel.text=[[dictData objectForKey:@"id"]objectForKey:@"coordinates"];
cell.yourLabel.text=[dictData objectForKey:@"properties"];

return cell;
}
</code>```

Body:
  "Names":[
  {
     "type":"Name",
     "id":{
        "type":"Point",
        "coordinates":[
           80.26483,
           13.08891
        ]
     },
     "properties":{
       "region":"Tamil Nadu",
        "region_gid":"whosonfirst:region:85672245",
        "county":"Chennai",
        "county_gid":"whosonfirst:county:890505403",
        "label":"Chennai, India"
     }
  },
  {
     "type":"Name",
     "id":{
        "type":"Point",
        "coordinates":[
           80.27847,
           13.08784
        ]
     },

 for(NSDictionary * dict in autocompletedata)
             {
                 Autodata *data = [[Autodata alloc]init];

                 NSMutableArray *coordinates =[dict valueForKey:@"geometry"];
                 NSMutableArray *propertiesarray = [dict valueForKey:@"properties"];

                 for(NSDictionary *properties_dict in propertiesarray)
                 {
                     data.searchterm = [properties_dict objectForKey:@"label"];
                 }
                 NSLog(@"searchterm%@",coordinates);
                  NSLog(@"coordinates%@",propertiesarray);

                 [autodataarray addObject:data];

             }

Parse json value from server and display it in tableview cell.

I need to show the label and coordinates, region in tableview cell.

However, I have an error. I don't know how to parse it. I was thinking perhaps I can save the id and properties in different array, and from that I can get value of coordinates and label.

Body:
success from webservice

yourArray=[dictDashboardData objectForKey:@"Names"];

[yourTableView reloadData];

table veiw method

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return yourArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

//...

NSDictionary *dictData = [yourArray objectAtIndex:indexPath.row];

cell.yourLabel.text=[dictData objectForKey:@"type"];
cell.yourLabel.text=[dictData objectForKey:@"id"];
    cell.yourLabel.text=[[dictData objectForKey:@"id"]objectForKey:@"type"];
cell.yourLabel.text=[[dictData objectForKey:@"id"]objectForKey:@"coordinates"];
cell.yourLabel.text=[dictData objectForKey:@"properties"];

return cell;
}


问:
How to access form control from within ToString method of nested struct
I am building a small windows form application in C#.  Within the form code I define a public struct with a ToString method that must build part of its output from items in comboBoxes on the same form.  This doesn't sound like it should be difficult

```<code>public partial class Form1 : Form
{
 public struct OrderLineItem
    {
     string someString;
     int index;
     string ToString()
        {return someString + ActiveForm.sizeComboBox.Items[index].ToString();}
    }
}
</code>```

It complains that it cannot find a definition for sizeComboBox.  If I explicitly use the name of the form, it says an object reference is required for the static field...
I'm not quite sure what it means by that.  Using this.sizeComboBox refers to the struct, not the form.  Using just sizeComboBox, again, an object reference is required.

答:
Suppose the other form is Form2 you can cast ActiveForm to Form2:

```<code>var form2 = ActiveForm as Form2;
if (form2 != null) // form2 == null if ActiveForm is not of type Form2.
{
    form2.sizeComboBox...
}
</code>```

Edit:

Two notes.

Instead of getting ActiveForm it is better store form2 in a member variable in form1 when form2 is created.

You should encapsulate the getting of combobox values behind a property in Form2, like SelectedFooValue.

Body:
I am building a small windows form application in C#.  Within the form code I define a public struct with a ToString method that must build part of its output from items in comboBoxes on the same form.  This doesn't sound like it should be difficult

public partial class Form1 : Form
{
 public struct OrderLineItem
    {
     string someString;
     int index;
     string ToString()
        {return someString + ActiveForm.sizeComboBox.Items[index].ToString();}
    }
}

It complains that it cannot find a definition for sizeComboBox.  If I explicitly use the name of the form, it says an object reference is required for the static field...
I'm not quite sure what it means by that.  Using this.sizeComboBox refers to the struct, not the form.  Using just sizeComboBox, again, an object reference is required.

Body:
Suppose the other form is Form2 you can cast ActiveForm to Form2:

var form2 = ActiveForm as Form2;
if (form2 != null) // form2 == null if ActiveForm is not of type Form2.
{
    form2.sizeComboBox...
}

Edit:

Two notes.

Instead of getting ActiveForm it is better store form2 in a member variable in form1 when form2 is created.

You should encapsulate the getting of combobox values behind a property in Form2, like SelectedFooValue.


问:
Unexpected output with arrays
This is my script:

```<code>#!/usr/bin/perl
use strict;
use warnings;
use Web::Scraper;
use Data::Dumper;
use URI;
my $purlToScrape='http://www.natboard.edu.in/dnbfinal.php';
my $webdata = scraper {
      process 'td.noticeboard', "data[]" => 'TEXT';
  };
my $dnbnotices = $webdata->scrape(URI->new($purlToScrape));
my @noticeboard=$dnbnotices->{data};
print ref @noticeboard."\n\n";
print Dumper(@noticeboard);
print scalar @noticeboard."\n";
for my $notice ( @noticeboard ) {
    if ($notice) {
        print $notice."\n";
    }
}
print $noticeboard[1];
</code>```

Output:

```<code> $VAR1 = [
           'December - 2016 ',
           'DNB Final December -2016',
           '30th September, 2016',
           '',
           '',
           'JUNE - 2016 ',
           'DNB Final JUNE -2016',
           '15th May, 2016',
           '',
           '',
           'Dec - 2015 ',
           'DNB Final Dec -2015',
           '9th October, 2015',
           '',
           '',
           'June - 2015 ',
           'DNB Final June -2015',
           '6th May, 2015',
           '',
           '',
           'December - 2014 ',
           'DNB Final December - 2014',
           '30th September, 2014',
           '',
           ''
         ];
 1
 ARRAY(0x4521bd8)
 Use of uninitialized value in print at ./test1.pl line 21.
</code>```

Questions:

Why is the ref not printing out "ARRAY"?

Why is the array count shown as 1? It's not a single element array.

Why are the elements of the array not being printed out?

Why is $noticeboard[1] uninitialized?

答:
1- ref returns an empty string when called on something else than a ref. So when doing ref @xxx, you can't expect anything else than an empty string.

Furthermore, ref @noticeboard."\n\n" is the same as ref ((scalar @noticeboard)."\n\n"), which is ref "1\n\n", which returns an empty string.

2-3-4- scrape returned you an array reference, not an array. So when assigning it to an array (my @noticeboard=$dnbnotices->{data}), it went in the first element. (the fact that the array only has one element that is an array ref explains your question 2, 3 and 4).

Your script should be:

```<code>#!/usr/bin/perl
use strict;
use warnings;
use Web::Scraper;
use Data::Dumper;
use URI;
my $purlToScrape='http://www.natboard.edu.in/dnbfinal.php';
my $webdata = scraper {
      process 'td.noticeboard', "data[]" => 'TEXT';
  };
my $dnbnotices = $webdata->scrape(URI->new($purlToScrape));
my $noticeboard=$dnbnotices->{data};
print "ref=",ref($noticeboard),"\n\n";
print "dumper:",Dumper($noticeboard);
print "nb elements:",scalar @$noticeboard,"\n";
print "content:\n";
for my $notice ( @$noticeboard ) {
    if ($notice) {
        print "  ",$notice,"\n";
    }
}
print "first element:",$noticeboard->[1];
</code>```

Also, feel free to use say instead of print ... "\n", it can be more convenient. (you'll need use feature 'say' or use v5.10 or higher though).

If you need further references about references, see perlref and perlreftut.

Title: Unexpected output with arrays

Body:
This is my script:

#!/usr/bin/perl
use strict;
use warnings;
use Web::Scraper;
use Data::Dumper;
use URI;
my $purlToScrape='http://www.natboard.edu.in/dnbfinal.php';
my $webdata = scraper {
      process 'td.noticeboard', "data[]" => 'TEXT';
  };
my $dnbnotices = $webdata->scrape(URI->new($purlToScrape));
my @noticeboard=$dnbnotices->{data};
print ref @noticeboard."\n\n";
print Dumper(@noticeboard);
print scalar @noticeboard."\n";
for my $notice ( @noticeboard ) {
    if ($notice) {
        print $notice."\n";
    }
}
print $noticeboard[1];

Output:

 $VAR1 = [
           'December - 2016 ',
           'DNB Final December -2016',
           '30th September, 2016',
           '',
           '',
           'JUNE - 2016 ',
           'DNB Final JUNE -2016',
           '15th May, 2016',
           '',
           '',
           'Dec - 2015 ',
           'DNB Final Dec -2015',
           '9th October, 2015',
           '',
           '',
           'June - 2015 ',
           'DNB Final June -2015',
           '6th May, 2015',
           '',
           '',
           'December - 2014 ',
           'DNB Final December - 2014',
           '30th September, 2014',
           '',
           ''
         ];
 1
 ARRAY(0x4521bd8)
 Use of uninitialized value in print at ./test1.pl line 21.

Questions:

Why is the ref not printing out "ARRAY"?

Why is the array count shown as 1? It's not a single element array.

Why are the elements of the array not being printed out?

Why is $noticeboard[1] uninitialized?

Body:
1- ref returns an empty string when called on something else than a ref. So when doing ref @xxx, you can't expect anything else than an empty string.

Furthermore, ref @noticeboard."\n\n" is the same as ref ((scalar @noticeboard)."\n\n"), which is ref "1\n\n", which returns an empty string.

2-3-4- scrape returned you an array reference, not an array. So when assigning it to an array (my @noticeboard=$dnbnotices->{data}), it went in the first element. (the fact that the array only has one element that is an array ref explains your question 2, 3 and 4).

Your script should be:

#!/usr/bin/perl
use strict;
use warnings;
use Web::Scraper;
use Data::Dumper;
use URI;
my $purlToScrape='http://www.natboard.edu.in/dnbfinal.php';
my $webdata = scraper {
      process 'td.noticeboard', "data[]" => 'TEXT';
  };
my $dnbnotices = $webdata->scrape(URI->new($purlToScrape));
my $noticeboard=$dnbnotices->{data};
print "ref=",ref($noticeboard),"\n\n";
print "dumper:",Dumper($noticeboard);
print "nb elements:",scalar @$noticeboard,"\n";
print "content:\n";
for my $notice ( @$noticeboard ) {
    if ($notice) {
        print "  ",$notice,"\n";
    }
}
print "first element:",$noticeboard->[1];

Also, feel free to use say instead of print ... "\n", it can be more convenient. (you'll need use feature 'say' or use v5.10 or higher though).

If you need further references about references, see perlref and perlreftut.


问:
Fetching records that having their monthly period of creation date
I want to grab all the records that have been created ℕ month ago, exactly the same hour. (age of the records should be only ℕ months, 0 days, 0 hour)

ℕ = {1, 2, …}

for example if now() is 2016-11-15 13:15:00, any record having create_date as below is expected to be returned.

```<code>2010-11-15 13:15:00  -- different year
2016-02-15 13:15:00  -- different month
2016-11-15 13:46:23  -- different minute/seconds
2010-11-15 13:46:23  -- different year, month, minute and sec
</code>```

The best simple query I could think of was this:

```<code>SELECT  *
FROM    mytable
WHERE extract(day from age(now(), created_date)) = 0 -- same day any month ago
  AND extract(hour from age(now(), created_date)) = 0; -- same hour
</code>```

But the problem is there are some specific days that will be left out of the query. Such as when

```<code>created_date=2016-01-31 13:00:00
now() is 2016-02-28 13:00:00
</code>```

in this case, the age of the record is 28 days instead of 1 month; according to the age function in Postgresql.
So it will never be fetched neither at the end of Feb, or 1st of March.

Any idea about how this problem can be addressed in the most simple way is appreciated.

Here's some test data you can use to verify:

```<code>create table mytable (created_date timestamp, expected_records int);
truncate mytable;
insert into mytable (created_date, expected_records)  values
('2013-01-11 13:22:33', 2),
('2014-02-11 13:58:22', 2),
('2015-03-21 13:22:00', 1),
('2013-02-28 13:11:00', 5),
('2017-02-28 13:22:00', 5),
('2016-03-31 13:22:00', 5),
('2015-04-30 13:22:00', 5),
('2014-05-31 13:22:00', 5),
('2014-05-31 12:22:00', 1);
</code>```

the final SELECT query can be executed on any of these timstamps but should returns same amount of rows as expected_records states.
Also you can use 'some date'::timestamp instead of now() to fake time.

答:
You can workaround by getting the first month day - (1 day):

sample:

```<code>t=# create table so42(t timestamp);
CREATE TABLE
t=# insert into so42 select '2016-05-31 13:00:00';
INSERT 0 1
t=# insert into so42 select '2016-10-31 13:00:00';
INSERT 0 1
t=# insert into so42 select '2016-02-29 13:00:00';
INSERT 0 1
t=# insert into so42 select '2016-01-21 13:00:00';
INSERT 0 1
</code>```

join example:

```<code>t=# with ts as (
        select
                generate_series('2016-01-01 13:00:00'::timestamp,'2016-12-01'::date,'1 month'::interval)
                - '1 day'::interval
        lastday
)
select t
from so42
join ts on ts.lastday = t
;
          t
---------------------
 2016-02-29 13:00:00
 2016-05-31 13:00:00
 2016-10-31 13:00:00
(3 rows)
</code>```

also you can wrap it up into function with argument, smth like:

```<code>t=# create or replace function so45(_ts timestamp) returns table (lastday timestamp) as
$$
declare
 _start timestamp;
 _stop timestamp;
begin
 select date_trunc('year', _ts) + (_ts)::time +concat(extract(day from _ts),' days')::interval into _start;
 select date_trunc('year', _ts) + (_ts)::time +concat(extract(day from _ts),' days')::interval + '12 month'::interval into _stop;
return query with ts as (
        select
                generate_series(_start,_stop,'1 month'::interval)
                - '1 day'::interval
        lastday
)
select * from ts order by 1;
end;
$$ language plpgsql
;
CREATE FUNCTION
</code>```

join example:

```<code>t=# with ts as (select so45('2016-03-31 13:00:00'))
select t
from so42
join ts on ts.so45 = t
;
          t
---------------------
 2016-02-29 13:00:00
 2016-05-31 13:00:00
 2016-10-31 13:00:00
(3 rows)

t=# with ts as (select so45('2016-03-21 13:00:00'))
select t
from so42
join ts on ts.so45 = t
;
          t
---------------------
 2016-01-21 13:00:00
(1 row)
</code>```

Body:
I want to grab all the records that have been created ℕ month ago, exactly the same hour. (age of the records should be only ℕ months, 0 days, 0 hour)

ℕ = {1, 2, …}

for example if now() is 2016-11-15 13:15:00, any record having create_date as below is expected to be returned.

2010-11-15 13:15:00  -- different year
2016-02-15 13:15:00  -- different month
2016-11-15 13:46:23  -- different minute/seconds
2010-11-15 13:46:23  -- different year, month, minute and sec

The best simple query I could think of was this:

SELECT  *
FROM    mytable
WHERE extract(day from age(now(), created_date)) = 0 -- same day any month ago
  AND extract(hour from age(now(), created_date)) = 0; -- same hour

But the problem is there are some specific days that will be left out of the query. Such as when

created_date=2016-01-31 13:00:00
now() is 2016-02-28 13:00:00

in this case, the age of the record is 28 days instead of 1 month; according to the age function in Postgresql.
So it will never be fetched neither at the end of Feb, or 1st of March.

Any idea about how this problem can be addressed in the most simple way is appreciated.

Here's some test data you can use to verify:

create table mytable (created_date timestamp, expected_records int);
truncate mytable;
insert into mytable (created_date, expected_records)  values
('2013-01-11 13:22:33', 2),
('2014-02-11 13:58:22', 2),
('2015-03-21 13:22:00', 1),
('2013-02-28 13:11:00', 5),
('2017-02-28 13:22:00', 5),
('2016-03-31 13:22:00', 5),
('2015-04-30 13:22:00', 5),
('2014-05-31 13:22:00', 5),
('2014-05-31 12:22:00', 1);

the final SELECT query can be executed on any of these timstamps but should returns same amount of rows as expected_records states.
Also you can use 'some date'::timestamp instead of now() to fake time.

Body:
You can workaround by getting the first month day - (1 day):

sample:

t=# create table so42(t timestamp);
CREATE TABLE
t=# insert into so42 select '2016-05-31 13:00:00';
INSERT 0 1
t=# insert into so42 select '2016-10-31 13:00:00';
INSERT 0 1
t=# insert into so42 select '2016-02-29 13:00:00';
INSERT 0 1
t=# insert into so42 select '2016-01-21 13:00:00';
INSERT 0 1

join example:

t=# with ts as (
        select
                generate_series('2016-01-01 13:00:00'::timestamp,'2016-12-01'::date,'1 month'::interval)
                - '1 day'::interval
        lastday
)
select t
from so42
join ts on ts.lastday = t
;
          t
---------------------
 2016-02-29 13:00:00
 2016-05-31 13:00:00
 2016-10-31 13:00:00
(3 rows)

also you can wrap it up into function with argument, smth like:

t=# create or replace function so45(_ts timestamp) returns table (lastday timestamp) as
$$
declare
 _start timestamp;
 _stop timestamp;
begin
 select date_trunc('year', _ts) + (_ts)::time +concat(extract(day from _ts),' days')::interval into _start;
 select date_trunc('year', _ts) + (_ts)::time +concat(extract(day from _ts),' days')::interval + '12 month'::interval into _stop;
return query with ts as (
        select
                generate_series(_start,_stop,'1 month'::interval)
                - '1 day'::interval
        lastday
)
select * from ts order by 1;
end;
$$ language plpgsql
;
CREATE FUNCTION

join example:

t=# with ts as (select so45('2016-03-31 13:00:00'))
select t
from so42
join ts on ts.so45 = t
;
          t
---------------------
 2016-02-29 13:00:00
 2016-05-31 13:00:00
 2016-10-31 13:00:00
(3 rows)

t=# with ts as (select so45('2016-03-21 13:00:00'))
select t
from so42
join ts on ts.so45 = t
;
          t
---------------------
 2016-01-21 13:00:00
(1 row)


问:
Issue when implementing "Resource Owner Password Credentials Grant"
I try to implement "Resource Owner Password Credentials Grant" on an Azure AD scenario.

I have a web api (DemoWebApi) and a console (DemoConsole) declared as native application.
I was able to make "Authorization Code Grant" and "Client Credentials Grant" working, but I encounter some issue with "Resource Owner Password Credentials Grant".

First I read this:
http://www.cloudidentity.com/blog/2014/07/08/using-adal-net-to-authenticate-users-via-usernamepassword/

and more especially the NO MSA section.

So I created a user in my Azure AD tenant, now I get this error message:

The user or administrator has not consented to use the application with ID 'bd274da6-80f2-458a-b74b-...'. Send an interactive authorization request for this user and resource.

I can't figure out what I should do

This is my source code:

```<code>string authority = "https://login.microsoftonline.com/7dda5ce2-2fb6-4f82-bc27-...";

AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);
UserPasswordCredential credentials = new UserPasswordCredential(login, password);
AuthenticationResult res = await authenticationContext.AcquireTokenAsync(webApiClientId, consoleClientId, credentials);
</code>```

答:
You need to provide more information to help us reproduce the issue , for example , how do you register the app ,using azure portal ,powershell or visual studio.What is the user type of the new added user and how do you add that user .

Users do not have any opportunity of providing consent if username & password are passed directly. To fix that issue, you could try to grant permissions for that api in portal(better login with administrator account) :

Body:
I try to implement "Resource Owner Password Credentials Grant" on an Azure AD scenario.

I have a web api (DemoWebApi) and a console (DemoConsole) declared as native application.
I was able to make "Authorization Code Grant" and "Client Credentials Grant" working, but I encounter some issue with "Resource Owner Password Credentials Grant".

First I read this:
http://www.cloudidentity.com/blog/2014/07/08/using-adal-net-to-authenticate-users-via-usernamepassword/

and more especially the NO MSA section.

So I created a user in my Azure AD tenant, now I get this error message:

The user or administrator has not consented to use the application with ID 'bd274da6-80f2-458a-b74b-...'. Send an interactive authorization request for this user and resource.

I can't figure out what I should do

This is my source code:

string authority = "https://login.microsoftonline.com/7dda5ce2-2fb6-4f82-bc27-...";

AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);
UserPasswordCredential credentials = new UserPasswordCredential(login, password);
AuthenticationResult res = await authenticationContext.AcquireTokenAsync(webApiClientId, consoleClientId, credentials);


问:
How does cloud foundry's domain and DNS domain connected?
When I read cloud foundry document about Domains, it mentions that the term of "Domain" differs from its common use and is specific to Cloud Foundry.

THen when I am using PWS, cf domains shows:

```<code>name            status   type
cfapps.io       shared
cf-tcpapps.io   shared   tcp
</code>```

I assume the domains here are Cloud foundry domains. I can access my app by below URL:

```<code>https://browser-kissable-dizziness.cfapps.io
</code>```

here "cfapps.io" I guess it's a DNS domain name because it's on the public internet.

how do the cloud foundry domain and the DNS domain name connect? or is there a connection between them? or they are just two things which have the same name?

if I want to have multiple share HTTP cloud foundry domains? I can use cf create-shared-domain shared-domain.example.com to create one, but how can I make it usable by public internet?

Guess I want to understand the basic knowledge about how to make a cloud foundry instance accessible from the internet.

答:
They are two things with the same name. If you want to use shared-domain.example.com, you need to obtain the domain and register it yourself with a public DNS service.

You point this domain to cfapps.io, so your client requests are directed to the same CF load balancer and/or routers. The routers know to direct requests to that domain to your app when you have mapped a route with that domain to your app.

Body:
When I read cloud foundry document about Domains, it mentions that the term of "Domain" differs from its common use and is specific to Cloud Foundry.

THen when I am using PWS, cf domains shows:

name            status   type
cfapps.io       shared
cf-tcpapps.io   shared   tcp

I assume the domains here are Cloud foundry domains. I can access my app by below URL:

https://browser-kissable-dizziness.cfapps.io

here "cfapps.io" I guess it's a DNS domain name because it's on the public internet.

how do the cloud foundry domain and the DNS domain name connect? or is there a connection between them? or they are just two things which have the same name?

if I want to have multiple share HTTP cloud foundry domains? I can use cf create-shared-domain shared-domain.example.com to create one, but how can I make it usable by public internet?

Guess I want to understand the basic knowledge about how to make a cloud foundry instance accessible from the internet.


问:
Is It mandatory to check in Bin and Obj files to SVN or any other repository?
I am using SVN as my repository. Is it mandatory to commit Obj and Bin files to SVN or other repositories. As per my knowledge those are not required because when we build the solution Bin and Obj files will come automatically. Please correct me if I am wrong.

Thanks in advance.

答:
Yes you are absolutely correct. Don't check-in bin or obj folders. Exclude them from check-in list.

Once source code is taken and build locally those debug files and required dll's will get generated automatically


问:
How to get href value of active tab inside li list?
How to get href value of profileTab_51069

  My Home

PSC:51073

PSC:51069

```

答:
You can use id of ul element along with class selector active to find descendant child li element having class active:</p>

```<code>$('#TabView li.active').text()
</code>```

Body:
You can use id of ul element along with class selector active to find descendant child li element having class active:

$('#TabView li.active').text()


答:
You can try use $("#TabView li.active a").html() It takes the li that has the class active and get the value of the link

console.log($("#TabView li.active a").html())

// Example code
$("#TabView li").click(function() {
  if (!$(this).hasClass("active")) {
    $("#TabView li.active").removeClass("active")
    $(this).addClass("active")
    console.log($(this).find("a").html())
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="TabView" class="nav nav-tabs">
  <li id="myhomeTab" class="">  My Home    </li>
  <li id="2" class="">PSC:51073 </li>
  <li id="3" class="active">PSC:51069</li>
</ul></code>```

Title: How to get href value of active tab inside li list?

Body:
How to get href value of profileTab_51069

  My Home

PSC:51073

PSC:51069

Body:
You can try use $("#TabView li.active a").html() It takes the li that has the class active and get the value of the link

console.log($("#TabView li.active a").html())

// Example code
$("#TabView li").click(function() {
  if (!$(this).hasClass("active")) {
    $("#TabView li.active").removeClass("active")
    $(this).addClass("active")
    console.log($(this).find("a").html())
  }
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="TabView" class="nav nav-tabs">
  <li id="myhomeTab" class=""><a href="#home" class="" data-toggle="tab">&nbsp;&nbsp;My Home&nbsp;&nbsp;&nbsp;&nbsp;</a></li>
  <li id="2" class=""><a href="#profileTab_51073" data-toggle="tab">PSC:51073 </a></li>
  <li id="3" class="active"><a href="#profileTab_51069" data-toggle="tab">PSC:51069</a></li>
</ul>


问:
Building android app with javascript/angular
I know you need to use Java to build native applications for Android, however what is the best way to build websites and (or) native apps using javascript frameworks like Angular?</p>

答: You can try Ionic Framework. It is one of the most popular Javascript-based framework for iOS/ Android App Development. </p>


问:
NoReverseMatch in 'a href' HTML link
I'm trying to make a link that redirects to another page in my django application, I have the view, I have the url and I have the template, all are ok in my eyes, but when I try to 'href' the page to do the link I get the Following error:

Reverse for 'views.candidate_detail' with arguments '()' and keyword
  arguments '{'pk': ''}' not found. 0 pattern(s) tried: []

views.py

```<code>from django.shortcuts import render, get_object_or_404
from .models import Candidate, Criterion, Evaluation
from django import forms
from .forms import CandForm
from .forms import EvalForm
from .forms import TestForm
from django.shortcuts import redirect
from django.db import IntegrityError

def canditate_list(request):
    candidates = Candidate.objects.all()
    evaluation = Evaluation.objects.all()

    ######################## Ponho todos os candidatos e suas respectivas médias em um array em formato dict({Candidato:N})
    sum = 0
    cont = 1
    med = 0
    lista = []
    for cand in candidates:
        cont = 0
        sum = 0
        med = 0
        for e in evaluation:
            if cand == e.candidate:
                sum += e.score
                cont += 1
        if cont > 0:
            med = sum / cont

        data = {str(cand):med}              ## a Key recebe o candidato no formato string
        lista += [data]

    ##### passo os dicionários contidos na lista anterior para outra lista convertendo-os em string
    lista2 = []
    for l in lista:
        lista2 += [str(l)]

    lista2 = [re.sub(r'[^\w\d.:]+',"",e) for e in lista2]

    eval_cand_list = []                                     #aqui guarda uma lista com os FK candidates convertidos p/ str
    context = {
        'candidates': candidates,
        'evaluation': evaluation,
        'lista2':lista2
    }
    return render(request, 'app/candidate_list.html',context)

def candidate_detail(request, pk):
    candidate = get_object_or_404(Candidate, pk=pk)
    c_name = candidate.name                                 #pega o nome (string) do candidato
    c1 = Evaluation.objects.all()                           #guarda tds Evaluation na variavel
    scores = []                                             #declara a array que vai receber as notas
    for c in c1:
        cand = str(c.candidate)                             #guarda o nome do candidato do Evaluation atual
        if cand == c_name:                                  #confere se o Evaluation atual corresponde ao candidate atual(pk)
            scores += [c.score]

    soma = 0                                                #variavel que guardara a soma declarada
    for s in scores:
        soma += s                                           #faz a soma dos scores

    average = 0
    if len(scores) > 0:
        average = soma/len(scores)                              #tira a média

    context = {
        'candidate': candidate,
        'average': average,
    }

    return render(request, 'app/candidate_detail.html', context)
</code>```

urls.py

```<code>from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.canditate_list, name='canditate_list'),
    url(r'^candidato/(?P<pk>[0-9]+)/$', views.candidate_detail, name='candidate_detail'),
    url(r'^cadastrar/$', views.register, name='register'),  # <--! o cadastro fica num link independete
    url(r'^grid/$', views.grid, name='grid'),
    url(r'^candidato/[0-9]+/avaliacao/$', views.evaluation, name='evaluate'),

]
</code>```

template html:

```<code>{% load staticfiles %}
{% load mathfilters %}
<!DOCTYPE html>
<html>
<head>
    <title>Lista de candidatos</title>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    <link href="https://fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css">
    <link href="{% static 'css/app.css' %}" rel="stylesheet">
</head>
<body>
    <h1 class="h1t">Lista de Candidatos</h1>
    {% for l in lista2 %}
        <p class="tr"><a href="{% url 'views.candidate_detail' pk=post.pk %}">{{l}}</a></p>
    {% endfor %}

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

答:
You should iterate over the candidates QuerySet instead of the lista2 list. Then you can do it like this:

```<code>{% for candidate in candidates %}
    <p class="tr">
        <a href="{% url 'candidate_detail' candidate.pk %}">{{ candidate }}</a>
    </p>
{% endfor %}
</code>```

Title: NoReverseMatch in 'a href' HTML link

Body:
I'm trying to make a link that redirects to another page in my django application, I have the view, I have the url and I have the template, all are ok in my eyes, but when I try to 'href' the page to do the link I get the Following error:

Reverse for 'views.candidate_detail' with arguments '()' and keyword
  arguments '{'pk': ''}' not found. 0 pattern(s) tried: []

views.py

from django.shortcuts import render, get_object_or_404
from .models import Candidate, Criterion, Evaluation
from django import forms
from .forms import CandForm
from .forms import EvalForm
from .forms import TestForm
from django.shortcuts import redirect
from django.db import IntegrityError

def canditate_list(request):
    candidates = Candidate.objects.all()
    evaluation = Evaluation.objects.all()

    ######################## Ponho todos os candidatos e suas respectivas médias em um array em formato dict({Candidato:N})
    sum = 0
    cont = 1
    med = 0
    lista = []
    for cand in candidates:
        cont = 0
        sum = 0
        med = 0
        for e in evaluation:
            if cand == e.candidate:
                sum += e.score
                cont += 1
        if cont > 0:
            med = sum / cont

        data = {str(cand):med}              ## a Key recebe o candidato no formato string
        lista += [data]

    ##### passo os dicionários contidos na lista anterior para outra lista convertendo-os em string
    lista2 = []
    for l in lista:
        lista2 += [str(l)]

    lista2 = [re.sub(r'[^\w\d.:]+',"",e) for e in lista2]

    eval_cand_list = []                                     #aqui guarda uma lista com os FK candidates convertidos p/ str
    context = {
        'candidates': candidates,
        'evaluation': evaluation,
        'lista2':lista2
    }
    return render(request, 'app/candidate_list.html',context)

def candidate_detail(request, pk):
    candidate = get_object_or_404(Candidate, pk=pk)
    c_name = candidate.name                                 #pega o nome (string) do candidato
    c1 = Evaluation.objects.all()                           #guarda tds Evaluation na variavel
    scores = []                                             #declara a array que vai receber as notas
    for c in c1:
        cand = str(c.candidate)                             #guarda o nome do candidato do Evaluation atual
        if cand == c_name:                                  #confere se o Evaluation atual corresponde ao candidate atual(pk)
            scores += [c.score]

    soma = 0                                                #variavel que guardara a soma declarada
    for s in scores:
        soma += s                                           #faz a soma dos scores

    average = 0
    if len(scores) > 0:
        average = soma/len(scores)                              #tira a média

    context = {
        'candidate': candidate,
        'average': average,
    }

    return render(request, 'app/candidate_detail.html', context)

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.canditate_list, name='canditate_list'),
    url(r'^candidato/(?P<pk>[0-9]+)/$', views.candidate_detail, name='candidate_detail'),
    url(r'^cadastrar/$', views.register, name='register'),  # <--! o cadastro fica num link independete
    url(r'^grid/$', views.grid, name='grid'),
    url(r'^candidato/[0-9]+/avaliacao/$', views.evaluation, name='evaluate'),

]

template html:

{% load staticfiles %}
{% load mathfilters %}
<!DOCTYPE html>

    <title>Lista de candidatos</title>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    <link href="https://fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css">
    <link href="{% static 'css/app.css' %}" rel="stylesheet">

Lista de Candidatos

    {% for l in lista2 %}

{{l}}

    {% endfor %}

Body:
You should iterate over the candidates QuerySet instead of the lista2 list. Then you can do it like this:

{% for candidate in candidates %}
    <p class="tr">
        <a href="{% url 'candidate_detail' candidate.pk %}">{{ candidate }}</a>
    </p>
{% endfor %}


问:
Subprocess with ruby
I try to find the good way to call subprocess with ruby.I want to launch a new second terminal with a commande inside and then execute a new command after the last one on the first terminal.I want to do the same in ruby like this python short code.

```<code>import os
import subprocess
htop = "x-terminal-emulator -e 'bash -c \"htop; exec bash\"'"
ls = "ls"
p = subprocess.Popen(htop, shell=True, stderr=subprocess.PIPE)
p1 = subprocess.Popen(ls, shell=True, stderr=subprocess.PIPE)
</code>```

here htop is started on second terminal and then ls on the first, with ruby im stuck at htop and after ls is not started.Here is my ruby code

```<code>stdout, stdeerr, status = Open3.capture3("x-terminal-emulator -e bash -c htop")
sleep 2
system "iwconfig wlan0"
</code>```

答:
Solved by using fork

```<code>fork { exec "x-terminal-emulator -e bash -c htop" }
sleep 2
    system "ls"
</code>```

I will come back soon im learning ruby.

Title: Subprocess with ruby

Body:
I try to find the good way to call subprocess with ruby.I want to launch a new second terminal with a commande inside and then execute a new command after the last one on the first terminal.I want to do the same in ruby like this python short code.

import os
import subprocess
htop = "x-terminal-emulator -e 'bash -c \"htop; exec bash\"'"
ls = "ls"
p = subprocess.Popen(htop, shell=True, stderr=subprocess.PIPE)
p1 = subprocess.Popen(ls, shell=True, stderr=subprocess.PIPE)

here htop is started on second terminal and then ls on the first, with ruby im stuck at htop and after ls is not started.Here is my ruby code

stdout, stdeerr, status = Open3.capture3("x-terminal-emulator -e bash -c htop")
sleep 2
system "iwconfig wlan0"

Body:
Solved by using fork

fork { exec "x-terminal-emulator -e bash -c htop" }
sleep 2
    system "ls"

I will come back soon im learning ruby.


答:
```<code>    public partial class Form1 : Form
{
    internal static Form1 ActiveForm { get; set; }

    public Form1()
    {
        InitializeComponent();
        ActiveForm = this;
    }

    public struct OrderLineItem
    {
        public override string ToString()
        {
            return ActiveForm.sizeComboBox.Items[index].ToString();
        }
    }
</code>```

However note that this is not the correct approach. Maybe you can post what you are trying to accomplish and we can help?

Title: How to access form control from within ToString method of nested struct

Body:
    public partial class Form1 : Form
{
    internal static Form1 ActiveForm { get; set; }

    public Form1()
    {
        InitializeComponent();
        ActiveForm = this;
    }

    public struct OrderLineItem
    {
        public override string ToString()
        {
            return ActiveForm.sizeComboBox.Items[index].ToString();
        }
    }

However note that this is not the correct approach. Maybe you can post what you are trying to accomplish and we can help?


问:
ERROR: Make sure the NICT wordnet db is stored in classpath at: /wnjpn.db
I am trying to calculate the similarity between two words for my application. I have used the wordnet dictionary. While executing the code it requires wnjpn.db in the class path. When I executing the code as a java application it works fine when I add  this db file to src folder in app, but while I trying to run from web page it gives error that

```<code> ERROR: Make sure the NICT wordnet db is stored in classpath at: /wnjpn.db
</code>```

sample code look like

```<code>import edu.cmu.lti.lexical_db.ILexicalDatabase;
import edu.cmu.lti.lexical_db.NictWordNet;
import edu.cmu.lti.ws4j.RelatednessCalculator;
import edu.cmu.lti.ws4j.impl.HirstStOnge;
import edu.cmu.lti.ws4j.impl.JiangConrath;
import edu.cmu.lti.ws4j.impl.LeacockChodorow;
import edu.cmu.lti.ws4j.impl.Lesk;
import edu.cmu.lti.ws4j.impl.Lin;
import edu.cmu.lti.ws4j.impl.Path;
import edu.cmu.lti.ws4j.impl.Resnik;
import edu.cmu.lti.ws4j.impl.WuPalmer;
import edu.cmu.lti.ws4j.util.WS4JConfiguration;

 public class similarity {

public  static ILexicalDatabase db =  new NictWordNet();

/*
//available options of metrics
private static RelatednessCalculator[] rcs = { new HirstStOnge(db),
        new LeacockChodorow(db), new Lesk(db), new WuPalmer(db),
        new Resnik(db), new JiangConrath(db), new Lin(db), new Path(db) };
*/
public  static double compute(String word1, String word2) {
    WS4JConfiguration.getInstance().setMFS(true);
    double s = new WuPalmer(db).calcRelatednessOfWords(word1, word2);
    return s;
}

public static void main(String[] args) {
    String[] words = {"add", "get", "filter", "remove", "check", "find", "collect", "create"};

            double distance = compute("OTHER OFFENSE","PROSTITUTION");
            System.out.println( distance);

}
</code>```

}

答:
Found Solution.

add--> Folder to the Java Resources --->Some Folder

Add wnjpn.db to that folder-->go to the project properties--> Java Build Path

Image 1

Click to add Folder--> select folder in your wnjpn.db file is stored--> click Ok

image 2

It will automatically load wnjpn.db file at runtime. It works for me.

Body:
I am trying to calculate the similarity between two words for my application. I have used the wordnet dictionary. While executing the code it requires wnjpn.db in the class path. When I executing the code as a java application it works fine when I add  this db file to src folder in app, but while I trying to run from web page it gives error that

 ERROR: Make sure the NICT wordnet db is stored in classpath at: /wnjpn.db

sample code look like

import edu.cmu.lti.lexical_db.ILexicalDatabase;
import edu.cmu.lti.lexical_db.NictWordNet;
import edu.cmu.lti.ws4j.RelatednessCalculator;
import edu.cmu.lti.ws4j.impl.HirstStOnge;
import edu.cmu.lti.ws4j.impl.JiangConrath;
import edu.cmu.lti.ws4j.impl.LeacockChodorow;
import edu.cmu.lti.ws4j.impl.Lesk;
import edu.cmu.lti.ws4j.impl.Lin;
import edu.cmu.lti.ws4j.impl.Path;
import edu.cmu.lti.ws4j.impl.Resnik;
import edu.cmu.lti.ws4j.impl.WuPalmer;
import edu.cmu.lti.ws4j.util.WS4JConfiguration;

 public class similarity {

public  static ILexicalDatabase db =  new NictWordNet();

/*
//available options of metrics
private static RelatednessCalculator[] rcs = { new HirstStOnge(db),
        new LeacockChodorow(db), new Lesk(db), new WuPalmer(db),
        new Resnik(db), new JiangConrath(db), new Lin(db), new Path(db) };
*/
public  static double compute(String word1, String word2) {
    WS4JConfiguration.getInstance().setMFS(true);
    double s = new WuPalmer(db).calcRelatednessOfWords(word1, word2);
    return s;
}

public static void main(String[] args) {
    String[] words = {"add", "get", "filter", "remove", "check", "find", "collect", "create"};

            double distance = compute("OTHER OFFENSE","PROSTITUTION");
            System.out.println( distance);

}

}