问:
How do I elegantly use a pure random number generator inside a recursive function?
In my game dungeon generator made in Scala, I have a recursive function that generates a "tree-like" structure. It takes in a pure random number generator (RNG), and outputs a random tree and a new random number generator.

My issue is that because it's recursive, and every time my function branches out, I don't want to pass in the same RNG to both branches, so I have to keep an inner var inside my outer function.

An excerpt from my code:

```<code>  def generate(parameters: RandomBSPTreeParameters)(rng: RNG): (BSPTree, RNG) = {
    var varRng: RNG = rng

    def inner(size: Size, verticalSplit: Boolean): BSPTree = {

      def verticalBranch = {
        val leeway = size.height - parameters.minLeafEdgeLength.value * 2
        val (topHeightOffset, newRng) = RNG.nextPositiveInt(leeway)(varRng)
        varRng = newRng
        val topHeight = parameters.minLeafEdgeLength.value + topHeightOffset
        VerticalBranch(
          inner(Size(size.width, topHeight), verticalSplit = false),
          inner(Size(size.width, size.height - topHeight), verticalSplit = false)
        )
      }

      def horizontalBranch = {
        val leeway = size.width - parameters.minLeafEdgeLength.value * 2
        val (topWidthOffset, newRng) = RNG.nextPositiveInt(leeway)(varRng)
        varRng = newRng
        val leftWidth = parameters.minLeafEdgeLength.value + topWidthOffset
        HorizontalBranch(
          inner(Size(leftWidth, size.height), verticalSplit = true),
          inner(Size(size.width  - leftWidth, size.height), verticalSplit = true)
        )
      }

      def randomOrientationBranch = {
        val (splitVertically, newRng) = RNG.nextBoolean(varRng)
        varRng = newRng

        if (splitVertically)
          verticalBranch
        else
          horizontalBranch
      }

      if(size.surface > parameters.minLeafSurface)
        size.shape match {
          case Square if size.width > parameters.minLeafEdgeLength.value * 2 => randomOrientationBranch
          case SkewedHorizontally if size.width > parameters.minLeafEdgeLength.value * 2  => horizontalBranch
          case SkewedVertically if size.height > parameters.minLeafEdgeLength.value * 2 => verticalBranch
        }
      else Leaf(size)
    }

    val (firstSplitIsVertical, newRng) = RNG.nextBoolean(varRng)
    varRng = newRng

    val tree = inner(parameters.size, firstSplitIsVertical)
    (tree, varRng)
  }
</code>```

Can somebody guide me in the right direction for eliminating the need to keep the var varRng: RNG in this function, and make it state-less.

答:
Firstly, even if you get rid of the var, your function is still going to be side-effectful. The reason for that is that nextPositiveInt has a side-effect of generating random number. Even if nextPositiveInt takes numbers from immutable pre-generated collection (so, no IO) it has to increment internal position counter every-time you call it.

Secondly, if numbers are "pure" random, which is not really possible, IMO, but let's say they're at least i.i.d (independently and identically distributed) - it doesn't make any sense to pass different generator to a different branch as even if you pass a same generator - random data between branches still wouldn't correlate. So you can just use same rng everywhere.

If it's not the case and we're talking about pseudo-randomness (that could auto-correlate potentially) with a different seed per every case, just pass rng as a parameter for your inner functions, like :

```<code> def verticalBranch(vrng: RNG) = ...
</code>```

I'd also notice that you're not really propagating rng through a left (or right branch) - you'd have two vars then lrng, rrng, which in its turn would mean that you don't need vars at all - they could be vals:

```<code> val lRng = newRng()
 val rRng = newRng()

 def verticalBranch = {
    ...
    val (topHeightOffset, newRng) = RNG.nextPositiveInt(leeway)(lRng)
 }

 def horizontalBranch = {
    ...
    val (topHeightOffset, newRng) = RNG.nextPositiveInt(leeway)(rRng)
 }
</code>```

How to encapsulate side-effects better?

You can represent lRng, rRng and other necessary generators as Iterators:

```<code> val lRngGen = Iterator.continually(RNG.nextPositiveInt(rRng))
</code>```

and use something like:

```<code> case class Accumulator(size: Size, tree: BSPTree)

 val vert = (lRngGen zip rRngGen).foldLeft(Accumulator(parameters.size, emptyTree)(createNode)`

 def createNode(rng: (Int, Int), acc: Accumulator): Accumulator = {
    acc.size.shape match ...
 }
</code>```

However, it requires to completely rethink/rewrite your code in terms of foldLeft instead of explicit recursion.

Body:
In my game dungeon generator made in Scala, I have a recursive function that generates a "tree-like" structure. It takes in a pure random number generator (RNG), and outputs a random tree and a new random number generator.

My issue is that because it's recursive, and every time my function branches out, I don't want to pass in the same RNG to both branches, so I have to keep an inner var inside my outer function.

An excerpt from my code:

  def generate(parameters: RandomBSPTreeParameters)(rng: RNG): (BSPTree, RNG) = {
    var varRng: RNG = rng

    def inner(size: Size, verticalSplit: Boolean): BSPTree = {

      def verticalBranch = {
        val leeway = size.height - parameters.minLeafEdgeLength.value * 2
        val (topHeightOffset, newRng) = RNG.nextPositiveInt(leeway)(varRng)
        varRng = newRng
        val topHeight = parameters.minLeafEdgeLength.value + topHeightOffset
        VerticalBranch(
          inner(Size(size.width, topHeight), verticalSplit = false),
          inner(Size(size.width, size.height - topHeight), verticalSplit = false)
        )
      }

      def horizontalBranch = {
        val leeway = size.width - parameters.minLeafEdgeLength.value * 2
        val (topWidthOffset, newRng) = RNG.nextPositiveInt(leeway)(varRng)
        varRng = newRng
        val leftWidth = parameters.minLeafEdgeLength.value + topWidthOffset
        HorizontalBranch(
          inner(Size(leftWidth, size.height), verticalSplit = true),
          inner(Size(size.width  - leftWidth, size.height), verticalSplit = true)
        )
      }

      def randomOrientationBranch = {
        val (splitVertically, newRng) = RNG.nextBoolean(varRng)
        varRng = newRng

        if (splitVertically)
          verticalBranch
        else
          horizontalBranch
      }

      if(size.surface > parameters.minLeafSurface)
        size.shape match {
          case Square if size.width > parameters.minLeafEdgeLength.value * 2 => randomOrientationBranch
          case SkewedHorizontally if size.width > parameters.minLeafEdgeLength.value * 2  => horizontalBranch
          case SkewedVertically if size.height > parameters.minLeafEdgeLength.value * 2 => verticalBranch
        }
      else Leaf(size)
    }

    val (firstSplitIsVertical, newRng) = RNG.nextBoolean(varRng)
    varRng = newRng

    val tree = inner(parameters.size, firstSplitIsVertical)
    (tree, varRng)
  }

Can somebody guide me in the right direction for eliminating the need to keep the var varRng: RNG in this function, and make it state-less.

Body:
Firstly, even if you get rid of the var, your function is still going to be side-effectful. The reason for that is that nextPositiveInt has a side-effect of generating random number. Even if nextPositiveInt takes numbers from immutable pre-generated collection (so, no IO) it has to increment internal position counter every-time you call it.

Secondly, if numbers are "pure" random, which is not really possible, IMO, but let's say they're at least i.i.d (independently and identically distributed) - it doesn't make any sense to pass different generator to a different branch as even if you pass a same generator - random data between branches still wouldn't correlate. So you can just use same rng everywhere.

If it's not the case and we're talking about pseudo-randomness (that could auto-correlate potentially) with a different seed per every case, just pass rng as a parameter for your inner functions, like :

 def verticalBranch(vrng: RNG) = ...

I'd also notice that you're not really propagating rng through a left (or right branch) - you'd have two vars then lrng, rrng, which in its turn would mean that you don't need vars at all - they could be vals:

 val lRng = newRng()
 val rRng = newRng()

 def verticalBranch = {
    ...
    val (topHeightOffset, newRng) = RNG.nextPositiveInt(leeway)(lRng)
 }

 def horizontalBranch = {
    ...
    val (topHeightOffset, newRng) = RNG.nextPositiveInt(leeway)(rRng)
 }

How to encapsulate side-effects better?

You can represent lRng, rRng and other necessary generators as Iterators:

 val lRngGen = Iterator.continually(RNG.nextPositiveInt(rRng))

and use something like:

 case class Accumulator(size: Size, tree: BSPTree)

 val vert = (lRngGen zip rRngGen).foldLeft(Accumulator(parameters.size, emptyTree)(createNode)`

 def createNode(rng: (Int, Int), acc: Accumulator): Accumulator = {
    acc.size.shape match ...
 }

However, it requires to completely rethink/rewrite your code in terms of foldLeft instead of explicit recursion.


来源: stackexchange

问:
How to reset time limit on Celery Task
I have no experience with Celery so I'm looking into it if my use case is solvable in Celery.

The client will submit a job to Celery, this job will be executed in CeleryTask. Then the client has to send keepalive every 30 seconds to keep this job active. Once the job is not refreshed by keepalive message, the job will be cancelled.

I can think of two solutions:

Each job-task created will have hard time limit of 30s. When client sends keepalive the router will send message to relevant worker to reset the hard time limit.

Each job-task will have no time limit. For each job-task there will be another special watchdog task launched. The watchdog task will be launched with delay of 30s. If new keepalive arrives from the client the watchdog task is cancelled and recreated. Again with delay of 30 seconds. If the watchdog is executed, it will kill the job-task, thus eliminating it from system.

The 1. is much simpler, but I'm not sure how to reset the task timelimit. The solution 2. seems more correct, but I'm afraid there will be various race conditions. The watchdog task should be probably running in separate queue reserved for watchdogs only.

How is something like this possible? Even one of my solution or some other.

答:
In my understanding, you just want to have a middleware(one to receive  keepalive, on to control task), then this link will help youcelery.app.control.Control.terminate.

Get task_id of task when apply_async (destination or all workers)

listen the keepalive from client

if time limit arrived and no keepalive, terminate task app.control.terminate(task_id, reply=True)

ContentLicense: CC BY-SA 3.0

Title: How to reset time limit on Celery Task


问:
Sorting table with PHP
How to sort table in php?

I have code like this

```<code><th>$ATTT[0]</th>
        <td>".number_format($HA[0], 3, '.', ',')."</td>
        <td class='jumlah'>1</td>
        </tr>
        <th>$ATTT[1]</th>
        <td>".number_format($HA[1], 3, '.', ',')."</td>
        <td class='jumlah'>2</td>
</code>```

I want to sort column 2, so when column 2 sorting column 1 will follow column 2

Sorry for my English, I tried my best :D

答:
In that case there are two options, use order by in your query so that you get the data in some order or use JQUERY datatable plug-in which have so many features like sorting, searching, pagination etc. It can be used like:

```<code>$(document).ready(function(){
    $('#myTable').DataTable();
});
</code>```

Reference

Demo

How to implement

Title: Sorting table with PHP

Body:
How to sort table in php?

I have code like this

$ATTT[0]
        ".number_format($HA[0], 3, '.', ',')."
        1

        $ATTT[1]
        ".number_format($HA[1], 3, '.', ',')."
        2

I want to sort column 2, so when column 2 sorting column 1 will follow column 2

Sorry for my English, I tried my best :D

Body:
In that case there are two options, use order by in your query so that you get the data in some order or use JQUERY datatable plug-in which have so many features like sorting, searching, pagination etc. It can be used like:

$(document).ready(function(){
    $('#myTable').DataTable();
});

Reference

Demo

How to implement


问:
Codeigniter 3 show_404 function issue - MY_Exception doesn't load
I'm using Codeigniter 3 and I want to custom the show_404() function.

Here is my main controller:

```<code>class Welcome extends CI_Controller {

    public function index() {
        $this->load->view('welcome_message');
    }

    public function otherMethod() {
        show_404();
    }

}
</code>```

Added on my routes.php

```<code>$route['404_override'] = 'error/show_404_custom';
</code>```

Created the controller Error.php with the method show_404_custom

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Error extends CI_Controller {

    public function show_404_custom() {
        $this->load->view('404_read_view');
    }
}
</code>```

The 404_read_view.php view:

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<p>Custom 404 page.</p>
</body>
</html>
</code>```

Then I've tested with some undefined URL like:

```<code>/index.php/welcome/method_A
</code>```

And I successfully get my Custom 404 page.

However, if I run a method that uses the show_404() function like:

```<code>/index.php/welcome/otherMethod
</code>```

I oddly get the standard Codeigniter 404 page.

I've searched a bit and found out that I should Extend the Exception core class and override the show_404() function like this:

https://stackoverflow.com/a/8425433/4301970

So, I created the MY_Exceptions.php class inside /application/core:

```<code><?php (defined('BASEPATH')) OR exit('No direct script access allowed');

class MY_Exceptions extends CI_Exceptions {

    public function __construct() {
        parent::__construct();
    }

    public function show_404() {
        $CI =& get_instance();
        $CI->load->view('404_read_view');
        echo $CI->output->get_output();
        exit;
    }

}
</code>```

And when I run the URL:

```<code>/index.php/welcome/otherMethod
</code>```

I get the error:

```<code>Fatal error: Class 'MY_Exceptions' not found in (...)\system\core\Common.php on line 196
</code>```

I took look inside Common.php and noticed that the load class function looks inside the libraries directory instead of core directory?

```<code>function &load_class($class, $directory = 'libraries', $param = NULL)
</code>```

How can I solve this problem?

答:
use this, it's work in CI 3.1.4 (my latest project)</p>

```<code>class MY_Exceptions extends CI_Exceptions {

    public function __construct()
    {
        parent::__construct();
    }

    function show_404($page = '', $log_error = TRUE)
    {

        $CI =& get_instance();
        $CI->load->view('404_read_view');
        echo $CI->output->get_output();
        exit;
    }
}
</code>```

Body:
I'm using Codeigniter 3 and I want to custom the show_404() function.

Here is my main controller:

class Welcome extends CI_Controller {

    public function index() {
        $this->load->view('welcome_message');
    }

    public function otherMethod() {
        show_404();
    }

}

Added on my routes.php

$route['404_override'] = 'error/show_404_custom';

Created the controller Error.php with the method show_404_custom

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Error extends CI_Controller {

    public function show_404_custom() {
        $this->load->view('404_read_view');
    }
}

The 404_read_view.php view:

<!DOCTYPE html>

    <title></title>

Custom 404 page.

Then I've tested with some undefined URL like:

/index.php/welcome/method_A

And I successfully get my Custom 404 page.

However, if I run a method that uses the show_404() function like:

/index.php/welcome/otherMethod

I oddly get the standard Codeigniter 404 page.

I've searched a bit and found out that I should Extend the Exception core class and override the show_404() function like this:

https://stackoverflow.com/a/8425433/4301970

So, I created the MY_Exceptions.php class inside /application/core:

<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

class MY_Exceptions extends CI_Exceptions {

    public function __construct() {
        parent::__construct();
    }

    public function show_404() {
        $CI =& get_instance();
        $CI->load->view('404_read_view');
        echo $CI->output->get_output();
        exit;
    }

}

And when I run the URL:

/index.php/welcome/otherMethod

I get the error:

Fatal error: Class 'MY_Exceptions' not found in (...)\system\core\Common.php on line 196

I took look inside Common.php and noticed that the load class function looks inside the libraries directory instead of core directory?

function &load_class($class, $directory = 'libraries', $param = NULL)

How can I solve this problem?

Body:
use this, it's work in CI 3.1.4 (my latest project)

class MY_Exceptions extends CI_Exceptions {

    public function __construct()
    {
        parent::__construct();
    }

    function show_404($page = '', $log_error = TRUE)
    {

        $CI =& get_instance();
        $CI->load->view('404_read_view');
        echo $CI->output->get_output();
        exit;
    }
}


问:
Ruby post title to slug
How should I convert a post title to a slug in Ruby?

The title can have any characters, but I only want the slug to allow [a-z0-9-_] (Should it allow any other characters?).

So basically:

downcase all letters

convert spaces to hyphens

delete extraneous characters

答:
to_slug is a great Rails plugin that handles pretty much everything, including funky characters, but its implementation is very simple. Chuck it onto String and you'll be sorted. Here's the source condensed down:

```<code>String.class_eval do
  def to_slug
    value = self.mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]/n, '').to_s
    value.gsub!(/[']+/, '')
    value.gsub!(/\W+/, ' ')
    value.strip!
    value.downcase!
    value.gsub!(' ', '-')
    value
  end
end
</code>```

ContentLicense: CC BY-SA 2.5

Title: Ruby post title to slug

Body:
to_slug is a great Rails plugin that handles pretty much everything, including funky characters, but its implementation is very simple. Chuck it onto String and you'll be sorted. Here's the source condensed down:

String.class_eval do
  def to_slug
    value = self.mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]/n, '').to_s
    value.gsub!(/[']+/, '')
    value.gsub!(/\W+/, ' ')
    value.strip!
    value.downcase!
    value.gsub!(' ', '-')
    value
  end
end


问:
Extension for OmniSharp
Is there any way to get an extension point in omnisharp-roslyn?
I see that omnisharp.exe has the "--plugin" argument, but the digging in the source code did not give me an answer: how to use this argument.
I need a way to include my assemblies in mef composition, so I can import Roslyn and OmniSharp services and export my ICodeActionProvider.</p>

答:
Plugins/extensions are a work in progress for the omnisharp-roslyn project.

There's an open PR for it.

Title: Extension for OmniSharp


问:
Swift Timer App
I was trying to build a simple ios timer app using swift3. I successfully created an app using the following code. It has three buttons, one to start the timer, one to stop the timer which means reset and one to pause the timer. all the buttons are working but when I click on start once again while the timer is running, the timer interval speeds up (means calls the selector function twice within a second). how to solve this problem.
Here is my code</p>

```<code>@IBOutlet weak var lbl: UILabel!
var time = 0
var timer = Timer()

@IBOutlet weak var start: UIButton!
@IBOutlet weak var stop: UIButton!
@IBOutlet weak var pause: UIButton!
@IBAction func start(_ sender: AnyObject) {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
}
@IBAction func stop(_ sender: AnyObject) {
    //timer.invalidate()
    time = 0
    lbl.text = "0"
}
@IBAction func pause(_ sender: AnyObject) {
    timer.invalidate()
}
override func viewDidLoad() {
    super.viewDidLoad()

}

func action() {
    time += 1
    lbl.text = String(time)
}
</code>```

答:
```<code>@IBOutlet weak var lbl: UILabel!
var time = 0
var timer : Timer?
var isPause = false

@IBOutlet weak var start: UIButton!
@IBOutlet weak var stop: UIButton!
@IBOutlet weak var pause: UIButton!
@IBAction func start(_ sender: AnyObject) {
    timer?.invalidate()
    timer = nil
    isPause = false
    time = 0
    lbl.text = "0"
    // or call  stop(self.stop)
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
}
@IBAction func stop(_ sender: AnyObject) {
    timer?.invalidate()
    timer = nil
    isPause  = false
    time = 0
    lbl.text = "0"
}
@IBAction func pause(_ sender: AnyObject) {
    timer.invalidate()
    isPause  = !isPause   // second click to resum...
}
override func viewDidLoad() {
    super.viewDidLoad()

}

func action() {
    if !isPause {
       time += 1
       lbl.text = String(time)
    }
}
</code>```

Title: Swift Timer App

Body:
I was trying to build a simple ios timer app using swift3. I successfully created an app using the following code. It has three buttons, one to start the timer, one to stop the timer which means reset and one to pause the timer. all the buttons are working but when I click on start once again while the timer is running, the timer interval speeds up (means calls the selector function twice within a second). how to solve this problem.
Here is my code

@IBOutlet weak var lbl: UILabel!
var time = 0
var timer = Timer()

@IBOutlet weak var start: UIButton!
@IBOutlet weak var stop: UIButton!
@IBOutlet weak var pause: UIButton!
@IBAction func start(_ sender: AnyObject) {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
}
@IBAction func stop(_ sender: AnyObject) {
    //timer.invalidate()
    time = 0
    lbl.text = "0"
}
@IBAction func pause(_ sender: AnyObject) {
    timer.invalidate()
}
override func viewDidLoad() {
    super.viewDidLoad()

}

func action() {
    time += 1
    lbl.text = String(time)
}


问:
Understanding sub-second values in a timestamp
Lets say we have the following time stamp:

```<code>2017-03-28 23:59:58.12
</code>```

Should the above time stamp be interpreted as having 120 milliseconds or 12 milliseconds?
Further, if we expect a time stamp to have microseconds precision, should 12 be then considered as 120000 microseconds, or 12 microseconds?

答:
The decimal off of the second should be treated as, well, a decimal.  In your case since

```<code>0.1 seconds = 100 milliseconds
</code>```

you should interoperate it as 120 milliseconds.  This rule goes for microseconds as well,

```<code>0.1 seconds = 100000 microseconds
</code>```

So, you could read your time stamp as 120000 microseconds

Google`s time converter supports decimal fractions if you want to play around with it a bit.

Body:
Lets say we have the following time stamp:

2017-03-28 23:59:58.12

Should the above time stamp be interpreted as having 120 milliseconds or 12 milliseconds?
Further, if we expect a time stamp to have microseconds precision, should 12 be then considered as 120000 microseconds, or 12 microseconds?

Body:
The decimal off of the second should be treated as, well, a decimal.  In your case since

0.1 seconds = 100 milliseconds

you should interoperate it as 120 milliseconds.  This rule goes for microseconds as well,

0.1 seconds = 100000 microseconds

So, you could read your time stamp as 120000 microseconds

Google`s time converter supports decimal fractions if you want to play around with it a bit.


问:
How to configure C# Api to display JSON directly from browser? (but not XML)
First, to clarify that, my C# API is working properly. I am able to retrieve the json data from my javascript.

But, I am curious, whenever I access my API directly through the browser, it shows this:

However, when I access JSON hosted by others (such as myjson), they are able to display the json directly from the browser:

Here's my code briefly,

```<code>public Object Get()
{
  ...// form object from my data
  return myObject;
}
</code>```

Is there any configuration needed?

答:
First of all, you did not specified which framework version you're using. I assume this is WebAPI 2. If not you should clarify.

In WebAPI 2, if your controller returns an object, it will get serialized automatically by a default serialization handler. This default handler will return xml by default, but also return json if you ask for it. You can ask for the JSON version by specifying in your HTTP request accepts header. You can also change the code such that it will no longer return xml by default.

The following code is copied directly from:
How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

I just add the following in App_Start / WebApiConfig.cs class in my
  MVC Web API project.

```<code>config.Formatters.JsonFormatter.SupportedMediaTypes
    .Add(new MediaTypeHeaderValue("text/html") );
</code>```

Body:
First, to clarify that, my C# API is working properly. I am able to retrieve the json data from my javascript.

But, I am curious, whenever I access my API directly through the browser, it shows this:

However, when I access JSON hosted by others (such as myjson), they are able to display the json directly from the browser:

Here's my code briefly,

public Object Get()
{
  ...// form object from my data
  return myObject;
}

Is there any configuration needed?

Body:
First of all, you did not specified which framework version you're using. I assume this is WebAPI 2. If not you should clarify.

In WebAPI 2, if your controller returns an object, it will get serialized automatically by a default serialization handler. This default handler will return xml by default, but also return json if you ask for it. You can ask for the JSON version by specifying in your HTTP request accepts header. You can also change the code such that it will no longer return xml by default.

The following code is copied directly from:
How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

I just add the following in App_Start / WebApiConfig.cs class in my
  MVC Web API project.

config.Formatters.JsonFormatter.SupportedMediaTypes
    .Add(new MediaTypeHeaderValue("text/html") );


问:
Javascript, looping through an array and the arguments "object"
I can't get my head around this, i'm using filter to loop through an array and filter out all the integers passed as arguments ,i'm not limited in the number of arguments.

But i'm stuck here when it's about to get back to the function the value of the arguments object, at least more that once.

In my code below, obviously it's not fully working because i'm doing a return within the for…in loop, this is where i don't get how I can get the this second loop without having i re-initialised to 0…

function destroyer(arr) {
  var args = arguments.length;
  var arg0 = arguments[0];
  var Nargs = Array.prototype.slice.call(arguments, 1);
  var newArr = [];

    newArr = arg0.filter(filtre);

    /*Only the first argument is
    filtered out,here it's the value "2",
    but should filter out [2,3].
    The expected result is [1,1]*/
    console.log(newArr);
    return newArr;

     function filtre(e){

         for (var i in Nargs){

           return e !== Nargs[i];
         }
     }
}

destroyer([1, 2, 3, 1, 2, 3], 2,3);```

Hope this is clear enough,

Thanks for any input !

Matth.

答:
Since your return statement in your filtre function is always executed on the first run, it's only returning the whether the first number in Nargs is equal to the current item. Instead, you can use indexOf for full browser support (which returns the index of the item in an array, or "-1" if it's not in an array) instead of a loop (or includes, or a loop, etc. as shown further below):

function destroyer(arr) {
  var args = arguments.length;
  var arg0 = arguments[0];
  var Nargs = Array.prototype.slice.call(arguments, 1);
  var newArr = [];

  function filtre(e){
    return Nargs.indexOf(e) === -1;
  }

  newArr = arg0.filter(filtre);
  console.log(newArr);
  return newArr;
}
destroyer([1, 2, 3, 1, 2, 3], 2,3);```
</div>
</div>
</p>

<p>If you don't need Internet Explorer support, you could use <code>Array.includes</code>:</p>

```  function filtre(e){
    return !Nargs.includes(e);
  }
```

<p>And finally, if you <em>really</em> wanted to use a loop, you would only want to filter an item (return false) once it's found otherwise allow it (return true):</p>

``` function filtre(e){
   for (var i = 0, l = Nargs.length; i < l; i++) {
     if (e === Nargs[i])
       return false;
   }
   return true;
 }
```

Body:
I can't get my head around this, i'm using filter to loop through an array and filter out all the integers passed as arguments ,i'm not limited in the number of arguments.

But i'm stuck here when it's about to get back to the function the value of the arguments object, at least more that once.

In my code below, obviously it's not fully working because i'm doing a return within the for…in loop, this is where i don't get how I can get the this second loop without having i re-initialised to 0…

function destroyer(arr) {
  var args = arguments.length;
  var arg0 = arguments[0];
  var Nargs = Array.prototype.slice.call(arguments, 1);
  var newArr = [];

    newArr = arg0.filter(filtre);

    /*Only the first argument is
    filtered out,here it's the value "2",
    but should filter out [2,3].
    The expected result is [1,1]*/
    console.log(newArr);
    return newArr;

     function filtre(e){

         for (var i in Nargs){

           return e !== Nargs[i];
         }
     }
}

destroyer([1, 2, 3, 1, 2, 3], 2,3);

Hope this is clear enough,

Thanks for any input !

Matth.

Body:
Since your return statement in your filtre function is always executed on the first run, it's only returning the whether the first number in Nargs is equal to the current item. Instead, you can use indexOf for full browser support (which returns the index of the item in an array, or "-1" if it's not in an array) instead of a loop (or includes, or a loop, etc. as shown further below):

function destroyer(arr) {
  var args = arguments.length;
  var arg0 = arguments[0];
  var Nargs = Array.prototype.slice.call(arguments, 1);
  var newArr = [];

  function filtre(e){
    return Nargs.indexOf(e) === -1;
  }

  newArr = arg0.filter(filtre);
  console.log(newArr);
  return newArr;
}
destroyer([1, 2, 3, 1, 2, 3], 2,3);

If you don't need Internet Explorer support, you could use Array.includes:

  function filtre(e){
    return !Nargs.includes(e);
  }

And finally, if you really wanted to use a loop, you would only want to filter an item (return false) once it's found otherwise allow it (return true):

 function filtre(e){
   for (var i = 0, l = Nargs.length; i < l; i++) {
     if (e === Nargs[i])
       return false;
   }
   return true;
 }


问:
Requires simple explanation on Arbiter's role in a given mongoDB replica set
I came across MongoDB official site explaining on having odd number of members replica set up. I also heard of the term Arbiter from the same site, which based on my understanding, it will not be elected as primary and it does participate on election (from https://docs.mongodb.com/manual/core/replica-set-arbiter/).

There is also a post related to Arbiter in Why do we need an 'arbiter' in MongoDB replication? which then relates to CAP theorem, which further gets things more complicated.

First of all, why do we need to make the number of members odd? Also, can someone explain to me what this Arbiter is and what is its role in a given replica set in simple layman English??

Thanks in advance.

答: Take the example of a 2-member replica set: in the event of a network-partitioning, i.e., the 2 members lost touch of each other, who gets to become the primary? There will be a tie and a need for a tie-breaker. That would not be the case if we have a 3-member replica set: the group that contains two nodes will win and one of them will become primary. That is the basis of the requirement for an odd number of nodes in a replica set. As for an arbiter, it happens to be light weight so that I guess one can save money by having in place a smaller machine, since we do not expect it to hold any data, and that we just need it to be present to vote for primary. </p>


问:
Autorelease iPhone
Coming up towards the end of developing an iPhone application and I'm wondering just how bad is it to use autorelease when developing for the iphone. I'm faced with some fairly random crashes and, so far, I can't pinpoint it to anything other than sloppy memory usage.

As a Cocoa newbie I remember initially reading a guideline document that strongly suggested avoiding autorelease in favor of manual retain/release for iPhone. However, a more 'senior' Cocoa developer came on board early on (who ironically has been let go since), who used autorelease all over the place. Admittedly, I was went into "monkey see monkey do" mode, and it appears to be coming back to haunt me (I'm now the only developer on the project).

So what to do next? It seems to me that I have to branch the code and try to go through and replace, where possible, autorelease code keeping my fingers crossed that I don't inadvertently break the app. It seems a lot of library calls result in autoreleased objects like stringWithFormat and pretty much anything where I'm not using alloc myself. Any other gotchyas and/or suggestions I should be looking out for? Thanks Cocoa gurus.

答:
More important than the autorelease or manual-release choice is how often you alloc and dealloc your NSAutoreleasePools.  Since most of the Cocoa frameworks use autorelease liberally, you need to have a proper pool draining strategy.  Once that is in place, the choice of whether to release or autorelease becomes much less an issue.

That being said, the only areas you should worry about are tight loops--allocate and release an NSAutoreleasePool every few iterations for best results; and when you have spawned another NSThread that doesn't have a Runloop--create a pool and drain it every so often becomes idle.  Since most applications only allocate a small amount of data per event, UIKit's strategy of allocating the pool before the event is dispatched and releasing it after the dispatch returns works very well.

Title: Autorelease iPhone

OwnerDisplayName: rpetrich


问:
Android: Are there any benefits to using @id over @+id performance wise?
I know that the + in @+id tells the compiler to add the id to the (R.id.???) resources. However i was wondering if there were performance benefits to be gained by not putting the + ?

Perhaps for example when dealing with complex list view layouts?

答: The + means add to R list, without you're referencing an already existing UI element, in other words @+id/ != @id/</p>


问:
TypeError: unsupported operand type(s) for +: 'bool' and 'str' - Odoo v8 to Odoo v10 migration
I have this method:

```<code>@api.multi
def search_partner_seniat(self):
    """ Check vat of the partner and update iva rate
    """
    self.ensure_one()
    vat = self.vat.upper()
    res = {
        'name': _('The requested contributor does not exist'),
        'vat_subjected': False,
        'vat': vat,
        'wh_iva_agent': False,
        'wh_iva_rate': 0.0
    }

    if 'VE' in vat:
        vat = vat[2:]

    # assumption: both methods in new api style
    if self.env['res.partner'].check_vat_ve(vat):
        res = self.env['seniat.url']._dom_giver(vat)
    self.write(res)

    return {
        'type': 'ir.actions.act_window',
        'res_model': 'search.info.partner.seniat',
        'view_mode': 'form',
        'view_type': 'form',
        'res_id': self.id,
        'views': [(False, 'form')],
        'target': 'new',
    }
</code>```

It is a button, this method calls for _dom_giver which is like follows:

```<code>@api.multi
def _dom_giver(self, vat):
    """ Check and validates that the vat is a passport,
    id or rif, to send information to SENIAT and returns the
    partner info that provides.
    """

    url_obj = self.search([], limit=1)
    url1 = url_obj.name + '%s'
    url2 = url_obj.url_seniat + '%s'
    vat = self._validate_rif(vat)
    if vat:
        return self._get_rif(vat, url1, url2)
    else:
        return False
</code>```

The error comes on this line 'url1 = url.obj.name + '%s'', the complete traceback:

```<code>Traceback (most recent call last):
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 638, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 675, in dispatch
result = self._call_function(**self.params)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 331, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/service/model.py", line 119, in wrapper
return f(dbname, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 324, in checked_call
result = self.endpoint(*a, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 933, in __call__
return self.method(*args, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 504, in response_wrap
response = f(*args, **kw)
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 866, in call_button
action = self._call_kw(model, method, args, {})
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 854, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 681, in call_kw
return call_kw_multi(method, model, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 672, in call_kw_multi
result = method(recs, *args, **kwargs)
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/wizard/search_info_partner_seniat.py", line 64, in search_partner_seniat
res = self.env['seniat.url']._dom_giver(vat)  # _dom_giver() should be @api.model
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/model/seniat_url.py", line 215, in _dom_giver
url1 = url_obj.name + '%s'
TypeError: unsupported operand type(s) for +: 'bool' and 'str'
</code>```

Originally, _dom_giver method looked like this:

```<code>def _dom_giver(self, cr, uid, vat, context=None):
    """ Check and validates that the vat is a passport,
    id or rif, to send information to SENIAT and returns the
    partner info that provides.
    """
    if context is None:
        context = {}

    url_obj = self.browse(cr, uid, self.search(cr, uid, []))[0]
    url1 = url_obj.name + '%s'
    url2 = url_obj.url_seniat + '%s'
    vat = self._validate_rif(cr, uid, vat, context=None)
    if vat:
        return self._get_rif(cr, uid, vat, url1, url2, context=context)
    else:
        return False
</code>```

Any ideas?

答:
please check my answer in odoo forumclick here

which has solved.

Body:
I have this method:

@api.multi
def search_partner_seniat(self):
    """ Check vat of the partner and update iva rate
    """
    self.ensure_one()
    vat = self.vat.upper()
    res = {
        'name': _('The requested contributor does not exist'),
        'vat_subjected': False,
        'vat': vat,
        'wh_iva_agent': False,
        'wh_iva_rate': 0.0
    }

    if 'VE' in vat:
        vat = vat[2:]

    # assumption: both methods in new api style
    if self.env['res.partner'].check_vat_ve(vat):
        res = self.env['seniat.url']._dom_giver(vat)
    self.write(res)

    return {
        'type': 'ir.actions.act_window',
        'res_model': 'search.info.partner.seniat',
        'view_mode': 'form',
        'view_type': 'form',
        'res_id': self.id,
        'views': [(False, 'form')],
        'target': 'new',
    }

It is a button, this method calls for _dom_giver which is like follows:

@api.multi
def _dom_giver(self, vat):
    """ Check and validates that the vat is a passport,
    id or rif, to send information to SENIAT and returns the
    partner info that provides.
    """

    url_obj = self.search([], limit=1)
    url1 = url_obj.name + '%s'
    url2 = url_obj.url_seniat + '%s'
    vat = self._validate_rif(vat)
    if vat:
        return self._get_rif(vat, url1, url2)
    else:
        return False

The error comes on this line 'url1 = url.obj.name + '%s'', the complete traceback:

Traceback (most recent call last):
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 638, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 675, in dispatch
result = self._call_function(**self.params)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 331, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/service/model.py", line 119, in wrapper
return f(dbname, *args, **kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 324, in checked_call
result = self.endpoint(*a, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 933, in __call__
return self.method(*args, **kw)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/http.py", line 504, in response_wrap
response = f(*args, **kw)
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 866, in call_button
action = self._call_kw(model, method, args, {})
File "/home/kristian/odoov10/odoo-10.0rc1c-20161005/odoo/addons/web/controllers/main.py", line 854, in _call_kw
return call_kw(request.env[model], method, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 681, in call_kw
return call_kw_multi(method, model, args, kwargs)
File "/home/kristian/.virtualenvs/odoov10/lib/python2.7/site-packages/odoo-10.0rc1c_20161005-py2.7.egg/odoo/api.py", line 672, in call_kw_multi
result = method(recs, *args, **kwargs)
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/wizard/search_info_partner_seniat.py", line 64, in search_partner_seniat
res = self.env['seniat.url']._dom_giver(vat)  # _dom_giver() should be @api.model
File "/home/kristian/odoov10/gilda/l10n_ve_fiscal_requirements/model/seniat_url.py", line 215, in _dom_giver
url1 = url_obj.name + '%s'
TypeError: unsupported operand type(s) for +: 'bool' and 'str'

Originally, _dom_giver method looked like this:

def _dom_giver(self, cr, uid, vat, context=None):
    """ Check and validates that the vat is a passport,
    id or rif, to send information to SENIAT and returns the
    partner info that provides.
    """
    if context is None:
        context = {}

    url_obj = self.browse(cr, uid, self.search(cr, uid, []))[0]
    url1 = url_obj.name + '%s'
    url2 = url_obj.url_seniat + '%s'
    vat = self._validate_rif(cr, uid, vat, context=None)
    if vat:
        return self._get_rif(cr, uid, vat, url1, url2, context=context)
    else:
        return False

Any ideas?


问:
How can i skip files that does not exist file in the repository using python?
I want to download xml file from issue tracking system one by one.It produces error message when file not exist in the repository. I include the python script to better understand my problem.

My code:

```<code>import urllib.request
for i in range(0,1000):
    issue_id1='DERBY-'+str(i)
    url ="https://issues.apache.org/jira/si/jira.issueviews:issue-xml/"+issue_id1+'/'+issue_id1+'.xml'
    s=urllib.request.urlopen(url)
    contents = s.read()
    file = open(issue_id1+'.xml', 'wb')
    file.write(contents)

file.close()
</code>```

Stack Track:

```<code>Traceback (most recent call last):
  File "/PhP/Learning/xmldownlaod.py", line 10, in <module>
    s=urllib.request.urlopen(url)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 161, in urlopen
    return opener.open(url, data, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 469, in open
    response = meth(req, response)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 579, in http_response
    'http', request, response, code, msg, hdrs)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 507, in error
    return self._call_chain(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 441, in _call_chain
    result = func(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 587, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found
</code>```

答:
The problem happens on the first iteration of the loop, the url value becomes:

```<code>https://issues.apache.org/jira/si/jira.issueviews:issue-xml/DERBY-0/DERBY-0.xml
</code>```

which is a "dead link" and requesting it results into 404 Not Found error.

Start your loop with 1:

```<code>for i in range(1, 1000):
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to download xml file from issue tracking system one by one.It produces error message when file not exist in the repository. I include the python script to better understand my problem.

My code:

import urllib.request
for i in range(0,1000):
    issue_id1='DERBY-'+str(i)
    url ="https://issues.apache.org/jira/si/jira.issueviews:issue-xml/"+issue_id1+'/'+issue_id1+'.xml'
    s=urllib.request.urlopen(url)
    contents = s.read()
    file = open(issue_id1+'.xml', 'wb')
    file.write(contents)

file.close()

Stack Track:

Traceback (most recent call last):
  File "/PhP/Learning/xmldownlaod.py", line 10, in <module>
    s=urllib.request.urlopen(url)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 161, in urlopen
    return opener.open(url, data, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 469, in open
    response = meth(req, response)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 579, in http_response
    'http', request, response, code, msg, hdrs)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 507, in error
    return self._call_chain(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 441, in _call_chain
    result = func(*args)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 587, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found

Body:
The problem happens on the first iteration of the loop, the url value becomes:

https://issues.apache.org/jira/si/jira.issueviews:issue-xml/DERBY-0/DERBY-0.xml

which is a "dead link" and requesting it results into 404 Not Found error.

Start your loop with 1:

for i in range(1, 1000):


Title: how can i return the letter if it is not found in the dictionary in python

Body:
I am trying to encrypt the file using a dictionary i want to print the corresponding value to the key, but some letters are not in the dictionary meaning that letter is what is needed to be printed

#opening the file
file = open("fileToEncrypt.txt", 'r')
#the dictionary
CODE = {'A':')','a':'0','B':'(','b':'9','C':'*','c':'8',\
        'D':'&','d':'7','E':'^','e':'6','F':'%','f':'5',\
        'G':'$','g':'4','H':'#','h':'3','I':'@','i':'2',\
        'J':'!','j':'1','K':'Z','k':'z','L':'Y','l':'y',\
        'M':'X','m':'x','N':'W','n':'w','O':'V','o':'v',\
        'P':'U','p':'u','Q':'T','q':'t','R':'S','r':'s',\
        'S':'R','s':'r','T':'Q','t':'q','U':'P','u':'p',\
        'V':'O','v':'o','W':'N','w':'n','X':'M','x':'m',\
        'Y':'L','y':'l','Z':'K','z':'k','!':'J','1':'j',\
        '@':'I','2':'i','#':'H','3':'h','$':'G','4':'g',\
        '%':'F','5':'f','^':'E','6':'e','&':'D','7':'d',\
        '*':'C','8':'c','(':'B','9':'b',')':'A','0':'a',\
        ':':',',',':':','?':'.','.':'?','<':'>','>':'<',\
        "'":'"','"':"'",'+':'-','-':'+','=':';',';':'=',\
        '{':'[','[':'{','}':']',']':'}'}

for letter in file:
    if letter in CODE.keys():
        values = CODE.get(letter,"Not here")
        print(values)

the output would just print the default "Not here"

Body:
If you want to get the letters you must do a double for, since the first one iterates on the rows, and the second it will do on the letters.

#opening the file
file = open("fileToEncrypt.txt", 'r')
#the dictionary
CODE = {'A':')','a':'0','B':'(','b':'9','C':'*','c':'8',\
        'D':'&','d':'7','E':'^','e':'6','F':'%','f':'5',\
        'G':'$','g':'4','H':'#','h':'3','I':'@','i':'2',\
        'J':'!','j':'1','K':'Z','k':'z','L':'Y','l':'y',\
        'M':'X','m':'x','N':'W','n':'w','O':'V','o':'v',\
        'P':'U','p':'u','Q':'T','q':'t','R':'S','r':'s',\
        'S':'R','s':'r','T':'Q','t':'q','U':'P','u':'p',\
        'V':'O','v':'o','W':'N','w':'n','X':'M','x':'m',\
        'Y':'L','y':'l','Z':'K','z':'k','!':'J','1':'j',\
        '@':'I','2':'i','#':'H','3':'h','$':'G','4':'g',\
        '%':'F','5':'f','^':'E','6':'e','&':'D','7':'d',\
        '*':'C','8':'c','(':'B','9':'b',')':'A','0':'a',\
        ':':',',',':':','?':'.','.':'?','<':'>','>':'<',\
        "'":'"','"':"'",'+':'-','-':'+','=':';',';':'=',\
        '{':'[','[':'{','}':']',']':'}'}

for row in file:
    for letter in row.strip():
        values = CODE.get(letter,"Not here")
        print(values)


问:
How do I convert a column of Texts with hyperlink into the text URL in Excel?
For example,

The column of Company names that are hyperlinked
Company A
Company B
...

converted to

URL of company A
URL of company B
...

答:
This little piece of code should take the value of the hyperlink and put it into a column on a new sheet:</p>

```<code>Sub RemoveHyperlinks()
    Dim Cell As Range

    Dim i As Long
    Dim k As Long
    k = 1
    Set Cell = Workbooks("Book2").Sheets("Sheet1").UsedRange

    i = 0

    Do Until i = Cell.Hyperlinks.Count
    If Cell.Hyperlinks.Count > 0 Then
    Workbooks("Book2").Sheets("Sheet2").Cells(k, 1).Value = Cell.Hyperlinks.Item(k).Address
    i = i + 1
    k = k + 1
    End If

    Loop

End Sub
</code>```

Body:
This little piece of code should take the value of the hyperlink and put it into a column on a new sheet:

Sub RemoveHyperlinks()
    Dim Cell As Range

    Dim i As Long
    Dim k As Long
    k = 1
    Set Cell = Workbooks("Book2").Sheets("Sheet1").UsedRange

    i = 0

    Do Until i = Cell.Hyperlinks.Count
    If Cell.Hyperlinks.Count > 0 Then
    Workbooks("Book2").Sheets("Sheet2").Cells(k, 1).Value = Cell.Hyperlinks.Item(k).Address
    i = i + 1
    k = k + 1
    End If

    Loop

End Sub


问:
link django user to perticular site in site framework
I've setup Django sites framework in my project,
actually, i want to combine Django user to that particular site

What I want to achieve is that when user register from particular site or subsite which register with site framework then that user has to link to that particular site so that we can restrict a user to login to another site with their associate site credential.

答:
In the settings files for your different sites you can specify separate "users" databases, https://docs.djangoproject.com/en/1.10/topics/db/multi-db/</p>

```<code>#in site1 settings.py
DATABASES = {
    'default': {
        'NAME': 'app_data',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'priv4te'
    },
    'users': {
        'NAME': 'user_data_site1',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'priv4te'
    }
}

#in site2 settings.py
DATABASES = {
    'default': {
        'NAME': 'app_data',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'priv4te'
    },
    'users': {
        'NAME': 'user_data_site2',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'priv4te'
    }
}
</code>```

Body:
In the settings files for your different sites you can specify separate "users" databases, https://docs.djangoproject.com/en/1.10/topics/db/multi-db/

#in site1 settings.py
DATABASES = {
    'default': {
        'NAME': 'app_data',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'priv4te'
    },
    'users': {
        'NAME': 'user_data_site1',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'priv4te'
    }
}

#in site2 settings.py
DATABASES = {
    'default': {
        'NAME': 'app_data',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'priv4te'
    },
    'users': {
        'NAME': 'user_data_site2',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'priv4te'
    }
}


问:
Iterate over JSON with PHP
I cannot figure out how to get the following keys/values from the JSON below:

I need to print out in a for loop:

'projects' i.e 'test-project-1'

'datasets' i.e 'dataset1'

'permissions' i.e 'role: WRITER, group: test1@test.com'

```<code>{
   "projects":{
      "test-project-1":{
         "datasets":{
            "dataset1":{
               "permissions":{
                  "role":"WRITER",
                  "group":"test1@test.com"
               }
            },
            "dataset2":{
               "permissions":{
                  "role":"READER",
                  "group":"test2@test.com"
               }
            },
            "dataset3":{
               "permissions":{
                  "role":"READER",
                  "group":"test3@test.com"
               }
            },
            "dataset4":{
               "permissions":{
                  "role":"READER",
                  "group":"test4@test.com"
               }
            },
            "dataset5":{
               "permissions":{
                  "role":"READER",
                  "group":"test5@test.com"
               }
            }
         }
      },
      "test-project-2":{
         "datasets":{
            "dataset1":{
               "permissions":{
                  "role":"WRITER",
                  "group":"test1@test.com"
               }
            },
            "dataset2":{
               "permissions":{
                  "role":"READER",
                  "group":"test2@test.com"
               }
            },
            "dataset3":{
               "permissions":{
                  "role":"READER",
                  "group":"test3@test.com"
               }
            },
            "dataset4":{
               "permissions":{
                  "role":"READER",
                  "group":"test4@test.com"
               }
            },
            "dataset5":{
               "permissions":{
                  "role":"READER",
                  "group":"test5@test.com"
               }
            }
         }
      }
   }
}
</code>```

I tried this but the only thing that prints out is "Array".

Something like this does not work:

```<code>$new_json = {path_to_json};
$new_projects = $new_json['projects'];
foreach ($new_projects as $project) {
    echo $project . "<br>";
    foreach ($new_projects['datasets'] as $datasets){
        echo $datasets . "<br>";
    }
}
</code>```

答:
the format is foreach ("array"  as  "key in array")</p>

```<code>foreach ($new_json as $new_projects) {
    echo $new_projects . "<br>";
    $datasets=$new_projects['datasets'];
    foreach ($new_projects as $datasets){
        echo $datasets . "<br>";
    }
}
</code>```

Title: Iterate over JSON with PHP

Body:
I cannot figure out how to get the following keys/values from the JSON below:

I need to print out in a for loop:

'projects' i.e 'test-project-1'

'datasets' i.e 'dataset1'

'permissions' i.e 'role: WRITER, group: test1@test.com'

{
   "projects":{
      "test-project-1":{
         "datasets":{
            "dataset1":{
               "permissions":{
                  "role":"WRITER",
                  "group":"test1@test.com"
               }
            },
            "dataset2":{
               "permissions":{
                  "role":"READER",
                  "group":"test2@test.com"
               }
            },
            "dataset3":{
               "permissions":{
                  "role":"READER",
                  "group":"test3@test.com"
               }
            },
            "dataset4":{
               "permissions":{
                  "role":"READER",
                  "group":"test4@test.com"
               }
            },
            "dataset5":{
               "permissions":{
                  "role":"READER",
                  "group":"test5@test.com"
               }
            }
         }
      },
      "test-project-2":{
         "datasets":{
            "dataset1":{
               "permissions":{
                  "role":"WRITER",
                  "group":"test1@test.com"
               }
            },
            "dataset2":{
               "permissions":{
                  "role":"READER",
                  "group":"test2@test.com"
               }
            },
            "dataset3":{
               "permissions":{
                  "role":"READER",
                  "group":"test3@test.com"
               }
            },
            "dataset4":{
               "permissions":{
                  "role":"READER",
                  "group":"test4@test.com"
               }
            },
            "dataset5":{
               "permissions":{
                  "role":"READER",
                  "group":"test5@test.com"
               }
            }
         }
      }
   }
}

I tried this but the only thing that prints out is "Array".

Something like this does not work:

$new_json = {path_to_json};
$new_projects = $new_json['projects'];
foreach ($new_projects as $project) {
    echo $project . "
";
    foreach ($new_projects['datasets'] as $datasets){
        echo $datasets . "
";
    }
}

Body:
the format is foreach ("array"  as  "key in array")

foreach ($new_json as $new_projects) {
    echo $new_projects . "<br>";
    $datasets=$new_projects['datasets'];
    foreach ($new_projects as $datasets){
        echo $datasets . "<br>";
    }
}


问:
I am having to use RegEx to validate several parts of a form
For this project, I have to create a pizza delivery form. There are multiple steps, and the first part is to create a form that validates the user's input. So far I have been able to partially tackle this problem. My question is
1: Is there a more concise for validating?
2: I am trying to make it so that the submit button only appears once all the fields are validated, however, I can't figure out how to do that.
Below is my GitHub link

https://github.com/jcast90/JavaScript-RegEx-Form

```<code>var addressType = document.getElementById('addressType');
var submit = document.getElementById('submit');
var input = document.getElementById('otherInput');
var allInputs = document.querySelectorAll('input[type="text"]');

addressType.addEventListener('change', function () {
    if (addressType.value === 'other') {
        input.classList.remove('hidden');
    } else {
        input.classList.add('hidden');
    }
}, false);

var state = document.getElementById('state');
var phone = document.getElementById('phone');
var name = document.getElementById('name');
var zip = document.getElementById('zip');
var email = document.getElementById('email');

// NAME VERIFICATION => + check if empty
name.addEventListener('focusout', focus, false);
function focus() {
    if (name.value.match(/^[a-zA-z ]*$/)) {
        name.style.border = 'solid 3px green';
        return true;
    } else {
        name.style.border = 'solid 3px red';
        name.value = '';
    }
}

// ZIP VERIFICATION => + check if empty
zip.addEventListener('focusout', zipF, false);
function zipF() {
    var zipTest = /^([0-9]{5}(?:-[0-9]{4})?)/;
    if (zip.value.match(zipTest)) {
        zip.style.border = 'solid 3px green';
        return true;
    } else {
        zip.style.border = 'solid 3px red';
    }
}

// EMAIL VERIFICATION => + check if empty
email.addEventListener('focusout', emailF, false);
function emailF() {
    var emailTest = /^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})*$/;
    if (email.value.match(emailTest)) {
        email.style.border = 'solid 3px green';
        return true;
    } else {
        email.style.border = 'solid 3px red';
    }
}

// STATE VERIFICATION => + check if empty
var state = document.getElementById('state');
state.addEventListener('focusout', stateF, false);
function stateF() {
    var stateTest = /^(?:A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY |O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])*$/;
    if (state.value.match(stateTest)) {
        state.style.border = 'solid 3px green';
        return true;
    } else {
        state.style.border = 'solid 3px red';
        return state.value = '';
    }
}

// PHONE VERIFICATION => add to check if empty
var phone = document.getElementById('phone');
phone.addEventListener('focusout', phoneF, false);
function phoneF() {
    var phoneTest = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
    if (phone.value.match(phoneTest)) {
        phone.style.border = 'solid 3px green';
        return true;
    } else {
        phone.style.border = 'solid 3px red';
        return phone.value = '';
    }
}

function inputsTrue() {
    if (allInputs === true) {
        submit.classList.remove('hidden');
    } else {
        submit.classList.add('hidden');
    }
}

inputsTrue();
</code>```

答: The best practice for validation use jquery validation plugin.easy to use and strong validation for form.</p>

Body:
For this project, I have to create a pizza delivery form. There are multiple steps, and the first part is to create a form that validates the user's input. So far I have been able to partially tackle this problem. My question is
1: Is there a more concise for validating?
2: I am trying to make it so that the submit button only appears once all the fields are validated, however, I can't figure out how to do that.
Below is my GitHub link

https://github.com/jcast90/JavaScript-RegEx-Form

var addressType = document.getElementById('addressType');
var submit = document.getElementById('submit');
var input = document.getElementById('otherInput');
var allInputs = document.querySelectorAll('input[type="text"]');

addressType.addEventListener('change', function () {
    if (addressType.value === 'other') {
        input.classList.remove('hidden');
    } else {
        input.classList.add('hidden');
    }
}, false);

var state = document.getElementById('state');
var phone = document.getElementById('phone');
var name = document.getElementById('name');
var zip = document.getElementById('zip');
var email = document.getElementById('email');

// NAME VERIFICATION => + check if empty
name.addEventListener('focusout', focus, false);
function focus() {
    if (name.value.match(/^[a-zA-z ]*$/)) {
        name.style.border = 'solid 3px green';
        return true;
    } else {
        name.style.border = 'solid 3px red';
        name.value = '';
    }
}

// ZIP VERIFICATION => + check if empty
zip.addEventListener('focusout', zipF, false);
function zipF() {
    var zipTest = /^([0-9]{5}(?:-[0-9]{4})?)/;
    if (zip.value.match(zipTest)) {
        zip.style.border = 'solid 3px green';
        return true;
    } else {
        zip.style.border = 'solid 3px red';
    }
}

// EMAIL VERIFICATION => + check if empty
email.addEventListener('focusout', emailF, false);
function emailF() {
    var emailTest = /^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})*$/;
    if (email.value.match(emailTest)) {
        email.style.border = 'solid 3px green';
        return true;
    } else {
        email.style.border = 'solid 3px red';
    }
}

// STATE VERIFICATION => + check if empty
var state = document.getElementById('state');
state.addEventListener('focusout', stateF, false);
function stateF() {
    var stateTest = /^(?:A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY |O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])*$/;
    if (state.value.match(stateTest)) {
        state.style.border = 'solid 3px green';
        return true;
    } else {
        state.style.border = 'solid 3px red';
        return state.value = '';
    }
}

// PHONE VERIFICATION => add to check if empty
var phone = document.getElementById('phone');
phone.addEventListener('focusout', phoneF, false);
function phoneF() {
    var phoneTest = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
    if (phone.value.match(phoneTest)) {
        phone.style.border = 'solid 3px green';
        return true;
    } else {
        phone.style.border = 'solid 3px red';
        return phone.value = '';
    }
}

function inputsTrue() {
    if (allInputs === true) {
        submit.classList.remove('hidden');
    } else {
        submit.classList.add('hidden');
    }
}

inputsTrue();


问:
Converting a Python numeric expression to LaTeX
I need to  convert strings with valid Python syntax such as:

'1+2**(x+y)'
```
<p>and get the equivalent LaTeX:</p>
<pre class="lang-latex prettyprint-override"><code>$1+2^{x+y}$
</code>```

I have tried SymPy's latex function but it processes actual expression, rather than the string form of it:

>>> latex(1+2**(x+y))
'$1 + 2^{x + y}$'
>>> latex('1+2**(x+y)')
'$1+2**(x+y)$'
```
<p>but to even do this, it requires <code>x</code> and <code>y</code> to be declared as type "symbols".</p>
<p>I want something more straightforward, preferably doable with the parser from the compiler module.</p>
<pre class="lang-py prettyprint-override"><code>>>> compiler.parse('1+2**(x+y)')
Module(None, Stmt([Discard(Add((Const(1), Power((Const(2), Add((Name('x'), Name('y'))))))))]))
</code>```

Last but not least, the why: I need to generate those LaTeX snippets so that I can show them in a webpage with MathJax.

答:
You can use SymPy.  Just pass the string to the sympify() function first, which will convert it to a valid SymPy expression (i.e., create the Symbols for you, etc.).  So you could do

```<code>>>> latex(sympify('1+2**(x+y)'))
1 + 2^{x + y}
</code>```

S() is also a shortcut to sympify(), i.e., latex(S('1+2**(x+y)')) also works.

Body:
I need to  convert strings with valid Python syntax such as:

'1+2**(x+y)'

and get the equivalent LaTeX:

$1+2^{x+y}$

I have tried SymPy's latex function but it processes actual expression, rather than the string form of it:

>>> latex(1+2**(x+y))
'$1 + 2^{x + y}$'
>>> latex('1+2**(x+y)')
'$1+2**(x+y)$'

but to even do this, it requires x and y to be declared as type "symbols".

I want something more straightforward, preferably doable with the parser from the compiler module.

>>> compiler.parse('1+2**(x+y)')
Module(None, Stmt([Discard(Add((Const(1), Power((Const(2), Add((Name('x'), Name('y'))))))))]))

Last but not least, the why: I need to generate those LaTeX snippets so that I can show them in a webpage with MathJax.

Body:
You can use SymPy.  Just pass the string to the sympify() function first, which will convert it to a valid SymPy expression (i.e., create the Symbols for you, etc.).  So you could do

>>> latex(sympify('1+2**(x+y)'))
1 + 2^{x + y}

S() is also a shortcut to sympify(), i.e., latex(S('1+2**(x+y)')) also works.


问:
How to Apply Custom Filters in a Camera [Surfaceview Preview]...?
Guys i am developing Camera Application and this is my first android Application.

below i am Adding My App Screenshot for what i want.

First View :

Here , after Clicking on a Top-Right Corner Filter icon i want a below View.

Second View :

i don't know how can i get this type of a view. also how can i design this type of view into XML parts.

and i read more articles like how to Open a Multiple Surface-view Preview onto single screen but i did not get any much appreciate solution.

and Finally after selecting any of the Filter Preview i want a above Image type View.

means Selected Filter's is Preview apply onto Camera [Surfaceview Preview].
Please provide any type of Material link example.etc

guys please help me.any type of help will be appreciated..):

Thanks in advance

答: From the images, it's from a app called Geak Camera. Actually, I developed this app, and I used the GLSurfaceView not the surfaceview. And the app is not maintained now because I left that company. And I updated that app called "U camera".The scale animation was improved in "U camera".</p>


问:
Javascript: silently fail on undefined assignment
Suppose I am trying to assign a variable in a way that causes an exception

I am going to access a non-existent key of a dictionary:

```<code>myObject.property = dictionary['NO_KEY'][0];
</code>```

Now, because 'NO_KEY' does not exist on dictionary, my program will catch an exception when trying to subscript 0 of undefined - and crash. Is it possible to execute this line above as a no-op so that my script can continue running? I know there is try-catch syntex, but is there a more elegant syntax with ESMA6?

答:
Use ternary operator</p>

```<code>myObject.property = dictionary['NO_KEY'] ? dictionary['NO_KEY'][0] : null;
</code>```

Body:
Suppose I am trying to assign a variable in a way that causes an exception

I am going to access a non-existent key of a dictionary:

myObject.property = dictionary['NO_KEY'][0];

Now, because 'NO_KEY' does not exist on dictionary, my program will catch an exception when trying to subscript 0 of undefined - and crash. Is it possible to execute this line above as a no-op so that my script can continue running? I know there is try-catch syntex, but is there a more elegant syntax with ESMA6?

Body:
Use ternary operator

myObject.property = dictionary['NO_KEY'] ? dictionary['NO_KEY'][0] : null;


答:
You need to use json_decode function PHP Manual

```<code>$jsonArray = json_decode($jsonData, true);
foreach($jsonArray as $project){
    echo $project . '<br>';
    foreach($project['datasets'] as $dataset)
    {
        echo $dataset . '<br>';
        foreach($dataset['permissions'] as $permissions)
        {
            echo sprintf('Role: %s, group: %s<br>', $permissions['role'], $permissions['group'];
        }
    }
}
</code>```

if you dont want json to be converted to array, you need to pass false as second argument and stdClass will be returned instead.

Title: Iterate over JSON with PHP

Body:
You need to use json_decode function PHP Manual

$jsonArray = json_decode($jsonData, true);
foreach($jsonArray as $project){
    echo $project . '<br>';
    foreach($project['datasets'] as $dataset)
    {
        echo $dataset . '<br>';
        foreach($dataset['permissions'] as $permissions)
        {
            echo sprintf('Role: %s, group: %s<br>', $permissions['role'], $permissions['group'];
        }
    }
}

if you dont want json to be converted to array, you need to pass false as second argument and stdClass will be returned instead.


问:
How can I change the background color of a header from a TListView?
I need change the background color of all header of my listView for them to be highlighted. I found nothing on Object Inspector and nothing on Style Designer, can you guys give me some direction?

答:
Basically you need to place a Rectangle component inside the header item of your LV (ListView), then change its color accordingly. Here is how to accomplish it:

Your LV must be in Dynamic Appearance (I believe it already is)

Right click on you LV, and select Edit Custom Style

In the Style Container->expand your LV->expand Header

Drag a Rectangle component onto your LV header (MAKE SURE IT IS INSIDE THE HEADER item).

Set the desired fill color for the Rectangle.

Set its alignment to client

Close and save your Style Designer.

Should be working now


问:
How do I package a website to be served by tomcat?
First, let me apologize, I'm new at web development, so I'm not quite sure how this works, but it's a simple proof of concept, so I don't think it needs to be too advanced.

I have a jar that accesses a server and pulls information that needs to be displayed for the user, I also have a local site that is set up to display this information to the user via html and javascript (but obviously doesn't connect to the server or that jar).  I plan on using tomcat to act as a middleware server that will display the web page and handle the code that accesses the server.

I've seen it done before, but I'm not quite sure how to set it up.  Can somebody just give me the basics on where things need to go to make this work?  I think I'd be ok after that.

My Google-Fu has failed me in finding this, so really any help is appreciated.

Thanks!

答:
If you use Netbeans, you start by creating a Web Application Project (see tutorial here).

The project binds the JSP pages (the HTML) with a servlet. Inside the servlet, you access the server functions (inside the jar) and send the information back to the jsp file to display.

Netbeans will deploy the project to Tomcat for you if you select Tomcat as the default server in the Properties / Run dialog for that project.

Or you can copy the war file into the $TOMCAT_HOME/webapps/ directory. Tomcat will deploy the war file by automatically exploding it.


问:
SymmetricDS: lookup Table Router route to common and specific node
In SymmetricDS I know that 'lookuptable' in SYM_ROUTER can sync to specific node by referring a column that has the node id.

What I would want is for common data to sync to all node, how to configure this?

Example : I have 2 tables, Table 1 is Item, Table 2 is Store

ITEM_ID | ITEM_NAME | BRAND_ID

Item 1    | name | A

Item 2    | name | B

Item 3    | name | C

BRAND_ID | STORE_ID

A        | ALL

B        | 001

C       | 002

I want to sync Item 1 to ALL nodes, Item 2 to node 001, Item 3 to node 002, etc.
I will use below router to sync Item table. Item 2 and Item 3 are synced OK, but Item 1 fail to sync to all node, do you have any way to sync Item 1 ?

```<code>insert into SYM_ROUTER (
 router_id, source_node_group_id, target_node_group_id, router_type, router_expression, create_time, last_update_time
) values (
 'corp-2-store-ok','corp', 'store', 'lookuptable', 'LOOKUP_TABLE=STORE KEY_COLUMN=BRAND_ID LOOKUP_KEY_COLUMN=BRAND_ID EXTERNAL_ID_COLUMN=STORE_ID', current_timestamp, current_timestamp
);
</code>```

答:
You'll need a router with the router_type 'subselect' and router_expression something like</p>

```<code>c.external_id in (
  select :STORE_ID from dual
  union all
  select external_id from sym_node where 'ALL' = :STORE_ID
)
</code>```

Body:
In SymmetricDS I know that 'lookuptable' in SYM_ROUTER can sync to specific node by referring a column that has the node id.

What I would want is for common data to sync to all node, how to configure this?

Example : I have 2 tables, Table 1 is Item, Table 2 is Store

ITEM_ID | ITEM_NAME | BRAND_ID

Item 1    | name | A

Item 2    | name | B

Item 3    | name | C

BRAND_ID | STORE_ID

A        | ALL

B        | 001

C       | 002

I want to sync Item 1 to ALL nodes, Item 2 to node 001, Item 3 to node 002, etc.
I will use below router to sync Item table. Item 2 and Item 3 are synced OK, but Item 1 fail to sync to all node, do you have any way to sync Item 1 ?

insert into SYM_ROUTER (
 router_id, source_node_group_id, target_node_group_id, router_type, router_expression, create_time, last_update_time
) values (
 'corp-2-store-ok','corp', 'store', 'lookuptable', 'LOOKUP_TABLE=STORE KEY_COLUMN=BRAND_ID LOOKUP_KEY_COLUMN=BRAND_ID EXTERNAL_ID_COLUMN=STORE_ID', current_timestamp, current_timestamp
);

Body:
You'll need a router with the router_type 'subselect' and router_expression something like

c.external_id in (
  select :STORE_ID from dual
  union all
  select external_id from sym_node where 'ALL' = :STORE_ID
)


问:
Segmentation fault when inserting at the end of a linked list C++
Okay, so I'm trying to create a linked list of items by adding them one by one onto the end, and I also wanna print out the results.

I'm only showing part of my code (the part that I need work on), so ignore all the libraries that I'm not really making use of in this snippet:

```<code>#include <string>
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

struct Item {
    char letter;
    Item *next;
};

class List {
  public:
    List();
    void InsertEnd(char key);
    void Display();
    bool IsEmpty();
    void SizeOf();
  private:
    Item *head;
    Item *tail;
    int size;
};

List::List() {
    head = NULL;
    tail = NULL;
    size = 0;
}

void List::InsertEnd(char key) {
    //new item we're adding to the end
    Item* addOn = new Item();
    addOn->letter = key;
    addOn->next = NULL;

    //temporary item to traverse through list
    Item* temp = head;

    //if list is empty, head and tail both point to it
    if ( IsEmpty() ) {
        head->next = addOn;
        tail->next = addOn;
    } else {
        //once temp = tail
        if (temp->next == NULL) {
            tail->next = temp;
            temp = addOn;
        }
    }

    //update size of list
    SizeOf();

}

void List::Display() {
    cout << "Items:" << endl;
    for (Item* curr = head->next; curr != NULL; curr = curr->next) {
      cout << curr->letter << endl;
    }

cout << size << " items." << endl;

}

bool List::IsEmpty() {
    if (size == 0)
        return true;
    else
        return false;
}

void List::SizeOf() {
    size++;
}

int main() {
    List* test = new List;

    test->InsertEnd('A');
    test->InsertEnd('B');
    test->InsertEnd('C');

    test->Display();

    return 0;
}
</code>```

It compiles just fine, but when I run it, literally the only thing I get is "Segmentation fault." ???

答:
If the list is empty then head->next will be NULL, yet you say head->next = addOn;. Shouldn't it be head = addOn; ?

In fact this whole block of code is rubbish:

```<code>if ( IsEmpty() ) {
    // head and tail are both null so both of these lines
    // invoke undefined behavior (you cant say NULL->field = something)
    head->next = addOn;
    tail->next = addOn;
} else {
    //once temp = tail
    // temp = head. Shouldn't you just be putting "addOn" as the next item
    // in the list after tail? What if temp->next != NULL?
    if (temp->next == NULL) {
        // tail->next = head (because temp == head). That makes no sense.
        tail->next = temp;
        // So some temp variable = addOn? addOn doesn't actually go into the list?
        // Thats a memory leak right there.
        temp = addOn;
    }
}
</code>```

In pseudo code what you want is something like this:

```<code>if (IsEmpty())
{
    head = addOn;
    tail = addOn;
}
else
{
    // special case when 1 item in the list (i.e. head == tail)
    if (head == tail)
    {
        // new item comes after head
        head->next = addOn;
    }
    else
    {
        // new item comes after tail
        tail->next = addOn;
    }
    // tail is now the item just added.
    tail = addOn;
}
</code>```

Body:
Okay, so I'm trying to create a linked list of items by adding them one by one onto the end, and I also wanna print out the results.

I'm only showing part of my code (the part that I need work on), so ignore all the libraries that I'm not really making use of in this snippet:

#include <string>
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

struct Item {
    char letter;
    Item *next;
};

class List {
  public:
    List();
    void InsertEnd(char key);
    void Display();
    bool IsEmpty();
    void SizeOf();
  private:
    Item *head;
    Item *tail;
    int size;
};

List::List() {
    head = NULL;
    tail = NULL;
    size = 0;
}

void List::InsertEnd(char key) {
    //new item we're adding to the end
    Item* addOn = new Item();
    addOn->letter = key;
    addOn->next = NULL;

    //temporary item to traverse through list
    Item* temp = head;

    //if list is empty, head and tail both point to it
    if ( IsEmpty() ) {
        head->next = addOn;
        tail->next = addOn;
    } else {
        //once temp = tail
        if (temp->next == NULL) {
            tail->next = temp;
            temp = addOn;
        }
    }

    //update size of list
    SizeOf();

}

void List::Display() {
    cout << "Items:" << endl;
    for (Item* curr = head->next; curr != NULL; curr = curr->next) {
      cout << curr->letter << endl;
    }

cout << size << " items." << endl;

}

bool List::IsEmpty() {
    if (size == 0)
        return true;
    else
        return false;
}

void List::SizeOf() {
    size++;
}

int main() {
    List* test = new List;

    test->InsertEnd('A');
    test->InsertEnd('B');
    test->InsertEnd('C');

    test->Display();

    return 0;
}

It compiles just fine, but when I run it, literally the only thing I get is "Segmentation fault." ???

Body:
If the list is empty then head->next will be NULL, yet you say head->next = addOn;. Shouldn't it be head = addOn; ?

In fact this whole block of code is rubbish:

if ( IsEmpty() ) {
    // head and tail are both null so both of these lines
    // invoke undefined behavior (you cant say NULL->field = something)
    head->next = addOn;
    tail->next = addOn;
} else {
    //once temp = tail
    // temp = head. Shouldn't you just be putting "addOn" as the next item
    // in the list after tail? What if temp->next != NULL?
    if (temp->next == NULL) {
        // tail->next = head (because temp == head). That makes no sense.
        tail->next = temp;
        // So some temp variable = addOn? addOn doesn't actually go into the list?
        // Thats a memory leak right there.
        temp = addOn;
    }
}

In pseudo code what you want is something like this:

if (IsEmpty())
{
    head = addOn;
    tail = addOn;
}
else
{
    // special case when 1 item in the list (i.e. head == tail)
    if (head == tail)
    {
        // new item comes after head
        head->next = addOn;
    }
    else
    {
        // new item comes after tail
        tail->next = addOn;
    }
    // tail is now the item just added.
    tail = addOn;
}


问:
Swift Timer App
I was trying to build a simple ios timer app using swift3. I successfully created an app using the following code. It has three buttons, one to start the timer, one to stop the timer which means reset and one to pause the timer. all the buttons are working but when I click on start once again while the timer is running, the timer interval speeds up (means calls the selector function twice within a second). how to solve this problem.
Here is my code</p>

```<code>@IBOutlet weak var lbl: UILabel!
var time = 0
var timer = Timer()

@IBOutlet weak var start: UIButton!
@IBOutlet weak var stop: UIButton!
@IBOutlet weak var pause: UIButton!
@IBAction func start(_ sender: AnyObject) {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
}
@IBAction func stop(_ sender: AnyObject) {
    //timer.invalidate()
    time = 0
    lbl.text = "0"
}
@IBAction func pause(_ sender: AnyObject) {
    timer.invalidate()
}
override func viewDidLoad() {
    super.viewDidLoad()

}

func action() {
    time += 1
    lbl.text = String(time)
}
</code>```

答:
One Mistake in Source code.

First Stop exist timer then start new timer.

Code for that is below.

```<code>@IBAction func start(_ sender: AnyObject) {
    timer.invalidate()
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
}
</code>```

And for stop timer use invalidate timer function.

```<code>@IBAction func stop(_ sender: AnyObject) {
    timer.invalidate()
}
</code>```

Title: Swift Timer App

Body:
I was trying to build a simple ios timer app using swift3. I successfully created an app using the following code. It has three buttons, one to start the timer, one to stop the timer which means reset and one to pause the timer. all the buttons are working but when I click on start once again while the timer is running, the timer interval speeds up (means calls the selector function twice within a second). how to solve this problem.
Here is my code

@IBOutlet weak var lbl: UILabel!
var time = 0
var timer = Timer()

@IBOutlet weak var start: UIButton!
@IBOutlet weak var stop: UIButton!
@IBOutlet weak var pause: UIButton!
@IBAction func start(_ sender: AnyObject) {
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
}
@IBAction func stop(_ sender: AnyObject) {
    //timer.invalidate()
    time = 0
    lbl.text = "0"
}
@IBAction func pause(_ sender: AnyObject) {
    timer.invalidate()
}
override func viewDidLoad() {
    super.viewDidLoad()

}

func action() {
    time += 1
    lbl.text = String(time)
}

Body:
One Mistake in Source code.

First Stop exist timer then start new timer.

Code for that is below.

@IBAction func start(_ sender: AnyObject) {
    timer.invalidate()
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)
}

And for stop timer use invalidate timer function.

@IBAction func stop(_ sender: AnyObject) {
    timer.invalidate()
}


问:
How to configure C# Api to display JSON directly from browser? (but not XML)
First, to clarify that, my C# API is working properly. I am able to retrieve the json data from my javascript.

But, I am curious, whenever I access my API directly through the browser, it shows this:

However, when I access JSON hosted by others (such as myjson), they are able to display the json directly from the browser:

Here's my code briefly,

```<code>public Object Get()
{
  ...// form object from my data
  return myObject;
}
</code>```

Is there any configuration needed?

答:
On your Application_Start you can configure the formatter as needed
ex:

```<code>protected void Application_Start()
{
     GlobalConfiguration.Configure(ServerConfig.Configure);
}

void Configure(HttpConfiguration config)
{
      var formatters = config.Formatters;
      var jsonFormatter = formatters.JsonFormatter;
      // "text/html" is the default browser request content type
      jsonFormatter.SupportedMediaTypes.Add(new
      MediaTypeHeaderValue("text/html"));
      WebApiConfig.Register(config);
      RegisterDependencies();
 }
</code>```

Body:
First, to clarify that, my C# API is working properly. I am able to retrieve the json data from my javascript.

But, I am curious, whenever I access my API directly through the browser, it shows this:

However, when I access JSON hosted by others (such as myjson), they are able to display the json directly from the browser:

Here's my code briefly,

public Object Get()
{
  ...// form object from my data
  return myObject;
}

Is there any configuration needed?

Body:
On your Application_Start you can configure the formatter as needed
ex:

protected void Application_Start()
{
     GlobalConfiguration.Configure(ServerConfig.Configure);
}

void Configure(HttpConfiguration config)
{
      var formatters = config.Formatters;
      var jsonFormatter = formatters.JsonFormatter;
      // "text/html" is the default browser request content type
      jsonFormatter.SupportedMediaTypes.Add(new
      MediaTypeHeaderValue("text/html"));
      WebApiConfig.Register(config);
      RegisterDependencies();
 }


问:
PHP - preg_match fail
Could someone tell me why the following preg_match search works:

```<code>preg_match("/\xF0\x49\xF7\xF8..\xF3\xF8/s", $bin, $matches2, PREG_OFFSET_CAPTURE);
</code>```

while this doesnt give any result:

```<code>preg_match("/\x3F.\x0D\x01\x3E.\xF3\xFA..\x43\xFA.\x04\xFD\x02/s", $bin, $matches, PREG_OFFSET_CAPTURE);
</code>```

Both possibilities are inside $bin.

Further question:

What is the best way to search the following positions, where XX are variables and could be anything (1 match or more) in the $bin file, at least i need the beginning position of each match.

I need to search for this:

```<code>3F XX 0D 01 3E XX F3 FA XX XX 43 FA XX 04 FD 02
</code>```

Example matches:

```<code>**4 example matches**
1) 3F 64 0D 01 3E 64 F3 FA 86 F8 43 FA E1 04 FD 02
2) 3F 5C 0D 01 3E 5C F3 FA 9C F8 43 FA B6 04 FD 02
3) 3F 5B 0D 01 3E 5B F3 FA 9A F8 43 FA 69 04 FD 02
4) 3F 6B 0D 01 3E 6B F3 FA 78 F8 43 FA 38 04 FD 02
</code>```

I can search in a $bin file where $bin contains raw binary, or convert it like bin2hex($bin), ..

I found out this way now, and it seems to be working, but, is this a "nice" and fast way to do this? I have more then 300MB ram already allocated in my script now, and want it make a little bit resource-friendlier.

```<code>preg_match_all("/3F[A-Z0-9]{2}0D013E[A-Z0-9]{2}F3FA[A-Z0-9]{4}43FA[A-Z0-9]{2}04FD02/", $binhex, $matches, PREG_OFFSET_CAPTURE);
</code>```

答:
Your latest regex was missing several spaces and the {4} group wasn't going to match your samples.  Corrected, it looks like this:
3F [A-F\d]{2} 0D 01 3E [A-F\d]{2} F3 FA [A-F\d]{2} [A-F\d]{2} 43 FA [A-F\d]{2} 04 FD 02  This runs at 172steps which is nothing to be disappointed about.

When selecting the right regex pattern for your project, it is best to identify your priorities across:

Pattern Brevity & Readability - more of a concern if working in a team or updating frequently.

Pattern Speed/Steps -- certainly a concern when working with big volumes of data.

Pattern Validation Strength -- it is the dev's responsibility to understand what is necessary.

Let's consider a few options that I've prepared (there are more, regex is a rabbit hole).

(?:.. ?){16}
272steps: this prioritizes pattern brevity, at a large cost of validation strength and speed

(?:[A-F\d]{2} ?){16}
208steps: this prioritizes brevity, with slightly improved validation and speed

3F \d[A-F\d] 0D 01 3E \d[A-F\d] F3 FA \d[A-F\d] F8 43 FA [A-F\d]\d 04 FD 02
192steps: this is very literal and prioritizes validation, with a cost on pattern length and speed

3F [A-F\d]{2} 0D 01 3E [A-F\d]{2} F3 FA [A-F\d]{2} [A-F\d]{2} 43 FA [A-F\d]{2} 04 FD 02
172steps: the quantifier {2} increases speed, but with a slight impact on validation because the broadened character ranges in each pair

[A-F\d]{2} [A-F\d]{2} [A-F\d]{2} [A-F\d]{2} [A-F\d]{2} [A-F\d]{2} [A-F\d]{2} [A-F\d]{2} [A-F\d]{2} [A-F\d]{2} [A-F\d]{2} [A-F\d]{2} [A-F\d]{2} [A-F\d]{2} [A-F\d]{2} [A-F\d]{2} 135steps: this is the largest sensible trade off when prioritizing speed, pattern brevity and validation strength are largely impacted

[A-F\d ]{47} 12steps: _if validation only needs to protect from malicious strings rather than checking string quality, this may be the go.

Then again, if your demand on validation is this low, then perhaps avoid the expense of regex/preg_match_all all together. Perhaps use str_split($str,49) or similar.

So the decision is purely yours, but it is best to have a few options to compare and contrast.

Whenever you have questions or doubts about a regex pattern, head over to regex101.com throw in some sample data and have a play with a few regex patterns.  The page will show you errors, steps/speed, and captured data -- it's pretty handy.

Title: PHP - preg_match fail

Body:
Could someone tell me why the following preg_match search works:

preg_match("/\xF0\x49\xF7\xF8..\xF3\xF8/s", $bin, $matches2, PREG_OFFSET_CAPTURE);

while this doesnt give any result:

preg_match("/\x3F.\x0D\x01\x3E.\xF3\xFA..\x43\xFA.\x04\xFD\x02/s", $bin, $matches, PREG_OFFSET_CAPTURE);

Both possibilities are inside $bin.

Further question:

What is the best way to search the following positions, where XX are variables and could be anything (1 match or more) in the $bin file, at least i need the beginning position of each match.

I need to search for this:

3F XX 0D 01 3E XX F3 FA XX XX 43 FA XX 04 FD 02

Example matches:

**4 example matches**
1) 3F 64 0D 01 3E 64 F3 FA 86 F8 43 FA E1 04 FD 02
2) 3F 5C 0D 01 3E 5C F3 FA 9C F8 43 FA B6 04 FD 02
3) 3F 5B 0D 01 3E 5B F3 FA 9A F8 43 FA 69 04 FD 02
4) 3F 6B 0D 01 3E 6B F3 FA 78 F8 43 FA 38 04 FD 02

I can search in a $bin file where $bin contains raw binary, or convert it like bin2hex($bin), ..

I found out this way now, and it seems to be working, but, is this a "nice" and fast way to do this? I have more then 300MB ram already allocated in my script now, and want it make a little bit resource-friendlier.

preg_match_all("/3F[A-Z0-9]{2}0D013E[A-Z0-9]{2}F3FA[A-Z0-9]{4}43FA[A-Z0-9]{2}04FD02/", $binhex, $matches, PREG_OFFSET_CAPTURE);