问:
How to get data-tables in asp.net to show only certain data
I cannot figure how to get the data to show only the entries with John. I am using dataTables, so not sure how to get it to work. When I launch the app it still shows all the users. Here is what I got so far any help would be appreciated. I am trying to get a where clause into the program do I create it in the model not in the controller.

Controller

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Asp.NetMVCCrud.Models;

namespace Asp.NetMVCCrud.Controllers
{
    public class EmployeeController : Controller
    {
        // GET: Employee
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult GetData()
        {
            using(DBModel db = new DBModel())
            {
               db.Employees.Where(Employee => Employee.Name == "John");
                List<Employee> empList = db.Employees.ToList<Employee>();
                return Json(new { data = empList }, JsonRequestBehavior.AllowGet);
            }

        }
    }
}
</code>```

Employee model generated

```<code>namespace Asp.NetMVCCrud.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Employee
    {
        public int EmployeeID { get; set; }
        public string Name { get; set; }
        public string Postion { get; set; }
        public string Office { get; set; }
        public Nullable<int> Age { get; set; }
        public Nullable<int> Salary { get; set; }
    }
}
</code>```

view index

```<code>@{
    ViewBag.Title = "Employee List";
}

<h2>Employee Crud Operations</h2>
<table id="employeetable" class="table table-striped table-bordered">
  <thead>
      <tr>
          <th>Name</th>
          <th>Position</th>
          <th>Office</th>
          <th>Age</th>
          <th>Salary</th>
      </tr>
  </thead>
</table>
<link href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css" rel="stylesheet" />

@section scripts{
    <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#employeetable").DataTable({
                "ajax": {
                    "url": "/Employee/GetData",
                    "type": "GET",
                    "datatype":"json"

                },
                "columns": [

                    { "data": "Name" },
                      { "data": "Postion" },
                        { "data": "Office" },
                          { "data": "Age" },
                            { "data": "Salary" },

                ]

            });

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

答:
Because your code is returning empList which is all the employees.

You have a LINQ query (this line db.Employees.Where(Employee => Employee.Name == "John");) to get the the filtered subset, but you are not executing that query or using the result of that to return the result.

Return only the filtered result. This should work

```<code>var filteredList = db.Employees.Where(e=> e.Name == "John").ToList();
return Json(new { data = filteredList }, JsonRequestBehavior.AllowGet);
</code>```

Body:
I cannot figure how to get the data to show only the entries with John. I am using dataTables, so not sure how to get it to work. When I launch the app it still shows all the users. Here is what I got so far any help would be appreciated. I am trying to get a where clause into the program do I create it in the model not in the controller.

Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Asp.NetMVCCrud.Models;

namespace Asp.NetMVCCrud.Controllers
{
    public class EmployeeController : Controller
    {
        // GET: Employee
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult GetData()
        {
            using(DBModel db = new DBModel())
            {
               db.Employees.Where(Employee => Employee.Name == "John");
                List<Employee> empList = db.Employees.ToList<Employee>();
                return Json(new { data = empList }, JsonRequestBehavior.AllowGet);
            }

        }
    }
}

Employee model generated

namespace Asp.NetMVCCrud.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Employee
    {
        public int EmployeeID { get; set; }
        public string Name { get; set; }
        public string Postion { get; set; }
        public string Office { get; set; }
        public Nullable<int> Age { get; set; }
        public Nullable<int> Salary { get; set; }
    }
}

view index

@{
    ViewBag.Title = "Employee List";
}

Employee Crud Operations

          Name
          Position
          Office
          Age
          Salary

<link href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css" rel="stylesheet" />

@section scripts{

    }

Body:
Because your code is returning empList which is all the employees.

You have a LINQ query (this line db.Employees.Where(Employee => Employee.Name == "John");) to get the the filtered subset, but you are not executing that query or using the result of that to return the result.

Return only the filtered result. This should work

var filteredList = db.Employees.Where(e=> e.Name == "John").ToList();
return Json(new { data = filteredList }, JsonRequestBehavior.AllowGet);


来源: stackexchange

问:
File Streaming in Java
I'm currently developing 3D graphics application using JOGL (Java OpenGL binding). In brief, I have a huge landscape binary file. Due to its size, I have to stream terrain chunks in the run-time. Therefore, we explicitly see the random access concern. I have already finished the first (and dirty :)) implementation (perhaps it is multi-threaded), where I'm using a foolish approach...  Here is the initialization of it:

```<code>dataInputStream = new DataInputStream(new BufferedInputStream(fileInputStream,4 * 1024);
dataInputStream.mark(dataInputStream.available());
</code>```

And when I need to read (stream) special chunk (I already know its "offset" in the file) I'm performing the following (shame on me :)):

```<code>dataInputStream.reset();
dataInputStream.skipBytes(offset);
dataInputStream.read(whatever I need...);
</code>```

Since I had little experience that was the first thing I could think about :)
So, until now I have read 3 useful and quite interesting articles (I'm suggesting you to read them, perhaps if you are interested in this topic)

Byte Buffers and Non-Heap Memory - Mr. Gregory seems to be literate in Java NIO.

Java tip: How to read files quickly [http://nadeausoftware.com/articles/2008/02/java_tip_how_read_files_quickly] - That's an interesting benchmark.

Articles: Tuning Java I/O Performance [http://java.sun.com/developer/technicalArticles/Programming/PerfTuning/] - Simple Sun recommendations, but please scroll down and have a look at "Random Access" section there; they show a simple implementation of RandomAccessFile (RAF) with self-buffering improvement.

Mr. Gregory provides several *.java files in the end of his article. One of them is a benchmarking between FileChannel + ByteBuffer + Mapping (FBM) and RAF. He says that he noticed 4x speedup when using FBM compared to RAF. I have ran this benchmark in the following conditions:

The offset (e. g. place of access) is generated randomly (in the file scope, e. g. 0 - file.length());

File size is 220MB;

1 000 000 accesses (75% reads and 25% writes)

The results were stunning:

~ 28 sec for RAF!
~ 0.2 sec for FBM!

However, his implementation of RAF in this benchmark doesn't have self-buffering (the 3rd article tells about one), so I guess it is the "RandomAccessFile.seek" method calling, who drops performance so hard.

Ok, now after all those things I've learnt there is 1 question and 1 dilemma :)

Question: When we are mapping a file using "FileChannel.map" does Java copy the whole file contents into the MappedByteBuffer? Or does it just emulate it? If it copies, then using FBM approach is not suitable for my situation, is it?

Dilemma: Depends on your answers on the question...

If mapping copies a file, then it seems like I have only 2 possible solutions to go: RAF + self-buffering (the one from the 3rd article) or make use of position in FileChannel (not with mapping)... Which one would be better?

If mapping doesn't copy a file, then I have 3 options: two previous ones and FBM itself.

Edit: Here is one more question. Some of you here say that mapping doesn't copy file into MappedByteBuffer. Ok then, why can't I map 1GB file then, I'm getting "failed to map" message...

P. S. I would like to receive a fulfilled answer with advices, since I'm not able to find the consistent information over this topic in the internet.

Thanks :)

答:
No, the data is not buffered. A MappedByteBuffer references the data using a pointer. In other words, the data is not copied, it is simply mapped into physical memory. See the API docs if you haven't already.

A memory-mapped file is a segment of
  virtual memory which has been assigned
  a direct byte-for-byte correlation
  with some portion of a file or
  file-like resource. This resource is
  typically a file that is physically
  present on-disk, but can also be a
  device, shared memory object, or other
  resource that the operating system can
  reference through a file descriptor.
  Once present, this correlation between
  the file and the memory space permits
  applications to treat the mapped
  portion as if it were primary memory.

Source: Wikipedia

If you are going to be reading data quite frequently, it is a good idea to at least cache some of it.

ContentLicense: CC BY-SA 2.5

Title: File Streaming in Java

Body:
I'm currently developing 3D graphics application using JOGL (Java OpenGL binding). In brief, I have a huge landscape binary file. Due to its size, I have to stream terrain chunks in the run-time. Therefore, we explicitly see the random access concern. I have already finished the first (and dirty :)) implementation (perhaps it is multi-threaded), where I'm using a foolish approach...  Here is the initialization of it:

dataInputStream = new DataInputStream(new BufferedInputStream(fileInputStream,4 * 1024);
dataInputStream.mark(dataInputStream.available());

And when I need to read (stream) special chunk (I already know its "offset" in the file) I'm performing the following (shame on me :)):

dataInputStream.reset();
dataInputStream.skipBytes(offset);
dataInputStream.read(whatever I need...);

Since I had little experience that was the first thing I could think about :)
So, until now I have read 3 useful and quite interesting articles (I'm suggesting you to read them, perhaps if you are interested in this topic)

Byte Buffers and Non-Heap Memory - Mr. Gregory seems to be literate in Java NIO.

Java tip: How to read files quickly [http://nadeausoftware.com/articles/2008/02/java_tip_how_read_files_quickly] - That's an interesting benchmark.

Articles: Tuning Java I/O Performance [http://java.sun.com/developer/technicalArticles/Programming/PerfTuning/] - Simple Sun recommendations, but please scroll down and have a look at "Random Access" section there; they show a simple implementation of RandomAccessFile (RAF) with self-buffering improvement.

Mr. Gregory provides several *.java files in the end of his article. One of them is a benchmarking between FileChannel + ByteBuffer + Mapping (FBM) and RAF. He says that he noticed 4x speedup when using FBM compared to RAF. I have ran this benchmark in the following conditions:

The offset (e. g. place of access) is generated randomly (in the file scope, e. g. 0 - file.length());

File size is 220MB;

1 000 000 accesses (75% reads and 25% writes)

The results were stunning:

~ 28 sec for RAF!
~ 0.2 sec for FBM!

However, his implementation of RAF in this benchmark doesn't have self-buffering (the 3rd article tells about one), so I guess it is the "RandomAccessFile.seek" method calling, who drops performance so hard.

Ok, now after all those things I've learnt there is 1 question and 1 dilemma :)

Question: When we are mapping a file using "FileChannel.map" does Java copy the whole file contents into the MappedByteBuffer? Or does it just emulate it? If it copies, then using FBM approach is not suitable for my situation, is it?

Dilemma: Depends on your answers on the question...

If mapping copies a file, then it seems like I have only 2 possible solutions to go: RAF + self-buffering (the one from the 3rd article) or make use of position in FileChannel (not with mapping)... Which one would be better?

If mapping doesn't copy a file, then I have 3 options: two previous ones and FBM itself.

Edit: Here is one more question. Some of you here say that mapping doesn't copy file into MappedByteBuffer. Ok then, why can't I map 1GB file then, I'm getting "failed to map" message...

P. S. I would like to receive a fulfilled answer with advices, since I'm not able to find the consistent information over this topic in the internet.

Thanks :)


问:
Scala regex, how to fix
here is my code:

```<code>object test extends App {

  private val PLAYER_REGEX = """[\s\S]*(?:<td class="align-middle plus-size"> <s class="text-muted">|<td class="align-middle plus-size">)(.*)(?:</s> </td></tr>|</td></tr>)""".r
  val str ="""<td class="align-middle plus-size"> <s class="text-muted">first</s> </td></tr>"""
  val str2 ="""<td class="align-middle plus-size">second</td></tr>"""

  private def find(str:String) = {
    PLAYER_REGEX.findFirstMatchIn(str) match {
      case Some(data) => data.group(1).trim
      case None => "Not found"
    }
  }
  println(find(str))
  println(find(str2))
}
</code>```

And Output is

```<code>first</s>
second
</code>```

My question is - why those redundant

```<code></s>
</code>```

in first case? I thought that

```<code>(?:</s> </td></tr>|</td></tr>)
</code>```

should select first occurence

```<code></s> </td></tr>
</code>```

but looks like it select

```<code></td></tr>???
</code>```

Off course I can trim it, but it looks ugly.
If you can provide another regex I'll also will be glad:)

答:
It's caused by this greedy quantifier beforehand:

```<code>…(.*)…
</code>```

Instead, use the lazy version:

```<code>…(.*?)…
</code>```

ContentLicense: CC BY-SA 3.0

Title: Scala regex, how to fix

Body:
here is my code:

object test extends App {

  private val PLAYER_REGEX = """[\s\S]*(?: <s class="text-muted">|)(.*)(?:</s>
|
)""".r
  val str =""" <s class="text-muted">first</s>
"""
  val str2 ="""second
"""

  private def find(str:String) = {
    PLAYER_REGEX.findFirstMatchIn(str) match {
      case Some(data) => data.group(1).trim
      case None => "Not found"
    }
  }
  println(find(str))
  println(find(str2))
}

And Output is

first</s>
second

My question is - why those redundant

</s>

in first case? I thought that

(?:</s>
|
)

should select first occurence

</s>

but looks like it select

???

Off course I can trim it, but it looks ugly.
If you can provide another regex I'll also will be glad:)

Body:
It's caused by this greedy quantifier beforehand:

…(.*)…

Instead, use the lazy version:

…(.*?)…


问:
How can I declare a function or variable in a file and use it always in Swift
Currently I am working on a project and I have to use an alert message almost in every view controller. Particularly this one:

```<code>func showMessage(myMessage: String) {
    let myAlert = UIAlertController(title: "ALERT", message: myMessage, preferredStyle: UIAlertControllerStyle.alert)
    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
    myAlert.addAction(okAction)
    self.present(myAlert, animated: true, completion: nil)
}
</code>```

Using the same code over an over again makes my code verbose. This scenario goes with some other functions and some variables also. How can I declare this function somewhere in a different file and use it whenever necessary? Shall I use a singleton pattern like:

```<code>static let sharedInstance = viewController()
</code>```

If so, please show me an example.

答:
Use a custom class for the view controllers in your app. Instead of subclassing UIViewController, each of your view controllers would subclass your CustomViewController class. Here's an example:

```<code>class CustomViewController: UIViewController {
    func showMessage(myMessage: String) {
        let myAlert = UIAlertController(title: "ALERT", message: myMessage, preferredStyle: UIAlertControllerStyle.alert)
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
        myAlert.addAction(okAction)
        self.present(myAlert, animated: true, completion: nil)
    }
}
</code>```

Each view controller you create that subclasses CustomViewController would then have access to the showMessage function.

Body:
Currently I am working on a project and I have to use an alert message almost in every view controller. Particularly this one:

func showMessage(myMessage: String) {
    let myAlert = UIAlertController(title: "ALERT", message: myMessage, preferredStyle: UIAlertControllerStyle.alert)
    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
    myAlert.addAction(okAction)
    self.present(myAlert, animated: true, completion: nil)
}

Using the same code over an over again makes my code verbose. This scenario goes with some other functions and some variables also. How can I declare this function somewhere in a different file and use it whenever necessary? Shall I use a singleton pattern like:

static let sharedInstance = viewController()

If so, please show me an example.

Body:
Use a custom class for the view controllers in your app. Instead of subclassing UIViewController, each of your view controllers would subclass your CustomViewController class. Here's an example:

class CustomViewController: UIViewController {
    func showMessage(myMessage: String) {
        let myAlert = UIAlertController(title: "ALERT", message: myMessage, preferredStyle: UIAlertControllerStyle.alert)
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
        myAlert.addAction(okAction)
        self.present(myAlert, animated: true, completion: nil)
    }
}

Each view controller you create that subclasses CustomViewController would then have access to the showMessage function.


问:
Ruby 1.8.6 Array#uniq not removing duplicate hashes
I have this array, in a ruby 1.8.6 console:

```<code>arr = [{:foo => "bar"}, {:foo => "bar"}]
</code>```

both elements are equal to each other:

```<code>arr[0] == arr[1]
=> true
#just in case there's some "==" vs "===" oddness...
arr[0] === arr[1]
=> true
</code>```

But, arr.uniq doesn't remove the duplicates:

```<code>arr.uniq
=> [{:foo=>"bar"}, {:foo=>"bar"}]
</code>```

Can anyone tell me what's going on here?

EDIT:  I can write a not very clever uniqifier which uses include? as follows:

```<code>uniqed = []
arr.each do |hash|
  unless uniqed.include?(hash)
    uniqed << hash
  end
end;false
uniqed
=> [{:foo=>"bar"}]
</code>```

This produces the correct result, which makes the failure of uniq even more mysterious.

EDIT 2:  Some notes on what's going on, possibly just for my own clarity.  As @Ajedi32 points out in the comments, the failure to uniqify comes from the fact that the two elements are different objects.  Some classes define eql? and hash methods, used for comparison, to mean "are these effectively the same thing, even if they're not the same object in memory".  String does this for example, which is why you can define two variables to be "foo" and they are said to be equal to one another, even though they're not the same object.

The Hash class doesn't do this, in Ruby 1.8.6, and so when .eql? and .hash are called on a hash object (the .hash method has nothing to do with the Hash data type - it's like the checksum kind of hash) it falls back to using the methods defined in the Object base class, which simply say "Is it the same object in memory".

The == and === operators, for hash objects, already do what I want, ie to say that two hashes are the same if their contents are the same.  I've overriden Hash#eql? to use these, like so:

```<code>class Hash
  def eql?(other_hash)
    self == other_hash
  end
end
</code>```

But, I'm not sure how to handle Hash#hash: that is, I don't know how to generate a checksum which will be the same for two hashes whose contents are the same and always different for two hashes with different contents.

@Ajedi32 suggested I have a look at Rubinius' implentation of the Hash#hash method here https://github.com/rubinius/rubinius/blob/master/core/hash.rb#L589 , and my version of Rubinius' implementation looks like this:

```<code>class Hash
  def hash
    result = self.size
    self.each do |key,value|
      result ^= key.hash
      result ^= value.hash
    end
    return result
  end
end
</code>```

and this does seem to work, although I don't know what the "^=" operator does, which makes me a bit nervous.  Also, it's very slow - about 50x as slow based on some primitive benchmarking.  This might make it too slow to use.

EDIT 3: A bit of research has revealed that "^" is the Bitwise Exclusive OR operator.  When we have two inputs, an XOR returns 1 if the inputs are different (ie it returns 0 for 0,0 and 1,1 and 1 for 0,1 and 1,0).

So, at first I thought that means that

```<code>result ^= key.hash
</code>```

is shorthand for

```<code>result = result ^ key.hash
</code>```

In other words, do an XOR between the current value of result and the other thing, and then save that in result. I still don't quite get the logic of this though.  I thought that perhaps the ^ operator was something to do with pointers, because calling it on variables works while calling it on the value of the variable doesn't work:  eg

```<code>var = 1
=> 1
var ^= :foo
=> 14904
1 ^= :foo
SyntaxError: compile error
(irb):11: syntax error, unexpected tOP_ASGN, expecting $end
</code>```

So, it's fine with calling ^= on a variable but not the value of the variable, which made me think it's something to do with referencing/dereferencing.

Later implementations of Ruby also have C code for the Hash#hash method, and Rubinius' implementaion seems too slow.  Bit stuck...

答:
For efficiency reasons, Array#uniq does not compare values using == or even ===. According to the docs:

It compares values using their hash and eql? methods for efficiency.

(Note I linked the docs for 2.4.2 here. While the docs for 1.8.6 do not include this statement, I believe it still holds true for that version of Ruby.)

In Ruby 1.8.6, neither Hash#hash nor Hash#eql? are implemented, so they fallback to using Object#hash and Object#eql?:

Equality—At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendent classes to provide class-specific meaning.

[...]

The eql? method returns true if obj and anObject have the same value. Used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==.

So according to Array#uniq, those two hashes are different objects, and are therefore unique.

To fix this, you can try defining Hash#hash and Hash#eql? yourself. The details of how to do this are left as an exercise to the reader. You may find it helpful however to refer to Rubinius's implementation of these methods.

Body:
I have this array, in a ruby 1.8.6 console:

arr = [{:foo => "bar"}, {:foo => "bar"}]

both elements are equal to each other:

arr[0] == arr[1]
=> true
#just in case there's some "==" vs "===" oddness...
arr[0] === arr[1]
=> true

But, arr.uniq doesn't remove the duplicates:

arr.uniq
=> [{:foo=>"bar"}, {:foo=>"bar"}]

Can anyone tell me what's going on here?

EDIT:  I can write a not very clever uniqifier which uses include? as follows:

uniqed = []
arr.each do |hash|
  unless uniqed.include?(hash)
    uniqed << hash
  end
end;false
uniqed
=> [{:foo=>"bar"}]

This produces the correct result, which makes the failure of uniq even more mysterious.

EDIT 2:  Some notes on what's going on, possibly just for my own clarity.  As @Ajedi32 points out in the comments, the failure to uniqify comes from the fact that the two elements are different objects.  Some classes define eql? and hash methods, used for comparison, to mean "are these effectively the same thing, even if they're not the same object in memory".  String does this for example, which is why you can define two variables to be "foo" and they are said to be equal to one another, even though they're not the same object.

The Hash class doesn't do this, in Ruby 1.8.6, and so when .eql? and .hash are called on a hash object (the .hash method has nothing to do with the Hash data type - it's like the checksum kind of hash) it falls back to using the methods defined in the Object base class, which simply say "Is it the same object in memory".

The == and === operators, for hash objects, already do what I want, ie to say that two hashes are the same if their contents are the same.  I've overriden Hash#eql? to use these, like so:

class Hash
  def eql?(other_hash)
    self == other_hash
  end
end

But, I'm not sure how to handle Hash#hash: that is, I don't know how to generate a checksum which will be the same for two hashes whose contents are the same and always different for two hashes with different contents.

@Ajedi32 suggested I have a look at Rubinius' implentation of the Hash#hash method here https://github.com/rubinius/rubinius/blob/master/core/hash.rb#L589 , and my version of Rubinius' implementation looks like this:

class Hash
  def hash
    result = self.size
    self.each do |key,value|
      result ^= key.hash
      result ^= value.hash
    end
    return result
  end
end

and this does seem to work, although I don't know what the "^=" operator does, which makes me a bit nervous.  Also, it's very slow - about 50x as slow based on some primitive benchmarking.  This might make it too slow to use.

EDIT 3: A bit of research has revealed that "^" is the Bitwise Exclusive OR operator.  When we have two inputs, an XOR returns 1 if the inputs are different (ie it returns 0 for 0,0 and 1,1 and 1 for 0,1 and 1,0).

So, at first I thought that means that

result ^= key.hash

is shorthand for

result = result ^ key.hash

In other words, do an XOR between the current value of result and the other thing, and then save that in result. I still don't quite get the logic of this though.  I thought that perhaps the ^ operator was something to do with pointers, because calling it on variables works while calling it on the value of the variable doesn't work:  eg

var = 1
=> 1
var ^= :foo
=> 14904
1 ^= :foo
SyntaxError: compile error
(irb):11: syntax error, unexpected tOP_ASGN, expecting $end

So, it's fine with calling ^= on a variable but not the value of the variable, which made me think it's something to do with referencing/dereferencing.

Later implementations of Ruby also have C code for the Hash#hash method, and Rubinius' implementaion seems too slow.  Bit stuck...


问:
Is it possible to pass the reference to the i-th element of a primitive array?
Right now, somewhere in my code, I am passing a reference to a primitive, for example an Int

```<code>val i = 0
</code>```

to

```<code>fun whatever(i: KMutableProperty0<Int>)
</code>```

as

```<code>whatever(::i)
</code>```

to being able to get/set its value from within the function

Everything worked great so far.

I'd like now to do the same for an i-th element of a primitive array, such as an IntArray

```<code>val arr = intArrayOf(1, 2, 3)

whatever(/* passing the reference to item 2 of arr*/)
</code>```

Is it possible?

答:
What about passing the reference to the arr property and the index?

```<code>fun whatever(arr: KMutableProperty0<IntArray>, index: Int)

whatever(::arr, i)
</code>```

Body:
Right now, somewhere in my code, I am passing a reference to a primitive, for example an Int

val i = 0

to

fun whatever(i: KMutableProperty0<Int>)

as

whatever(::i)

to being able to get/set its value from within the function

Everything worked great so far.

I'd like now to do the same for an i-th element of a primitive array, such as an IntArray

val arr = intArrayOf(1, 2, 3)

whatever(/* passing the reference to item 2 of arr*/)

Is it possible?

Body:
What about passing the reference to the arr property and the index?

fun whatever(arr: KMutableProperty0<IntArray>, index: Int)

whatever(::arr, i)


答:
this line db.Employees.Where(Employee => Employee.Name == "John") isn't currently functionally doing anything. It is querying the db for employees with name John and then not doing anything with that data. I think you want

```<code>List<Employee> empList = db.Employees.Where(Employee => Employee.Name == "John").ToList();

return Json(new { data = empList }, JsonRequestBehavior.AllowGet);
</code>```

you need to assign the filtered data to a variable so you have a reference to it and then return that data as part of your json

Title: How to get data-tables in asp.net to show only certain data

Body:
this line db.Employees.Where(Employee => Employee.Name == "John") isn't currently functionally doing anything. It is querying the db for employees with name John and then not doing anything with that data. I think you want

List<Employee> empList = db.Employees.Where(Employee => Employee.Name == "John").ToList();

return Json(new { data = empList }, JsonRequestBehavior.AllowGet);

you need to assign the filtered data to a variable so you have a reference to it and then return that data as part of your json


问:
Serialization with CodeDomSerializer - How to Initialize Manager Object?
There are numerous examples on the web that show how to use the CodeDomSerializer. Most of them show how to override the Serialize and Deserialize methods of that class. The problem is that this Serialize method takes a manager argument of type IDesignerSerializationManager. I cannot figure out how to create an instance of that type...

Here's what I tried:

```<code>var root = new Form();
root.Controls.Add(new TextBox()
{
   Text = "hello"
});

Type rootSerializerType = Type.GetType("System.ComponentModel.Design.Serialization.RootCodeDomSerializer, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", true);

var rootSerializer = Activator.CreateInstance(
   rootSerializerType,
   BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance,
   null,
   null,
   null) as CodeDomSerializer;

IDesignerSerializationManager manager = new DesignerSerializationManager();
var serializationResult = (CodeTypeDeclaration)rootSerializer.Serialize(manager, root);
</code>```

Because my manager object is not properly initialized, when I call the Serialize method as shown above, this exception is thrown:

[System.InvalidOperationException] "This method cannot be invoked
  because the serialization manager does not have an active
  serialization session."

I have googled and checked StackOverflow and I can't find any help on how to properly initialize the manager object ahead of my .Serialize invokation.

Any ideas?

答:
You need to create the section. Change last two lines to:

```<code>DesignerSerializationManager manager = new DesignerSerializationManager();
using (var session = manager.CreateSession())
{
    var serializationResult = (CodeTypeDeclaration)rootSerializer.Serialize(manager, root);
    // handle the result here
}
</code>```

Use either the concrete class DesignerSerializationManager or var, because the IDesignerSerializationManager interface does not have the CreateSession method.

Body:
There are numerous examples on the web that show how to use the CodeDomSerializer. Most of them show how to override the Serialize and Deserialize methods of that class. The problem is that this Serialize method takes a manager argument of type IDesignerSerializationManager. I cannot figure out how to create an instance of that type...

Here's what I tried:

var root = new Form();
root.Controls.Add(new TextBox()
{
   Text = "hello"
});

Type rootSerializerType = Type.GetType("System.ComponentModel.Design.Serialization.RootCodeDomSerializer, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", true);

var rootSerializer = Activator.CreateInstance(
   rootSerializerType,
   BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance,
   null,
   null,
   null) as CodeDomSerializer;

IDesignerSerializationManager manager = new DesignerSerializationManager();
var serializationResult = (CodeTypeDeclaration)rootSerializer.Serialize(manager, root);

Because my manager object is not properly initialized, when I call the Serialize method as shown above, this exception is thrown:

[System.InvalidOperationException] "This method cannot be invoked
  because the serialization manager does not have an active
  serialization session."

I have googled and checked StackOverflow and I can't find any help on how to properly initialize the manager object ahead of my .Serialize invokation.

Any ideas?

Body:
You need to create the section. Change last two lines to:

DesignerSerializationManager manager = new DesignerSerializationManager();
using (var session = manager.CreateSession())
{
    var serializationResult = (CodeTypeDeclaration)rootSerializer.Serialize(manager, root);
    // handle the result here
}

Use either the concrete class DesignerSerializationManager or var, because the IDesignerSerializationManager interface does not have the CreateSession method.


问:
C# Winforms: User Control to blink labels in Legacy project NET 1.1
I am trying to make a User Control to blink a label.

I have found this example:

```<code>using System.Diagnostics;
using System.Threading.Tasks;

private async void SoftBlink(Control ctrl, Color c1, Color c2, short CycleTime_ms, bool BkClr)
        {
            var sw = new Stopwatch(); sw.Start();
            short halfCycle = (short)Math.Round(CycleTime_ms * 0.5);
            while (true)
            {
                await Task.Delay(1);
                var n = sw.ElapsedMilliseconds % CycleTime_ms;  // ERROR #1
                var per = (double)Math.Abs(n - halfCycle) / halfCycle;
                var red = (short)Math.Round((c2.R - c1.R) * per) + c1.R; // ERROR #2
                var grn = (short)Math.Round((c2.G - c1.G) * per) + c1.G; // ERROR #3
                var blw = (short)Math.Round((c2.B - c1.B) * per) + c1.B; // ERROR #4
                var clr = Color.FromArgb(red, grn, blw);
                if (BkClr) ctrl.BackColor = clr; else ctrl.ForeColor = clr;
            }
        }
</code>```

Since I want to implement it in a legacy project NET 1.1 I need to convert above piece of code to make it work so I have implemented below user control:

```<code>public class UCSoftBlink : System.Windows.Forms.Label
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.Container components = null;
    private bool exit = false;
    private DateTime startTime = new DateTime();
    private TimeSpan elapsedTime = new TimeSpan();
    private Timer timer = new Timer();
    private delegate void blinkingDelegate(Label lbl, Color clr1, Color clr2, short CycleTime_ms, bool bkClr);
    public static UCSoftBlink _ucSoftBlink;

    private UCSoftBlink()
    {
        // This call is required by the Windows.Forms Form Designer.
        InitializeComponent();

        timer.Tick += new EventHandler( timer_Tick );
        timer.Interval = (1000) * (1);
        timer.Enabled = true;
    }

    public static void StartBlinking(Label lbl, Color clr1, Color clr2, short CycleTime_ms, bool bkClr)
    {
        _ucSoftBlink = new UCSoftBlink();

        blinkingDelegate bd = new blinkingDelegate(_ucSoftBlink.Blink);
        bd.BeginInvoke(lbl, clr1, clr2, CycleTime_ms, bkClr, null, null);
    }

    public static void StopBlinking()
    {
        _ucSoftBlink.timer.Stop();
        _ucSoftBlink.exit = true;
    }

    private void Blink(Label lbl, Color clr1, Color clr2, short CycleTime_ms, bool bkClr)
    {
        _ucSoftBlink.timer.Start();
        _ucSoftBlink.startTime = DateTime.Now;

        short halfCycle = (short)Math.Round(CycleTime_ms * 0.5);
        while (!exit)
        {
            System.Threading.Thread.Sleep(1000);
            short n = _ucSoftBlink.elapsedTime.TotalMilliseconds % CycleTime_ms; // ERROR #1
            double per = (double)Math.Abs(n - halfCycle) / halfCycle;
            short red = (short)Math.Round((clr2.R - clr1.R) * per) + clr1.R; ERROR #2
            short grn = (short)Math.Round((clr2.G - clr1.G) * per) + clr1.G; ERROR #3
            short blw = (short)Math.Round((clr2.B - clr1.B) * per) + clr1.B; ERROR #4
            Color clr = Color.FromArgb(red, grn, blw);

            if (bkClr)
            {
                lbl.BackColor = clr;
            }
            else
            {
                lbl.ForeColor = clr;
            }
        }

        Dispose(true);
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        _ucSoftBlink.elapsedTime = DateTime.Now - _ucSoftBlink.startTime;
    }

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
        if( disposing )
        {
            if(components != null)
            {
                _ucSoftBlink.timer.Stop();
                _ucSoftBlink.timer.Tick -= timer_Tick; // // ERROR #5 I know this is possible in other version of NET (>=2.0).
                components.Dispose();
            }
        }
        base.Dispose( disposing );
    }

    #region Component Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        components = new System.ComponentModel.Container();
    }
    #endregion
}
</code>```

but I get some compilation errors:

```<code>ERROR #1 error CS0197: Cannot pass 'My.Controls.UCSoftBlink.elapsedTime' as ref or out, because 'My.Controls.UCSoftBlink.elapsedTime' is a marshal-by-reference class
ERROR #1 error CS0029: Cannot implicitly convert type 'double' to 'short'
ERROR #2 error CS0029: Cannot implicitly convert type 'int' to 'short'
ERROR #3 error CS0029: Cannot implicitly convert type 'int' to 'short'
ERROR #4 error CS0029: Cannot implicitly convert type 'int' to 'short'
ERROR #5 error CS0654: Method 'sdpiu.Controles.UCSoftBlink.timer_Tick(object, System.EventArgs)' referenced without parentheses
</code>```

I want StartBlinking, StopBlinking to be static so I can access without the need of instantiate the user control.

答:
You can create a class with static methods and properties to handle this task on another thread and use a delegate in order to access safely to GUI controls,
here is a basic approach, you can improve it for your specific needs.

calling the class from your user control:

```<code>public void StartBlink()
{
    BlinkMe.BlinkedLabel = this.label1;
    // start blinking
    System.Threading.Thread t1 = new System.Threading.Thread(BlinkMe.Blink);
    t1.Start();
}
private void btnStopBlinking_Click(object sender, EventArgs e)
{
    // stop blinking
    BlinkMe.IsBlinking = false;
}
</code>```

the class that will handle the blink:

```<code>class BlinkMe
{
    public static Label BlinkedLabel;
    public static int milisec = 500;
    public delegate void BlinkDel();
    public static bool IsBlinking { get; set; } = true;

    public static void Blink()
    {

        while (IsBlinking)
        {
            System.Threading.Thread.Sleep(milisec);
            BlinkedLabel.Invoke(new BlinkDel(DoBLink));
        }
    }

    public static void DoBLink()
    {
        if (BlinkedLabel.BackColor != Color.Yellow)
        {
            BlinkedLabel.BackColor = Color.Yellow;
        }
        else
        {
            BlinkedLabel.BackColor = Color.Green;
        }
    }
}
</code>```

Body:
I am trying to make a User Control to blink a label.

I have found this example:

using System.Diagnostics;
using System.Threading.Tasks;

private async void SoftBlink(Control ctrl, Color c1, Color c2, short CycleTime_ms, bool BkClr)
        {
            var sw = new Stopwatch(); sw.Start();
            short halfCycle = (short)Math.Round(CycleTime_ms * 0.5);
            while (true)
            {
                await Task.Delay(1);
                var n = sw.ElapsedMilliseconds % CycleTime_ms;  // ERROR #1
                var per = (double)Math.Abs(n - halfCycle) / halfCycle;
                var red = (short)Math.Round((c2.R - c1.R) * per) + c1.R; // ERROR #2
                var grn = (short)Math.Round((c2.G - c1.G) * per) + c1.G; // ERROR #3
                var blw = (short)Math.Round((c2.B - c1.B) * per) + c1.B; // ERROR #4
                var clr = Color.FromArgb(red, grn, blw);
                if (BkClr) ctrl.BackColor = clr; else ctrl.ForeColor = clr;
            }
        }

Since I want to implement it in a legacy project NET 1.1 I need to convert above piece of code to make it work so I have implemented below user control:

public class UCSoftBlink : System.Windows.Forms.Label
{
    ///
    /// Required designer variable.
    ///
    private System.ComponentModel.Container components = null;
    private bool exit = false;
    private DateTime startTime = new DateTime();
    private TimeSpan elapsedTime = new TimeSpan();
    private Timer timer = new Timer();
    private delegate void blinkingDelegate(Label lbl, Color clr1, Color clr2, short CycleTime_ms, bool bkClr);
    public static UCSoftBlink _ucSoftBlink;

    private UCSoftBlink()
    {
        // This call is required by the Windows.Forms Form Designer.
        InitializeComponent();

        timer.Tick += new EventHandler( timer_Tick );
        timer.Interval = (1000) * (1);
        timer.Enabled = true;
    }

    public static void StartBlinking(Label lbl, Color clr1, Color clr2, short CycleTime_ms, bool bkClr)
    {
        _ucSoftBlink = new UCSoftBlink();

        blinkingDelegate bd = new blinkingDelegate(_ucSoftBlink.Blink);
        bd.BeginInvoke(lbl, clr1, clr2, CycleTime_ms, bkClr, null, null);
    }

    public static void StopBlinking()
    {
        _ucSoftBlink.timer.Stop();
        _ucSoftBlink.exit = true;
    }

    private void Blink(Label lbl, Color clr1, Color clr2, short CycleTime_ms, bool bkClr)
    {
        _ucSoftBlink.timer.Start();
        _ucSoftBlink.startTime = DateTime.Now;

        short halfCycle = (short)Math.Round(CycleTime_ms * 0.5);
        while (!exit)
        {
            System.Threading.Thread.Sleep(1000);
            short n = _ucSoftBlink.elapsedTime.TotalMilliseconds % CycleTime_ms; // ERROR #1
            double per = (double)Math.Abs(n - halfCycle) / halfCycle;
            short red = (short)Math.Round((clr2.R - clr1.R) * per) + clr1.R; ERROR #2
            short grn = (short)Math.Round((clr2.G - clr1.G) * per) + clr1.G; ERROR #3
            short blw = (short)Math.Round((clr2.B - clr1.B) * per) + clr1.B; ERROR #4
            Color clr = Color.FromArgb(red, grn, blw);

            if (bkClr)
            {
                lbl.BackColor = clr;
            }
            else
            {
                lbl.ForeColor = clr;
            }
        }

        Dispose(true);
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        _ucSoftBlink.elapsedTime = DateTime.Now - _ucSoftBlink.startTime;
    }

    ///
    /// Clean up any resources being used.
    ///
    protected override void Dispose( bool disposing )
    {
        if( disposing )
        {
            if(components != null)
            {
                _ucSoftBlink.timer.Stop();
                _ucSoftBlink.timer.Tick -= timer_Tick; // // ERROR #5 I know this is possible in other version of NET (>=2.0).
                components.Dispose();
            }
        }
        base.Dispose( disposing );
    }

    #region Component Designer generated code
    ///
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    ///
    private void InitializeComponent()
    {
        components = new System.ComponentModel.Container();
    }
    #endregion
}

but I get some compilation errors:

ERROR #1 error CS0197: Cannot pass 'My.Controls.UCSoftBlink.elapsedTime' as ref or out, because 'My.Controls.UCSoftBlink.elapsedTime' is a marshal-by-reference class
ERROR #1 error CS0029: Cannot implicitly convert type 'double' to 'short'
ERROR #2 error CS0029: Cannot implicitly convert type 'int' to 'short'
ERROR #3 error CS0029: Cannot implicitly convert type 'int' to 'short'
ERROR #4 error CS0029: Cannot implicitly convert type 'int' to 'short'
ERROR #5 error CS0654: Method 'sdpiu.Controles.UCSoftBlink.timer_Tick(object, System.EventArgs)' referenced without parentheses

I want StartBlinking, StopBlinking to be static so I can access without the need of instantiate the user control.

Body:
You can create a class with static methods and properties to handle this task on another thread and use a delegate in order to access safely to GUI controls,
here is a basic approach, you can improve it for your specific needs.

calling the class from your user control:

public void StartBlink()
{
    BlinkMe.BlinkedLabel = this.label1;
    // start blinking
    System.Threading.Thread t1 = new System.Threading.Thread(BlinkMe.Blink);
    t1.Start();
}
private void btnStopBlinking_Click(object sender, EventArgs e)
{
    // stop blinking
    BlinkMe.IsBlinking = false;
}

the class that will handle the blink:

class BlinkMe
{
    public static Label BlinkedLabel;
    public static int milisec = 500;
    public delegate void BlinkDel();
    public static bool IsBlinking { get; set; } = true;

    public static void Blink()
    {

        while (IsBlinking)
        {
            System.Threading.Thread.Sleep(milisec);
            BlinkedLabel.Invoke(new BlinkDel(DoBLink));
        }
    }

    public static void DoBLink()
    {
        if (BlinkedLabel.BackColor != Color.Yellow)
        {
            BlinkedLabel.BackColor = Color.Yellow;
        }
        else
        {
            BlinkedLabel.BackColor = Color.Green;
        }
    }
}


问:
unknown error: failed to write prefs file for loading multiple chrome profile
I have difficult time trying to load multiple chrome profile at the same time, and it always show "unknown error: failed to write prefs file"
  .I'm using selenium 2.48.2 and Selenium.WebDriver.ChromeDriver 2.20.0.0

```<code>    string localAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
      String chromeLocalAppDataPath = localAppDataPath + @"\Google\Chrome\User Data\Default\";

          var options = new ChromeOptions();
                        options.AddArgument("--no-experiments");
                        options.AddArguments("user-data-dir=" + chromeLocalAppDataPath);
                        options.AddArgument("--disable-translate");
                        options.AddArguments("--start-maximized");
                        //options.AddArgument("--disable-plugins");
                        //options.AddArgument("--disable-extensions");
                        options.AddArgument("--no-default-browser-check");
                        options.AddArgument("--clear-token-service");
                        options.AddArgument("--disable-default-apps");
                        options.AddArgument("--no-displaying-insecure-content");
                        //options.AddArgument("--disable-block-external-urls");
                        options.AddArgument("--disable-bundled-ppapi-flash");
            using (abcDataContext db = new abcDataContext())
                        {
                                Parallel.ForEach(fixtures, (current) =>
                                {
                                    using (IWebDriver driver = new ChromeDriver(options))   // fail right here
                                    {
                                        driver.Navigate().GoToUrl("http://google.com");
                                    }
                                });
                                counter++;
                            }
                            while (counter <= fixtures.Count() / 3);
}
</code>```

UPDATE: using firefoxdriver, it works fine with default profile

```<code>FirefoxProfileManager profileManager = new FirefoxProfileManager();
                FirefoxProfile profile = profileManager.GetProfile("default");

Parallel.ForEach(collections, (current) =>
                    {

                        IWebDriver driver = new FirefoxDriver(profile);
                        driver.Navigate().GoToUrl("http://google.com");

                    });
</code>```

答:
It's caused by parallel execution of ChromeDriver. Other errors as "failed to write first run file" or "cannot create default profile directory" may happen.

My solution was to specify option user-data-dir. Two concurrent Chromedriver should not use same user data directory.

```<code>chromeOptions.AddArgument("--user-data-dir=C:\\tmp\\chromeprofiles\\profile" + someKindOfIdOrIndex);
</code>```

You can of course change the path for whatever you want :)

Body:
I have difficult time trying to load multiple chrome profile at the same time, and it always show "unknown error: failed to write prefs file"
  .I'm using selenium 2.48.2 and Selenium.WebDriver.ChromeDriver 2.20.0.0

    string localAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
      String chromeLocalAppDataPath = localAppDataPath + @"\Google\Chrome\User Data\Default\";

          var options = new ChromeOptions();
                        options.AddArgument("--no-experiments");
                        options.AddArguments("user-data-dir=" + chromeLocalAppDataPath);
                        options.AddArgument("--disable-translate");
                        options.AddArguments("--start-maximized");
                        //options.AddArgument("--disable-plugins");
                        //options.AddArgument("--disable-extensions");
                        options.AddArgument("--no-default-browser-check");
                        options.AddArgument("--clear-token-service");
                        options.AddArgument("--disable-default-apps");
                        options.AddArgument("--no-displaying-insecure-content");
                        //options.AddArgument("--disable-block-external-urls");
                        options.AddArgument("--disable-bundled-ppapi-flash");
            using (abcDataContext db = new abcDataContext())
                        {
                                Parallel.ForEach(fixtures, (current) =>
                                {
                                    using (IWebDriver driver = new ChromeDriver(options))   // fail right here
                                    {
                                        driver.Navigate().GoToUrl("http://google.com");
                                    }
                                });
                                counter++;
                            }
                            while (counter <= fixtures.Count() / 3);
}

UPDATE: using firefoxdriver, it works fine with default profile

FirefoxProfileManager profileManager = new FirefoxProfileManager();
                FirefoxProfile profile = profileManager.GetProfile("default");

Parallel.ForEach(collections, (current) =>
                    {

                        IWebDriver driver = new FirefoxDriver(profile);
                        driver.Navigate().GoToUrl("http://google.com");

                    });

Body:
It's caused by parallel execution of ChromeDriver. Other errors as "failed to write first run file" or "cannot create default profile directory" may happen.

My solution was to specify option user-data-dir. Two concurrent Chromedriver should not use same user data directory.

chromeOptions.AddArgument("--user-data-dir=C:\\tmp\\chromeprofiles\\profile" + someKindOfIdOrIndex);

You can of course change the path for whatever you want :)


问:
How to properly display a new view and how to go back to the previous view
I'm very new to iPhone development and Objective-C. Today, I figured out how to open a new ViewController and how to return to the previous one.

Here's how I currently do this:

// In the main view controller I have a method called openSecondView that is defined like this:

```<code>- (void) openSecondView:(id)sender {
    SecondViewController *secondView = [[SecondViewController alloc] initWithNibName:nil bundle:nil];
    [self presentModalViewController:secondView animated:YES];
}
</code>```

// In the SecondViewController I have a back button that calls a method called closeView that is defined like this:

```<code>- (void)closeView:(id)sender {
    [self dismissModalViewControllerAnimated:YES];
}
</code>```

My question is, how do you do properly accomplish this?

Should I call [secondView release] after calling presentModalViewController or is this done some what behind the scenes? I ask this because when I was debugging I noticed that presentModalViewController doesn't seem to be a blocking code, the next few lines of code I added seem to execute immediately, without calling dismissModalViewControllerAnimated. Are there any consequences of calling [secondView release] after presentModalViewController?

Any help/advise would be much appreciated.

答: Just call [secondView release] after calling presentModalViewController. The view controller will be retained until it is dismissed.

Body:
I'm very new to iPhone development and Objective-C. Today, I figured out how to open a new ViewController and how to return to the previous one.

Here's how I currently do this:

// In the main view controller I have a method called openSecondView that is defined like this:

- (void) openSecondView:(id)sender {
    SecondViewController *secondView = [[SecondViewController alloc] initWithNibName:nil bundle:nil];
    [self presentModalViewController:secondView animated:YES];
}

// In the SecondViewController I have a back button that calls a method called closeView that is defined like this:

- (void)closeView:(id)sender {
    [self dismissModalViewControllerAnimated:YES];
}

My question is, how do you do properly accomplish this?

Should I call [secondView release] after calling presentModalViewController or is this done some what behind the scenes? I ask this because when I was debugging I noticed that presentModalViewController doesn't seem to be a blocking code, the next few lines of code I added seem to execute immediately, without calling dismissModalViewControllerAnimated. Are there any consequences of calling [secondView release] after presentModalViewController?

Any help/advise would be much appreciated.


问:
Where should I store a client_secret key in Django?
I have built an Android app with a Django REST backend, using django-rest-social-auth (Oauth2). Everything works fine but I am wondering where/how should I store the client_secret (of the OAuth Django app created in /admin) key, used for the first call to convert my user_token (or username/password if logged by credentials) to an access_token that will be used in all the next calls.

Indeed, I have read that it cannot be stored within my Android app as it can be decompiled. Thus, I store it on my server and retrieve the right client_secret according to the incoming client_id. But I do not know if it is the classical way to handle it.

答: Storing secrets for Django on servers is often done with environment variables, though there are several libraries out there that aim to tidy up the process, I like Django environ for example though that does a bit more than simply hide secrets.</p>


问:
Regular expression substituion vim
I would like to replace every occurence of the word ANYTHING.json with test.ANYTHING.

How can I do this with a vim regular expression?

答:
try this:

```<code>:%s/\(\w\+\)\.json/test.\1/g
</code>```

% - substitute on the whole file

/ - pattern to substitute

\( - start capturing the matched pattern into the variable \1

\w - matches any word character

\+ - the previous pattern must be present one or more times

\) - end capturing \1

\. - litteral dot

.json - litteral

/ - replace by

test. - litteral

\1 - insert what was matched inside the brackets

/g - mutiple times on a line

Title: Regular expression substituion vim

Body:
try this:

:%s/\(\w\+\)\.json/test.\1/g

% - substitute on the whole file

/ - pattern to substitute

\( - start capturing the matched pattern into the variable \1

\w - matches any word character

\+ - the previous pattern must be present one or more times

\) - end capturing \1

\. - litteral dot

.json - litteral

/ - replace by

test. - litteral

\1 - insert what was matched inside the brackets

/g - mutiple times on a line


问:
Call a python function from jinja2
I am using jinja2, and I want to call a python function as a helper, using a similar syntax as if I were calling a macro. jinja2 seems intent on preventing me from making a function call, and insists I repeat myself by copying the function into a template as a macro.

Is there any straightforward way to do this?  And, is there any way to import a whole set of python functions and have them accessible from jinja2, without going through a whole lot of rigamarole (such as writing an extension)?

答:
I like @AJP's answer. I used it verbatim until I ended up with a lot of functions. Then I switched to a Python function decorator.

from jinja2 import Template

template = '''
Hi, my name is {{ custom_function1(first_name) }}
My name is {{ custom_function2(first_name) }}
My name is {{ custom_function3(first_name) }}
'''
jinga_html_template = Template(template)

def template_function(func):
    jinga_html_template.globals[func.__name__] = func
    return func

@template_function
def custom_function1(a):
    return a.replace('o', 'ay')

@template_function
def custom_function2(a):
    return a.replace('o', 'ill')

@template_function
def custom_function3(a):
    return 'Slim Shady'

fields = {'first_name': 'Jo'}
print(jinga_html_template.render(**fields))
```

Good thing functions have a __name__!

Title: Call a python function from jinja2

Body:
I like @AJP's answer. I used it verbatim until I ended up with a lot of functions. Then I switched to a Python function decorator.

from jinja2 import Template

template = '''
Hi, my name is {{ custom_function1(first_name) }}
My name is {{ custom_function2(first_name) }}
My name is {{ custom_function3(first_name) }}
'''
jinga_html_template = Template(template)

def template_function(func):
    jinga_html_template.globals[func.__name__] = func
    return func

@template_function
def custom_function1(a):
    return a.replace('o', 'ay')

@template_function
def custom_function2(a):
    return a.replace('o', 'ill')

@template_function
def custom_function3(a):
    return 'Slim Shady'

fields = {'first_name': 'Jo'}
print(jinga_html_template.render(**fields))

Good thing functions have a __name__!


问:
CosmosDB RU Calculator Errors
I'm developing a technical document for a client where we are using CosmosDB and on this document the client has asked me to input the estimated monthly cost of running CosmosDB.

Now, when I head over to https://azure.microsoft.com/en-gb/pricing/calculator/ the minimum option I see to define the minimum number of RUs is 4*100 RU/s which is 4000 RUs. I think this is excessive but I don't see an option to "downgrade" this value. Is this really the minimum RU/s allowed?

Also, on the CosmosDB capacity planner (https://www.documentdb.com/capacityplanner) every time I upload my sample document I get an error stating that "Something went wrong. Please check your sample documents and try again."

The sample document I'm trying to upload is this: https://pastebin.com/dUypV2bj

Why am I getting errors? The page doesn't say what's wrong and no JSON validators have found any errors.
Can anyone help me please?

答:
4*100 = 400 RUs, which is the minimum for a fixed (10gb) size collection.

With regards to the JSON, the calculator appears to be failing on the html tags in the exp.Description properties. Remove those tags and the calculator will accept it.

Title: CosmosDB RU Calculator Errors


问:
Microsoft reports nested object datasource gives #Error
I am attempting to get nested objects to work in Microsoft reports. I downloaded example code from http://www.gotreportviewer.com/objectdatasources/index.html, and it runs correctly.

I built the following little app based on a Windows Form and their code, and all that I ever get when I reference a nested object value is a "#Error" in the place where the data should appear.

In the report, I use the same nested object syntax that is recommended at the web site:

```<code>=Fields!Name.Value.FirstName
</code>```

It works for their application on my computer, but not for mine. I can't understand it! Has anyone encountered this, or know why this happens?

Furthermore - and I don't know if this is related - I can't add a single instance of ClientItem to the LocalReport.DataSources object. It has to be a list. However, when it renders, it only shows one row of (#Errored) data in the table on the report.

Any help would be appreciated!

```<code>namespace ReportTest
{

    public class ClientItem
    {
        public int Id { get; set; }
        public ClientName Name { get; set; }
    }

    public class ClientName
    {
        public ClientName(string first, string last)
        {
            FirstName = first;
            LastName = last;
        }

        string FirstName { get; set; }
        string LastName { get; set; }
    }

    public partial class Form1 : Form
    {
        private List<ClientItem> clients = new List<ClientItem>();

        public Form1()
        {
            InitializeComponent();
            PopulateLists();
            GenerateReport();
        }

        private void PopulateLists()
        {
            clients.Add(new ClientItem { Id = 1, Name = new ClientName("Adrian", "Adesco") } );
            clients.Add(new ClientItem { Id = 2, Name = new ClientName("Brian", "Briar") } );
            clients.Add(new ClientItem { Id = 3, Name = new ClientName("Clive", "Cussler") } );
        }

        private void GenerateReport()
        {
            this.Text = "Report Control Demo";
            this.ClientSize = new System.Drawing.Size(950, 600);

            ReportViewer reportViewer = new ReportViewer();

            reportViewer.ProcessingMode = ProcessingMode.Local;

            reportViewer.LocalReport.ReportPath = "TestReport.rdlc";

            reportViewer.LocalReport.DataSources.Add(new ReportDataSource("ReportTest_ClientItem", clients));

            reportViewer.Dock = DockStyle.Fill;
            this.Controls.Add(reportViewer);

            reportViewer.RefreshReport();
        }
    }
}
</code>```

答:
Okay, the solution for the problem with the test case (above) is to make the properties in ClientName public:

```<code>public class ClientName
{
    public ClientName(string first, string last)
    {
        FirstName = first;
        LastName = last;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}
</code>```

This solved the test case problem for me.

However, I was still having problems with my actual report. It was still giving an error. As it turned out, this was because the sub-object was actually defined in a different assembly.

In order for it to work, the following line had to be added to the AssemblyInfo.cs file of the project containing the sub-object:

```<code>[assembly: AllowPartiallyTrustedCallers]
</code>```

Now it works! It took quite a while to discover that - hope this helps someone...

OwnerDisplayName: Reiste

Body:
I am attempting to get nested objects to work in Microsoft reports. I downloaded example code from http://www.gotreportviewer.com/objectdatasources/index.html, and it runs correctly.

I built the following little app based on a Windows Form and their code, and all that I ever get when I reference a nested object value is a "#Error" in the place where the data should appear.

In the report, I use the same nested object syntax that is recommended at the web site:

=Fields!Name.Value.FirstName

It works for their application on my computer, but not for mine. I can't understand it! Has anyone encountered this, or know why this happens?

Furthermore - and I don't know if this is related - I can't add a single instance of ClientItem to the LocalReport.DataSources object. It has to be a list. However, when it renders, it only shows one row of (#Errored) data in the table on the report.

Any help would be appreciated!

namespace ReportTest
{

    public class ClientItem
    {
        public int Id { get; set; }
        public ClientName Name { get; set; }
    }

    public class ClientName
    {
        public ClientName(string first, string last)
        {
            FirstName = first;
            LastName = last;
        }

        string FirstName { get; set; }
        string LastName { get; set; }
    }

    public partial class Form1 : Form
    {
        private List<ClientItem> clients = new List<ClientItem>();

        public Form1()
        {
            InitializeComponent();
            PopulateLists();
            GenerateReport();
        }

        private void PopulateLists()
        {
            clients.Add(new ClientItem { Id = 1, Name = new ClientName("Adrian", "Adesco") } );
            clients.Add(new ClientItem { Id = 2, Name = new ClientName("Brian", "Briar") } );
            clients.Add(new ClientItem { Id = 3, Name = new ClientName("Clive", "Cussler") } );
        }

        private void GenerateReport()
        {
            this.Text = "Report Control Demo";
            this.ClientSize = new System.Drawing.Size(950, 600);

            ReportViewer reportViewer = new ReportViewer();

            reportViewer.ProcessingMode = ProcessingMode.Local;

            reportViewer.LocalReport.ReportPath = "TestReport.rdlc";

            reportViewer.LocalReport.DataSources.Add(new ReportDataSource("ReportTest_ClientItem", clients));

            reportViewer.Dock = DockStyle.Fill;
            this.Controls.Add(reportViewer);

            reportViewer.RefreshReport();
        }
    }
}

LastEditorDisplayName: Dustin Brooks

Body:
Okay, the solution for the problem with the test case (above) is to make the properties in ClientName public:

public class ClientName
{
    public ClientName(string first, string last)
    {
        FirstName = first;
        LastName = last;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

This solved the test case problem for me.

However, I was still having problems with my actual report. It was still giving an error. As it turned out, this was because the sub-object was actually defined in a different assembly.

In order for it to work, the following line had to be added to the AssemblyInfo.cs file of the project containing the sub-object:

[assembly: AllowPartiallyTrustedCallers]

Now it works! It took quite a while to discover that - hope this helps someone...


问:
C++ Set Iterator in Class
I have a class, which has a member named _Emails. It is of the type set<PEmail*>. When I'm in a member function, and run the following code, it works as expected:

```<code>for( set<PEmail*>::iterator it=this->_Emails->begin(); it!=this->_Emails->end(); ++it )
  {
    cout << "Email: " << (*it)->getEmail() << endl;
  }
</code>```

That is, it yields a list of email addresses. Now, I'd like to be able to add to this set as the class grows, and not lose my place of last iteration. I attempted to make another member of my class, named _EmailItr, of type set<PEmail*>::iterator. I initialize it in my constructor, right after my _Emails, like so:

```<code>this->_Emails = new set<PEmail*>;
this->_EmailItr = this->_Emails->begin();
</code>```

Then, attempting to do a similar for loop:

```<code>// send the max queue amount, or until there are no more emails
for( int i=0;  i<this->_QueueSize || i==_Emails->size(); ++i )
  {
    cout << "i: " << i << endl;
    cout << "QueueSize: " << this->_QueueSize << endl;
    cout << "Emails: " << this->_Emails->size() << endl;

    cout << (*_EmailItr)->getEmail() << endl;
  }
</code>```

I get the following output:

```<code>i: 0
QueueSize: 2
Emails: 2
Segmentation fault
</code>```

What gives? Am I trying to use iterators in an improper way?

答: The STL set is well-behaved when inserting new elements during an iteration.  In particular, if you're iterating over a set while adding new elements, you won't "lose track" of where you are; your iterator will remain valid and it will see any new elements that were added or removed.  I'm not fully sure what your use case is here, but I don't think you need all of the added machinery you've introduced here.  Just using a good old-fashioned iterator without any adornments should work just fine.

Title: C++ Set Iterator in Class

Body:
I have a class, which has a member named _Emails. It is of the type set<PEmail*>. When I'm in a member function, and run the following code, it works as expected:

for( set<PEmail*>::iterator it=this->_Emails->begin(); it!=this->_Emails->end(); ++it )
  {
    cout << "Email: " << (*it)->getEmail() << endl;
  }

That is, it yields a list of email addresses. Now, I'd like to be able to add to this set as the class grows, and not lose my place of last iteration. I attempted to make another member of my class, named _EmailItr, of type set<PEmail*>::iterator. I initialize it in my constructor, right after my _Emails, like so:

this->_Emails = new set<PEmail*>;
this->_EmailItr = this->_Emails->begin();

Then, attempting to do a similar for loop:

// send the max queue amount, or until there are no more emails
for( int i=0;  i<this->_QueueSize || i==_Emails->size(); ++i )
  {
    cout << "i: " << i << endl;
    cout << "QueueSize: " << this->_QueueSize << endl;
    cout << "Emails: " << this->_Emails->size() << endl;

    cout << (*_EmailItr)->getEmail() << endl;
  }

I get the following output:

i: 0
QueueSize: 2
Emails: 2
Segmentation fault

What gives? Am I trying to use iterators in an improper way?


问:
show date and time separately in Swift
Trying to show the time and date separately in Swift 3 and both fields are returning nil. I'm receiving the date as a string thats in the standard Date() format.

```<code>public func formatDateForAbandonTicket(_ dte: String) -> String {
    print(dte)
    let timeFormatter = DateFormatter()
    timeFormatter.dateFormat = "HH:mm"
    let t = timeFormatter.date(from: dte)
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "d/MM/YYYY"
    dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00")
    let d = dateFormatter.date(from: dte)
    print()
    print(t)
    print()
    print(d)
    return "\(d)" + "     " + "\(t)"
}
</code>```

I get a nil response from both d & t. The parameter does contain the right date "2017-11-14 16:36:29 +0000".

Thanks

答:
Your code doesn't work because you need to first convert dte to a Date and to do that, you need to specify a format that matches the complete date string. You only need one Date, not two.

And there is no reason to create two separate strings just to combine them back into one.

```<code>public func formatDateForAbandonTicket(_ dte: String) -> String {
    print(dte)
    let df = DateFormatter()
    df.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
    df.locale = Locale(identifier: "en_US_POSIX")
    if let date = df.date(from: dte) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "d/MM/yyyy     HH:mm"
        dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
        let dateStr = dateFormatter.string(from: date)
        return dateStr
    } else {
        return ""
    }
}
</code>```

Also note that you are converting the result to a time in UTC time instead of the user's locale time. That's fine if that is what you need, just make sure it makes sense to the user.

Title: show date and time separately in Swift

Body:
Trying to show the time and date separately in Swift 3 and both fields are returning nil. I'm receiving the date as a string thats in the standard Date() format.

public func formatDateForAbandonTicket(_ dte: String) -> String {
    print(dte)
    let timeFormatter = DateFormatter()
    timeFormatter.dateFormat = "HH:mm"
    let t = timeFormatter.date(from: dte)
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "d/MM/YYYY"
    dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00")
    let d = dateFormatter.date(from: dte)
    print()
    print(t)
    print()
    print(d)
    return "\(d)" + "     " + "\(t)"
}

I get a nil response from both d & t. The parameter does contain the right date "2017-11-14 16:36:29 +0000".

Thanks

Body:
Your code doesn't work because you need to first convert dte to a Date and to do that, you need to specify a format that matches the complete date string. You only need one Date, not two.

And there is no reason to create two separate strings just to combine them back into one.

public func formatDateForAbandonTicket(_ dte: String) -> String {
    print(dte)
    let df = DateFormatter()
    df.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
    df.locale = Locale(identifier: "en_US_POSIX")
    if let date = df.date(from: dte) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "d/MM/yyyy     HH:mm"
        dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
        let dateStr = dateFormatter.string(from: date)
        return dateStr
    } else {
        return ""
    }
}

Also note that you are converting the result to a time in UTC time instead of the user's locale time. That's fine if that is what you need, just make sure it makes sense to the user.


问:
How should I set up asynchronous error handling with promises in angular?
Currently, the flow in my application looks something like this

```<code>function searchAsync() {
    $scope.search.inProgress = true;

    return Service.search($scope.search.parameters).$promise
        .then(function (data) {
            $scope.search.data = data;
        }).catch(function (e) {
            displayError(e);
        }).finally(function () {
            $scope.search.inProgress = false;
        });
}

function initialize() {
    var promises = [];

    promises.push(setLookupsAsync($scope.categories, LookupResource.getCategories));
    promises.push(setLookupsAsync($scope.topics, LookupResource.getTopics));
    promises.push(setLookupsAsync($scope.races, LookupResource.getRaces));
    promises.push(setLookupsAsync($scope.genders, LookupResource.getGenders));

    $q.all(promises).then(function () {
        searchAsync()
    }).catch(function (e) {
        displayError(e);
    }).finally(function () {
        $scope.page.loaded = true;
    });
}
</code>```

I've found that if the promise inside the searchAsync function fails, the error handling is local to that promise and the outside caller has no way of knowing if it failed or not. If I needed to access the $scope.search.data after the searchAsync call in the $q.all 'then' piece, I would have no way of knowing if it had no items due to a handled catch or due to no matching items. Is there a cleaner way I can set up my error handling when working with promises?

答:
Is there a cleaner way I can set up my error handling when working with promises?

Yes: Don't handle it there.

Since searchAsync returns a promise, it shouldn't handle errors itself (other than optionally transforming them while keeping them as errors) unless it can meaningfully convert an error into a result (which it doesn't look like it can). Instead, it should let its caller handle errors. The catch block you currently have transforms an error (a rejected promise) into a success (a resolved promise) with the value undefined. (It's not just you, this is a common mistake.)

Either remove the catch:

```<code>function searchAsync() {
    $scope.search.inProgress = true;

    return Service.search($scope.search.parameters).$promise
        .then(function (data) {
            $scope.search.data = data;
        }).finally(function () {
            $scope.search.inProgress = false;
        });
}
</code>```

...or keep it to call displayError but rethrow the error:

```<code>function searchAsync() {
    $scope.search.inProgress = true;

    return Service.search($scope.search.parameters).$promise
        .then(function (data) {
            $scope.search.data = data;
        }).catch(function (e) {
            displayError(e);
            throw e; // <=========
        }).finally(function () {
            $scope.search.inProgress = false;
        });
}
</code>```

In general, a function should either handle errors or return the promise chain, but rarely both. Letting errors propagate through the chain to the top level leaves error handling to the top level, while optionally letting all levels know they occurred. (Again: You can transform an error, or "tap" it by doing something and then re-throwing; those are fine. Silently converting failure to success-with-undefined is not. :-) )

Body:
Currently, the flow in my application looks something like this

function searchAsync() {
    $scope.search.inProgress = true;

    return Service.search($scope.search.parameters).$promise
        .then(function (data) {
            $scope.search.data = data;
        }).catch(function (e) {
            displayError(e);
        }).finally(function () {
            $scope.search.inProgress = false;
        });
}

function initialize() {
    var promises = [];

    promises.push(setLookupsAsync($scope.categories, LookupResource.getCategories));
    promises.push(setLookupsAsync($scope.topics, LookupResource.getTopics));
    promises.push(setLookupsAsync($scope.races, LookupResource.getRaces));
    promises.push(setLookupsAsync($scope.genders, LookupResource.getGenders));

    $q.all(promises).then(function () {
        searchAsync()
    }).catch(function (e) {
        displayError(e);
    }).finally(function () {
        $scope.page.loaded = true;
    });
}

I've found that if the promise inside the searchAsync function fails, the error handling is local to that promise and the outside caller has no way of knowing if it failed or not. If I needed to access the $scope.search.data after the searchAsync call in the $q.all 'then' piece, I would have no way of knowing if it had no items due to a handled catch or due to no matching items. Is there a cleaner way I can set up my error handling when working with promises?

Body:
Is there a cleaner way I can set up my error handling when working with promises?

Yes: Don't handle it there.

Since searchAsync returns a promise, it shouldn't handle errors itself (other than optionally transforming them while keeping them as errors) unless it can meaningfully convert an error into a result (which it doesn't look like it can). Instead, it should let its caller handle errors. The catch block you currently have transforms an error (a rejected promise) into a success (a resolved promise) with the value undefined. (It's not just you, this is a common mistake.)

Either remove the catch:

function searchAsync() {
    $scope.search.inProgress = true;

    return Service.search($scope.search.parameters).$promise
        .then(function (data) {
            $scope.search.data = data;
        }).finally(function () {
            $scope.search.inProgress = false;
        });
}

...or keep it to call displayError but rethrow the error:

function searchAsync() {
    $scope.search.inProgress = true;

    return Service.search($scope.search.parameters).$promise
        .then(function (data) {
            $scope.search.data = data;
        }).catch(function (e) {
            displayError(e);
            throw e; // <=========
        }).finally(function () {
            $scope.search.inProgress = false;
        });
}

In general, a function should either handle errors or return the promise chain, but rarely both. Letting errors propagate through the chain to the top level leaves error handling to the top level, while optionally letting all levels know they occurred. (Again: You can transform an error, or "tap" it by doing something and then re-throwing; those are fine. Silently converting failure to success-with-undefined is not. :-) )


问:
Get id of an element with the same class
I have multiple div boxes with the class printPic which will have their own unique id. On hover in/out, toggle the display of printPicOverlay which is a child of printPic. The way I have it set up now, printPicOverlay for all ids are toggled on hover.

What would be the best way to show/hide printPicOverlay on hover for each individual id?

$(".printPic").hover(function () {
$(".printPicOverlay").toggle();
}, function () {
$(".printPicOverlay").toggle();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.printPic{
  height: 10em;
  width: 10em;
  display: inline-block;
  background: red;
  position: relative;
}

.printPicOverlay{
  height: 100%;
  width: 100%;
  background: rgba(0,0,0,0.4);
  display: none;
  position: absolute;
}</code>```

```

答:
```<code>$('#' + $(this).attr('id') + '> div').toggle(100);// with little animation
</code>```

Just a different approach; I rather use only CSS by @helb.

While you already over the element ; and with toggling you can achieve your target. with little animation if you wish.

$(function(){
   $(".printPic").hover(function () {
      $('#' + $(this).attr('id') + '> div').toggle(100);
   });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.printPic{
  height: 10em;
  width: 10em;
  display: inline-block;
  background: red;
  position: relative;
}

.printPicOverlay{
  height: 100%;
  width: 100%;
  background: rgba(0,0,0,0.4);
  display: none;
  position: absolute;
}</code>```

```

Body:
I have multiple div boxes with the class printPic which will have their own unique id. On hover in/out, toggle the display of printPicOverlay which is a child of printPic. The way I have it set up now, printPicOverlay for all ids are toggled on hover.

What would be the best way to show/hide printPicOverlay on hover for each individual id?

$(".printPic").hover(function () {
$(".printPicOverlay").toggle();
}, function () {
$(".printPicOverlay").toggle();
});

.printPic{
  height: 10em;
  width: 10em;
  display: inline-block;
  background: red;
  position: relative;
}

.printPicOverlay{
  height: 100%;
  width: 100%;
  background: rgba(0,0,0,0.4);
  display: none;
  position: absolute;
}

Body:
$('#' + $(this).attr('id') + '> div').toggle(100);// with little animation

Just a different approach; I rather use only CSS by @helb.

While you already over the element ; and with toggling you can achieve your target. with little animation if you wish.

$(function(){
   $(".printPic").hover(function () {
      $('#' + $(this).attr('id') + '> div').toggle(100);
   });
});

.printPic{
  height: 10em;
  width: 10em;
  display: inline-block;
  background: red;
  position: relative;
}

.printPicOverlay{
  height: 100%;
  width: 100%;
  background: rgba(0,0,0,0.4);
  display: none;
  position: absolute;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "printPic" id = "1">
  <div class = "printPicOverlay"></div>
</div>

<div class = "printPic" id = "2">
  <div class = "printPicOverlay"></div>
</div>

<div class = "printPic" id = "3">
  <div class = "printPicOverlay"></div>
</div>


问:
How do I read this text file and Insert into MySQL?
sample

```<code>user id  User Name
   U456      Mathew
   U457      Leon
   U458      Cris
   U459      Yancy
   U460      Jane
</code>```

and so on up to 500k.

I need to read this text file and insert to MySQL  in two columns say User ID and User Name. How do I do this in PHP?

答:
Delete the first line and use this command

```<code>LOAD DATA INFILE 'C:\\sample.txt'
INTO TABLE Users
FIELDS TERMINATED BY ' '
LINES TERMINATED BY '\r\n';
</code>```

For more information visit
http://tech-gupshup.blogspot.com/2010/04/loading-data-in-mysql-table-from-text.html

Body:
sample

user id  User Name
   U456      Mathew
   U457      Leon
   U458      Cris
   U459      Yancy
   U460      Jane

and so on up to 500k.

I need to read this text file and insert to MySQL  in two columns say User ID and User Name. How do I do this in PHP?

Body:
Delete the first line and use this command

LOAD DATA INFILE 'C:\\sample.txt'
INTO TABLE Users
FIELDS TERMINATED BY ' '
LINES TERMINATED BY '\r\n';

For more information visit
http://tech-gupshup.blogspot.com/2010/04/loading-data-in-mysql-table-from-text.html


问:
How can I find occurences in a list?
I´m working on an assigment in Python, and I have a question if you could answer.
I wanna write a function that returns a list with the locations of the first nucleotide of all occurrences of "ATG" in the sequence.
For example, we can say that our DNA sequence is AATGCATGC. We see that ATG can start in the index 1, and the other possibility is index 5.
I tried this one to solve this assignment;

```<code>dna = "AATGCATGC"
starting_offset = dna.index("ATG")
print(starting_offset)
</code>```

The result I´ve got is 1. But I wanna get result as [1, 5]

So how should I write this function for all occurrences?

Thanks for helping me :)

答:
Using regular expressions, you can use re.finditer to find all occurences:

You can try this function :

```<code>import re
text = 'AATGCATGC'
pattern='ATG'
def getIndexes (text,pattern):
    list=[index.start() for index in re.finditer('ATG', text)]
    return list
getIndexes(text,pattern)
>>[1, 5]
</code>```

It will gives you the list you're looking for . Hope that'll be helpful !

Title: How can I find occurences in a list?

Body:
I´m working on an assigment in Python, and I have a question if you could answer.
I wanna write a function that returns a list with the locations of the first nucleotide of all occurrences of "ATG" in the sequence.
For example, we can say that our DNA sequence is AATGCATGC. We see that ATG can start in the index 1, and the other possibility is index 5.
I tried this one to solve this assignment;

dna = "AATGCATGC"
starting_offset = dna.index("ATG")
print(starting_offset)

The result I´ve got is 1. But I wanna get result as [1, 5]

So how should I write this function for all occurrences?

Thanks for helping me :)

Body:
Using regular expressions, you can use re.finditer to find all occurences:

You can try this function :

import re
text = 'AATGCATGC'
pattern='ATG'
def getIndexes (text,pattern):
    list=[index.start() for index in re.finditer('ATG', text)]
    return list
getIndexes(text,pattern)
>>[1, 5]

It will gives you the list you're looking for . Hope that'll be helpful !


问:
Android Studio 3.1 Canary 3 - Gradle sync failed
For a unknown reason Android Studio 3.1 Canary 3 is bugged and stopped to work, I updated gradle to 3.1-alpha03 and it stopped working, no matter if I download the project again, already downloaded Android Studio again too.

I've already checkout old versions of the project, but this message still show:

```<code>Gradle sync failed: com.android.tools.idea.gradle.project.model.AndroidModuleModel.getSelectedVariant()Lcom/android/tools/idea/gradle/project/model/ide/android/IdeVariant; (8s 806ms)
</code>```

I've removed .idea folder, .gradle folder, did invalidate and restart

I don't know nothing more to do, cant run or use the IDE.

Edit:

Edit2:

New Projects doesnt work too

答:
solved:

first run -> find ~ -path ~/Library/Caches/Metadata/Safari -prune -o -iname \*android\*studio\* -print -prune

DELETE ALL FOLDERS related to android-studio

start fresh install and project setup

Body:
For a unknown reason Android Studio 3.1 Canary 3 is bugged and stopped to work, I updated gradle to 3.1-alpha03 and it stopped working, no matter if I download the project again, already downloaded Android Studio again too.

I've already checkout old versions of the project, but this message still show:

Gradle sync failed: com.android.tools.idea.gradle.project.model.AndroidModuleModel.getSelectedVariant()Lcom/android/tools/idea/gradle/project/model/ide/android/IdeVariant; (8s 806ms)

I've removed .idea folder, .gradle folder, did invalidate and restart

I don't know nothing more to do, cant run or use the IDE.

Edit:

Edit2:

New Projects doesnt work too


问:
Error 5 : Access Denied when starting windows service
I'm getting this error when I try to start a windows service I've created in C#:

My Code so far:

```<code>private ServiceHost host = null;

public RightAccessHost()
{
    InitializeComponent();
}

protected override void OnStart(string[] args)
{
    host = new ServiceHost(typeof(RightAccessWcf));
    host.Open();
}

protected override void OnStop()
{
    if (host != null)
        host.Close();
    host = null;
}
</code>```

Update #1

I solved the issue above by granting permissions to the account NETWORK SERVICE but now I have an another problem:

Update #2

Service cannot be started. System.InvalidOperationException: Service 'RightAccessManagementWcf.RightAccessWcf' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.
     at System.ServiceModel.Description.DispatcherBuilder.EnsureThereAreNonMexEndpoints(ServiceDescription description)
     at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
     at System.ServiceModel.ServiceHostBase.InitializeRuntime()
     at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
     at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
     at RightAccessHosting.RightAccessHost.OnStart(String[] args) in C:\Users....

答:
Right click on the service in service.msc and select property.

You will see a folder path under Path to executable like C:\Users\Me\Desktop\project\Tor\Tor\tor.exe

Navigate to C:\Users\Me\Desktop\project\Tor and right click on Tor.

Select property, security, edit and then add.
In the text field enter LOCAL SERVICE, click ok and then check the box FULL CONTROL

Click on add again then enter NETWORK SERVICE, click ok,  check the box FULL CONTROL

Then click ok (at the bottom)

Body:
I'm getting this error when I try to start a windows service I've created in C#:

My Code so far:

private ServiceHost host = null;

public RightAccessHost()
{
    InitializeComponent();
}

protected override void OnStart(string[] args)
{
    host = new ServiceHost(typeof(RightAccessWcf));
    host.Open();
}

protected override void OnStop()
{
    if (host != null)
        host.Close();
    host = null;
}

Update #1

I solved the issue above by granting permissions to the account NETWORK SERVICE but now I have an another problem:

Update #2

Service cannot be started. System.InvalidOperationException: Service 'RightAccessManagementWcf.RightAccessWcf' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.
     at System.ServiceModel.Description.DispatcherBuilder.EnsureThereAreNonMexEndpoints(ServiceDescription description)
     at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
     at System.ServiceModel.ServiceHostBase.InitializeRuntime()
     at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
     at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
     at RightAccessHosting.RightAccessHost.OnStart(String[] args) in C:\Users....


问:
Run and handle external application from python
I want to develop Python script that will open some windows-based application, then enter some data/commands simulating user using keyboard:

Run MS Calculator then: "5", "+", "8", "/", "2", "Enter" and that's it

Run MS Notepad then: "Hello world!", "Ctrl+s", "My file", "Enter", "Alt+F4"

Of course it could return exiting code like 1 when succeed and write some logs.

I believe there is some library (probably for UI testing purpouses) but I don't know any.

I know there is Selenium but I'm afraid it's only for web browser app.

答:
If you like Writing Scripts in Python Languages, you can use Autopythonlauncher Click Here with this Software you can make clickable Pictures with Python Scripting Codes. You can then simple write a python code to run a External Application and then You can Send any text or any Keyboard Shortcuts Macros (without focus the Windows - this means you can Send it to any Windows Applications) and it is everthing in 3d. Choose a Picture and write in the Command Editor this example code.

This Python Script Does also Work Without Autopythonlauncher. (see bottom)

```<code>#run calc
#######################
import subprocess

cmd = "C:/Windows/System32/calc.exe"
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, creationflags=0x08000000)
process.wait()
#######################

# you can send any text or Keyboard Shortcuts Combinations - pyautogui.hotkey('ctrl', 'c')
# send "5", "+", "8", "/", "2"
# send "Enter"
#######################
import pyautogui
import time

time.sleep(.500)
pyautogui.press(['5','+','8','/','2'])
pyautogui.hotkey('enter')
#######################
</code>```

Look to this intro youtube video Click Here you can see what AutoPythonlauncher Software can do.

Note:
If you want to test it out without AutopythonLauncher Software.

You will need to make this bat file,
Run this to install the packages pyautogui.
The only Contra is you can not use it (without focus the Windows)

install.bat

```<code>C:\Python27\scripts\pip.exe install pyautogui
pause
</code>```

Body:
If you like Writing Scripts in Python Languages, you can use Autopythonlauncher Click Here with this Software you can make clickable Pictures with Python Scripting Codes. You can then simple write a python code to run a External Application and then You can Send any text or any Keyboard Shortcuts Macros (without focus the Windows - this means you can Send it to any Windows Applications) and it is everthing in 3d. Choose a Picture and write in the Command Editor this example code.

This Python Script Does also Work Without Autopythonlauncher. (see bottom)

#run calc
#######################
import subprocess

cmd = "C:/Windows/System32/calc.exe"
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, creationflags=0x08000000)
process.wait()
#######################

# you can send any text or Keyboard Shortcuts Combinations - pyautogui.hotkey('ctrl', 'c')
# send "5", "+", "8", "/", "2"
# send "Enter"
#######################
import pyautogui
import time

time.sleep(.500)
pyautogui.press(['5','+','8','/','2'])
pyautogui.hotkey('enter')
#######################

Look to this intro youtube video Click Here you can see what AutoPythonlauncher Software can do.

Note:
If you want to test it out without AutopythonLauncher Software.

You will need to make this bat file,
Run this to install the packages pyautogui.
The only Contra is you can not use it (without focus the Windows)

install.bat

C:\Python27\scripts\pip.exe install pyautogui
pause