问:
Is there a way to declare members of an abstract base class that are the type of the derived class?
Suppose I have an abstract base class that I want to declare members in that will match the type of the classes that derive from this base class.

```<code>public abstract class BaseClass
{
    protected BaseClass parent;
}

public class DerivedClass1 : BaseClass
{
    // parent could be of type DerivedClass2
}

public class DerivedClass2 : BaseClass
{
    // parent could be of type DerivedClass1
}
</code>```

This won't work because the parent field in each derived class can be anything that derives from BaseClass. I want to ensure that the parent field in DerivedClass1 can only be of type DerivedClass1. So I'm thinking maybe I should use generics.

```<code>public abstract class BaseClass<T> where T : BaseClass<T>
{
    protected T parent;
}
</code>```

This may seem confusing and circular, but it does compile. It's basically saying parent is of type T which has to derive from the generic BaseClass. So now a derived class can look like this:

```<code>public class DerivedClass : BaseClass<DerivedClass>
{
    // parent is of type DerivedClass
}
</code>```

The problem is that I have to enforce the type-matching myself when I declare DerivedClass. There's nothing stopping someone from doing something like this:

```<code>public class DerivedClass1 : BaseClass<DerivedClass2>
{
    // parent is of type DerivedClass2
}
</code>```

Does C# have a way of doing this so that the type of a member declared in the base is sure to match the derived type?

I think this is similar to what this C++ question was trying to ask: Abstract base class for derived classes with functions that have a return type of the derived class

答:
If I understand your requirements correctly, you have a series of classes with an inheritance relationship, and you wish to arrange them in a tree structure where each instance has a parent of the same type and only of the same type. It's an interesting problem.

After noodling with this for a bit, may I suggest you separate the requirements into two parallel but related object graphs, so that you have

A set of classes with an inheritance relationship

A set of classes that can contain any of the classes from the first set, and have type-strict parents and children.

First, let's declare the first set of classes that inherit from each other. Ignore the Node bit for now.

```<code>public class BaseClass
{
    public Node ContainerNode { get; set; }
}

public class DerivedClass1 : BaseClass
{
}

public class DerivedClass2 : BaseClass
{
}
</code>```

These classes can't do much but it's just an example.

Now let's set up another set of classes that can participate in a tree. Each element in the tree is called a Node.

```<code>//Basic node
public class Node
{
}

//A node that can contain a T (which must be a BaseClass or derived from one)
public class Node<T> : Node where T : BaseClass
{
    public T Parent { get; set; }
    public T This { get; set; }

    public Node(T innerClass)
    {
        this.This = innerClass;
        innerClass.ContainerNode = this;
    }
}
</code>```

Now we have everything we need to enforce the type safety you seek. We can create classes in your inheritance hierarchy like this:

```<code>    var child1 = new Node<DerivedClass1>(new DerivedClass1());
    var parent1 = new Node<DerivedClass1>(new DerivedClass1());
    child1.Parent = parent1.This;
</code>```

Let's see what happens if we mistakenly mix up DerivedClass1 and DerivedClass2:

```<code>    var child2 = new Node<DerivedClass2>(new DerivedClass2());
    var parent2 = new Node<DerivedClass1>(new DerivedClass1()); //Oops
    child2.Parent = parent2.This;  //Does not compile
</code>```

So as you can see, the Parent property is now typesafe.

Now all that stuff ^^^^ looks kind of messy, so let's clean it up by adding a few helper methods.

```<code>public class Node
{
    public T GetParent<T>() where T : BaseClass
    {
        return ((Node<T>)this).Parent;
    }

    static public Node<T> Create<T>(T innerClass) where T : BaseClass
    {
        return new Node<T>(innerClass);
    }

    static public T GetParent<T>(T child) where T: BaseClass
    {
        return child.ContainerNode.GetParent<T>();
    }

    static public implicit operator T (Node<T> input)
    {
        return input.This;
    }
}
</code>```

Now, since the compiler can infer the <T> arguments, our declarations are much neater:

```<code>    var child1 = Node.Create(new DerivedClass1());
    var parent1 = Node.Create(new DerivedClass1());
    child1.Parent = parent1;
</code>```

And it's easy for any of the derived classes to find its own parent:

```<code>public class DerivedClass1 : BaseClass
{
    protected DerivedClass1 Parent
    {
        get
        {
            return Node.GetParent(this);  //This is type safe!
        }
    }
}
</code>```

One objection to all this is that you don't want coders to deal with this Node layer. Well, they don't, because we set up an implicit cast:

```<code>    Node<DerivedClass1> a = Node.Create(new DerivedClass1());
    DerivedClass1 b = a;  //Works!!! And is type-safe.
</code>```

Full working code on DotNetFiddle.

Body:
Suppose I have an abstract base class that I want to declare members in that will match the type of the classes that derive from this base class.

public abstract class BaseClass
{
    protected BaseClass parent;
}

public class DerivedClass1 : BaseClass
{
    // parent could be of type DerivedClass2
}

public class DerivedClass2 : BaseClass
{
    // parent could be of type DerivedClass1
}

This won't work because the parent field in each derived class can be anything that derives from BaseClass. I want to ensure that the parent field in DerivedClass1 can only be of type DerivedClass1. So I'm thinking maybe I should use generics.

public abstract class BaseClass<T> where T : BaseClass<T>
{
    protected T parent;
}

This may seem confusing and circular, but it does compile. It's basically saying parent is of type T which has to derive from the generic BaseClass. So now a derived class can look like this:

public class DerivedClass : BaseClass<DerivedClass>
{
    // parent is of type DerivedClass
}

The problem is that I have to enforce the type-matching myself when I declare DerivedClass. There's nothing stopping someone from doing something like this:

public class DerivedClass1 : BaseClass<DerivedClass2>
{
    // parent is of type DerivedClass2
}

Does C# have a way of doing this so that the type of a member declared in the base is sure to match the derived type?

I think this is similar to what this C++ question was trying to ask: Abstract base class for derived classes with functions that have a return type of the derived class

Body:
If I understand your requirements correctly, you have a series of classes with an inheritance relationship, and you wish to arrange them in a tree structure where each instance has a parent of the same type and only of the same type. It's an interesting problem.

After noodling with this for a bit, may I suggest you separate the requirements into two parallel but related object graphs, so that you have

A set of classes with an inheritance relationship

A set of classes that can contain any of the classes from the first set, and have type-strict parents and children.

First, let's declare the first set of classes that inherit from each other. Ignore the Node bit for now.

public class BaseClass
{
    public Node ContainerNode { get; set; }
}

public class DerivedClass1 : BaseClass
{
}

public class DerivedClass2 : BaseClass
{
}

These classes can't do much but it's just an example.

Now let's set up another set of classes that can participate in a tree. Each element in the tree is called a Node.

//Basic node
public class Node
{
}

//A node that can contain a T (which must be a BaseClass or derived from one)
public class Node<T> : Node where T : BaseClass
{
    public T Parent { get; set; }
    public T This { get; set; }

    public Node(T innerClass)
    {
        this.This = innerClass;
        innerClass.ContainerNode = this;
    }
}

Now we have everything we need to enforce the type safety you seek. We can create classes in your inheritance hierarchy like this:

    var child1 = new Node<DerivedClass1>(new DerivedClass1());
    var parent1 = new Node<DerivedClass1>(new DerivedClass1());
    child1.Parent = parent1.This;

Let's see what happens if we mistakenly mix up DerivedClass1 and DerivedClass2:

    var child2 = new Node<DerivedClass2>(new DerivedClass2());
    var parent2 = new Node<DerivedClass1>(new DerivedClass1()); //Oops
    child2.Parent = parent2.This;  //Does not compile

So as you can see, the Parent property is now typesafe.

Now all that stuff ^^^^ looks kind of messy, so let's clean it up by adding a few helper methods.

public class Node
{
    public T GetParent<T>() where T : BaseClass
    {
        return ((Node<T>)this).Parent;
    }

    static public Node<T> Create<T>(T innerClass) where T : BaseClass
    {
        return new Node<T>(innerClass);
    }

    static public T GetParent<T>(T child) where T: BaseClass
    {
        return child.ContainerNode.GetParent<T>();
    }

    static public implicit operator T (Node<T> input)
    {
        return input.This;
    }
}

Now, since the compiler can infer the <T> arguments, our declarations are much neater:

    var child1 = Node.Create(new DerivedClass1());
    var parent1 = Node.Create(new DerivedClass1());
    child1.Parent = parent1;

And it's easy for any of the derived classes to find its own parent:

public class DerivedClass1 : BaseClass
{
    protected DerivedClass1 Parent
    {
        get
        {
            return Node.GetParent(this);  //This is type safe!
        }
    }
}

One objection to all this is that you don't want coders to deal with this Node layer. Well, they don't, because we set up an implicit cast:

    Node<DerivedClass1> a = Node.Create(new DerivedClass1());
    DerivedClass1 b = a;  //Works!!! And is type-safe.

Full working code on DotNetFiddle.


来源: stackexchange

问:
ARSCNView created by code is slower than storyboard when opening
I try to use code to create the ARSCNView in the viewDidLoad like below:

```<code>_sceneView = [[ARSCNView alloc] initWithFrame:self.view.bounds];
_sceneView.automaticallyUpdatesLighting = YES;
[self.view addSubview:_sceneView];
ARWorldTrackingConfiguration *configuration = [ARWorldTrackingConfiguration new];
configuration.worldAlignment = ARWorldAlignmentGravityAndHeading;
configuration.lightEstimationEnabled = YES;
[_sceneView.session runWithConfiguration:configuration];
</code>```

And then I open it by using code:

```<code>MyARViewController *vc = [[MyARViewController alloc] init];
[self.navigationController pushViewController:vc animated:YES];
</code>```

I can obviously feel that at the beginning it's stuck a little bit moment and then work as usual while it's smooth to open the view if I use storyboard to create the ARSCNView.

What might be to cause this issue?

答:
I think the problem is the way you added ARSCNView.

When you use StoryBoard to add ARSCNView, the initWithCoder method of ARSCNView will be called instead of initWithFrame. I guess that you did something in initWithFrame and you don't do anything inside initWithCoder.

That's why you have a difference between adding ARSCNView programmatically and adding from StoryBoard

UPDATE

Another problem is the way you create MyARViewController when using StoryBoard. MyARViewController *vc = [[MyARViewController alloc] init]; isn't right way to create MyARViewController from StoryBoard. ARSCNView can't be added to MyARViewController. That's why you don't feed stuck.

ContentLicense: CC BY-SA 3.0

Body:
I try to use code to create the ARSCNView in the viewDidLoad like below:

_sceneView = [[ARSCNView alloc] initWithFrame:self.view.bounds];
_sceneView.automaticallyUpdatesLighting = YES;
[self.view addSubview:_sceneView];
ARWorldTrackingConfiguration *configuration = [ARWorldTrackingConfiguration new];
configuration.worldAlignment = ARWorldAlignmentGravityAndHeading;
configuration.lightEstimationEnabled = YES;
[_sceneView.session runWithConfiguration:configuration];

And then I open it by using code:

MyARViewController *vc = [[MyARViewController alloc] init];
[self.navigationController pushViewController:vc animated:YES];

I can obviously feel that at the beginning it's stuck a little bit moment and then work as usual while it's smooth to open the view if I use storyboard to create the ARSCNView.

What might be to cause this issue?


问:
What is the difference between iterator and iterable and how to use them?
I am new in Java and I'm really confused with iterator and iterable. Can anyone explain to me and give some examples?</p>

答:
As explained here, The “Iterable” was introduced to be able to use in the foreach loop. A class implementing the Iterable interface can be iterated over.

Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.


问:
Hibernate mapping resource locate in the separate jar
I have separate jar file has contain hibernate entity mapping and mapping directly. My Hibernate confg (cgf.xml) placed in another jar file. And as result I catch exception "resource: com/iceleads/data/Test.hbm.xml not found".

Example:

```<code>entities.jar
   com.package.entity.TestEntity.java
   com.package.entity.TestEnity.hbm.xml

mainUsage.jar
   com.package.main.MainClass.java - there are I get session factory
      SessionFactory factory = HibernateUtil.getSessionFactory();

   com.package.main.hibernate.cfg.xml

   in HibernateUtil
        sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();

  in hibernate.cfg.xml
       <mapping resource="com/package/entity/TestEntity/Test.hbm.xml"/>
</code>```

entities.jar in mainUsage.jar classpath

Please suggest me how I can configure hibernate.cfg.xml to use separate jar with entities.

Thanks a lot!

Artem

答:
Including the path of the mapping file into the mapping resource. For instance, use <mapping resource="com/example/test/test.hbm.xml"/>, and test.hbm.xml is located in the package com.example.test inside the jar file.

This will serve the purpose.

ContentLicense: CC BY-SA 2.5

Body:
I have separate jar file has contain hibernate entity mapping and mapping directly. My Hibernate confg (cgf.xml) placed in another jar file. And as result I catch exception "resource: com/iceleads/data/Test.hbm.xml not found".

Example:

entities.jar
   com.package.entity.TestEntity.java
   com.package.entity.TestEnity.hbm.xml

mainUsage.jar
   com.package.main.MainClass.java - there are I get session factory
      SessionFactory factory = HibernateUtil.getSessionFactory();

   com.package.main.hibernate.cfg.xml

   in HibernateUtil
        sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();

  in hibernate.cfg.xml
       <mapping resource="com/package/entity/TestEntity/Test.hbm.xml"/>

entities.jar in mainUsage.jar classpath

Please suggest me how I can configure hibernate.cfg.xml to use separate jar with entities.

Thanks a lot!

Artem


问:
Lucene.Net SynonymFilter with multiple word phrases
I am using Lucene.net and am trying to implement a SynonymFilter to provide expanded terms when items within my database of products can be named differently, or spelled differently - e.g. "spanner" > "wrench", or "lawnmower" > "lawn mower".

As a test I setup a SynonymMap as follows :

```<code>String base1 = "lawnmower";
String syn1 = "lawn mower";
String base2 = "spanner";
String syn2 = "wrench";

SynonymMap.Builder sb = new SynonymMap.Builder(true);
sb.Add(new CharsRef(base1), new CharsRef(syn1), true);
sb.Add(new CharsRef(base2), new CharsRef(syn2), true);
SynonymMap smap = sb.Build();
</code>```

Searching for "spanner" or "wrench" brings back all terms with either word in. Searching for "lawn mower" or "lawnmower" only brings back terms that match exactly the input search criteria.

Is there something else that needs to done for multiple word phrases within  the Synonyms?

Also how do I expand to say 3 or more terms for for example "lawnmower", "lawn mower", "mower", "grass cutter"?

Thanks

答:
There is an example of multi-word synonyms in the unit tests. You have to split the words yourself and insert a SynonymMap.WORD_SEPARATOR (null character) between them. To make this easier, there is a Join method on SynonymMap.Builder.

```<code>String base1 = "lawnmower";
String syn1 = "lawn mower";

SynonymMap.Builder sb = new SynonymMap.Builder(true);
CharsRef syn1Chars = sb.Join(Regex.Split(syn1, " +"), new CharsRef());
sb.Add(new CharsRef(base1), syn1Chars, true);
SynonymMap smap = sb.Build();
</code>```

Here is an extension method to make quick work of this.

```<code>public static class SynonymMapBuilderExtensions
{
    private static Regex Space = new Regex(" +", RegexOptions.Compiled);

    public static void AddPhrase(this SynonymMap.Builder builder, string input,
        string output, bool keepOrig)
    {
        CharsRef outputRef = builder.Join(Space.Split(output), new CharsRef());
        builder.Add(new CharsRef(input), outputRef, keepOrig);
    }
}
</code>```

You can then use this extension method whether the synonym has spaces or not, and you don't have to bother with creating the CharsRef objects if you don't need them anywhere else in your code.

```<code>String base1 = "lawnmower";
String syn1 = "lawn mower";
String base2 = "spanner";
String syn2 = "wrench";

SynonymMap.Builder sb = new SynonymMap.Builder(true);
sb.AddPhrase(base1, syn1, true);
sb.AddPhrase(base2, syn2, true);
SynonymMap smap = sb.Build();
</code>```

Body:
I am using Lucene.net and am trying to implement a SynonymFilter to provide expanded terms when items within my database of products can be named differently, or spelled differently - e.g. "spanner" > "wrench", or "lawnmower" > "lawn mower".

As a test I setup a SynonymMap as follows :

String base1 = "lawnmower";
String syn1 = "lawn mower";
String base2 = "spanner";
String syn2 = "wrench";

SynonymMap.Builder sb = new SynonymMap.Builder(true);
sb.Add(new CharsRef(base1), new CharsRef(syn1), true);
sb.Add(new CharsRef(base2), new CharsRef(syn2), true);
SynonymMap smap = sb.Build();

Searching for "spanner" or "wrench" brings back all terms with either word in. Searching for "lawn mower" or "lawnmower" only brings back terms that match exactly the input search criteria.

Is there something else that needs to done for multiple word phrases within  the Synonyms?

Also how do I expand to say 3 or more terms for for example "lawnmower", "lawn mower", "mower", "grass cutter"?

Thanks

Body:
There is an example of multi-word synonyms in the unit tests. You have to split the words yourself and insert a SynonymMap.WORD_SEPARATOR (null character) between them. To make this easier, there is a Join method on SynonymMap.Builder.

String base1 = "lawnmower";
String syn1 = "lawn mower";

SynonymMap.Builder sb = new SynonymMap.Builder(true);
CharsRef syn1Chars = sb.Join(Regex.Split(syn1, " +"), new CharsRef());
sb.Add(new CharsRef(base1), syn1Chars, true);
SynonymMap smap = sb.Build();

Here is an extension method to make quick work of this.

public static class SynonymMapBuilderExtensions
{
    private static Regex Space = new Regex(" +", RegexOptions.Compiled);

    public static void AddPhrase(this SynonymMap.Builder builder, string input,
        string output, bool keepOrig)
    {
        CharsRef outputRef = builder.Join(Space.Split(output), new CharsRef());
        builder.Add(new CharsRef(input), outputRef, keepOrig);
    }
}

You can then use this extension method whether the synonym has spaces or not, and you don't have to bother with creating the CharsRef objects if you don't need them anywhere else in your code.

String base1 = "lawnmower";
String syn1 = "lawn mower";
String base2 = "spanner";
String syn2 = "wrench";

SynonymMap.Builder sb = new SynonymMap.Builder(true);
sb.AddPhrase(base1, syn1, true);
sb.AddPhrase(base2, syn2, true);
SynonymMap smap = sb.Build();


问:
Image slideshow
I am using javascript to slideshow images.Images are loaded only when the user clicks the next button i.e there is no preloading before the slideshow begins. With every image there is a supporting description which is loaded by the same javascript from an array which is stored in the javascript file. The effect of this is such that the description on next image is shown even before the image is displayed. Please suggest me some method so that i can delay displaying the desprition until the image is loaded. Also a loading symbol could be of great help. Please let me know how to do that. Thanks.</p>

答:
Show that image in a dynamically added iframe and add an onload listener to that iframe to show the description only when it loads.
Here's an example:</p>

```<code>    <script>
    var i;
    var ifm;
    var spinner;
    function popupIframeWithImageInit(id, parent, initImageNumber) {
        ifm = document.getElementById(id);
        i = initImageNumber;
        if(ifm === null) {
            ifm = document.createElement('iframe');
        }
        if(!spinner) {
            spinner = document.getElementById('spinner');
        }
        ifm.setAttribute('src', google_logos[i]);
        ifm.setAttribute('id', id);
        ifm.setAttribute('name', id);
        ifm.setAttribute('height', document.body.clientHeight - 50);
        ifm.setAttribute('width', '840');//width is fixed because the image is assumed to be fixed size 800
        ifm.setAttribute('scrolling', 'yes');
        ifm.setAttribute('frameborder', '0');
        ifm.style.display= 'none';
        ifm.onload = function() {
            document.getElementById("description").innerHTML = pic_description[i];
            ifm.style.display= '';
            spinner.style.display = 'none';
        };
        document.getElementById(parent).appendChild(ifm);
        spinner.style.display = '';
    }
    function next() {
        ifm.src = google_logos[++i];
        spinner.style.display = '';
        ifm.style.display= 'none';
    }
    function prev() {
        ifm.src = google_logos[--i];
        spinner.style.display = '';
        ifm.style.display= 'none';
    }
    function dismissPopupIframeWithImage(parentId, ifmId) {
        document.getElementById(parentId).removeChild(document.getElementById(ifmId));
        spinner.style.display = 'none';
        ifm.style.display= 'none';
        return false;
    }
    //use large images to see the spinner
    google_logos = ['http://sharevm.files.wordpress.com/2010/03/googlevsmicrosoft300dpi.jpg',
    'http://hermalditaness.files.wordpress.com/2010/01/2.jpg',
    'http://tuescape.files.wordpress.com/2008/10/tous20les20logos20google20par20aysoon.jpg',
    'http://isopixel.net/wp-content/uploads/2007/02/logos-superbowl.gif'];
    pic_description = ['http://sharevm.files.wordpress.com/2010/03/googlevsmicrosoft300dpi.jpg',
    'http://hermalditaness.files.wordpress.com/2010/01/2.jpg',
    'http://tuescape.files.wordpress.com/2008/10/tous20les20logos20google20par20aysoon.jpg',
    'http://isopixel.net/wp-content/uploads/2007/02/logos-superbowl.gif'];
</script>
<img id="spinner" src="http://publish.gawker.com/assets/ged/img/spinner_16.gif" style="position:absolute; left:100px; top:150px; display:none;"/>
<div style="" id="panel"></div>
<div style="" id="description"></div>
<div >
    <button onclick="popupIframeWithImageInit('imagePopup', 'panel', 1);">Open</button>
    <button onclick="prev();"><-- Prev</button>
    <button onclick="next();">Next --></button>
    <button onclick="dismissPopupIframeWithImage('panel', 'imagePopup');">Close</button>
</div
</code>```

Title: Image slideshow

Body:
Show that image in a dynamically added iframe and add an onload listener to that iframe to show the description only when it loads.
Here's an example:

    <script>
    var i;
    var ifm;
    var spinner;
    function popupIframeWithImageInit(id, parent, initImageNumber) {
        ifm = document.getElementById(id);
        i = initImageNumber;
        if(ifm === null) {
            ifm = document.createElement('iframe');
        }
        if(!spinner) {
            spinner = document.getElementById('spinner');
        }
        ifm.setAttribute('src', google_logos[i]);
        ifm.setAttribute('id', id);
        ifm.setAttribute('name', id);
        ifm.setAttribute('height', document.body.clientHeight - 50);
        ifm.setAttribute('width', '840');//width is fixed because the image is assumed to be fixed size 800
        ifm.setAttribute('scrolling', 'yes');
        ifm.setAttribute('frameborder', '0');
        ifm.style.display= 'none';
        ifm.onload = function() {
            document.getElementById("description").innerHTML = pic_description[i];
            ifm.style.display= '';
            spinner.style.display = 'none';
        };
        document.getElementById(parent).appendChild(ifm);
        spinner.style.display = '';
    }
    function next() {
        ifm.src = google_logos[++i];
        spinner.style.display = '';
        ifm.style.display= 'none';
    }
    function prev() {
        ifm.src = google_logos[--i];
        spinner.style.display = '';
        ifm.style.display= 'none';
    }
    function dismissPopupIframeWithImage(parentId, ifmId) {
        document.getElementById(parentId).removeChild(document.getElementById(ifmId));
        spinner.style.display = 'none';
        ifm.style.display= 'none';
        return false;
    }
    //use large images to see the spinner
    google_logos = ['http://sharevm.files.wordpress.com/2010/03/googlevsmicrosoft300dpi.jpg',
    'http://hermalditaness.files.wordpress.com/2010/01/2.jpg',
    'http://tuescape.files.wordpress.com/2008/10/tous20les20logos20google20par20aysoon.jpg',
    'http://isopixel.net/wp-content/uploads/2007/02/logos-superbowl.gif'];
    pic_description = ['http://sharevm.files.wordpress.com/2010/03/googlevsmicrosoft300dpi.jpg',
    'http://hermalditaness.files.wordpress.com/2010/01/2.jpg',
    'http://tuescape.files.wordpress.com/2008/10/tous20les20logos20google20par20aysoon.jpg',
    'http://isopixel.net/wp-content/uploads/2007/02/logos-superbowl.gif'];
</script>
<img id="spinner" src="http://publish.gawker.com/assets/ged/img/spinner_16.gif" style="position:absolute; left:100px; top:150px; display:none;"/>
<div style="" id="panel"></div>
<div style="" id="description"></div>
<div >
    <button onclick="popupIframeWithImageInit('imagePopup', 'panel', 1);">Open</button>
    <button onclick="prev();"><-- Prev</button>
    <button onclick="next();">Next --></button>
    <button onclick="dismissPopupIframeWithImage('panel', 'imagePopup');">Close</button>
</div


问:
How to write a symmetric Play Json formatter for a case class with one field in scala?
Suppose I have some case class with one field

```<code>case class Id(value: String)
</code>```

Trivially, I can define a formatter by defining the Reads and Writes separately:

```<code>private implicit val idReads: Reads[Id] =
    JsPath.read[String].map(Id)

private implicit val idWrites: Writes[Id] =
{
    id: Id => JsString(id.value)
}

private idFormats: Format[Id] = Format(idReads, idWrites)
</code>```

The documentation suggests there is a way to define a symmetric formatter for this scenario, but I haven't found the specific incantation which makes it work for this case. I've tried the below, but I get a compile error:

```<code>private implicit val idFormats: Format[Id] =
    JsPath.format[String](Id, unlift(Id.unapply))
</code>```

Specifically, I get this compile error:

```<code>[error] overloaded method value format with alternatives:
[error]   (w: play.api.libs.json.Writes[String])(implicit r: play.api.libs.json.Reads[String])play.api.libs.json.OFormat[String] <and>
[error]   (r: play.api.libs.json.Reads[String])(implicit w: play.api.libs.json.Writes[String])play.api.libs.json.OFormat[String] <and>
[error]   (implicit f: play.api.libs.json.Format[String])play.api.libs.json.OFormat[String]
[error]  cannot be applied to (Id.type, Id => String)
[error]         JsPath.format[String](Id, unlift(Id.unapply))
[error]                      ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 1 s, completed Nov 13, 2017 5:07:58 PM
</code>```

I've read the documentation, but it hasn't helped me. I'm certain there is some one-liner that can be applied for this case, as it is trivial for case classes with two fields:

```<code>case class MyRow(id: Id, myNum: MyNum)

private implicit val myRowFormats: Format[MyRow] =
    ((JsPath \ "id").format[Id] and
        (JsPath \ "num").format[MyNum]) (MyRow, unlift(MyRow.unapply))
</code>```

答:
If you really want Id to be serialized as a JSON string, here you go:

```<code>import play.api.libs.json._
import play.api.libs.functional.syntax._

case class Id(value: String)

implicit val idFormats: Format[Id] =
  implicitly[Format[String]].inmap(Id, unlift(Id.unapply))

Json.toJson(Id("asd")) == JsString("asd")
Json.toJson(Id("asd")).toString == "\"asd\""
Json.parse(Json.toJson(Id("asd")).toString).as[Id] == Id("asd")
</code>```

I wrote it this way to clearly illustrate that you use nothing else that a basic String formatter, which is defined in play-json.

Body:
Suppose I have some case class with one field

case class Id(value: String)

Trivially, I can define a formatter by defining the Reads and Writes separately:

private implicit val idReads: Reads[Id] =
    JsPath.read[String].map(Id)

private implicit val idWrites: Writes[Id] =
{
    id: Id => JsString(id.value)
}

private idFormats: Format[Id] = Format(idReads, idWrites)

The documentation suggests there is a way to define a symmetric formatter for this scenario, but I haven't found the specific incantation which makes it work for this case. I've tried the below, but I get a compile error:

private implicit val idFormats: Format[Id] =
    JsPath.format[String](Id, unlift(Id.unapply))

Specifically, I get this compile error:

[error] overloaded method value format with alternatives:
[error]   (w: play.api.libs.json.Writes[String])(implicit r: play.api.libs.json.Reads[String])play.api.libs.json.OFormat[String] <and>
[error]   (r: play.api.libs.json.Reads[String])(implicit w: play.api.libs.json.Writes[String])play.api.libs.json.OFormat[String] <and>
[error]   (implicit f: play.api.libs.json.Format[String])play.api.libs.json.OFormat[String]
[error]  cannot be applied to (Id.type, Id => String)
[error]         JsPath.format[String](Id, unlift(Id.unapply))
[error]                      ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 1 s, completed Nov 13, 2017 5:07:58 PM

I've read the documentation, but it hasn't helped me. I'm certain there is some one-liner that can be applied for this case, as it is trivial for case classes with two fields:

case class MyRow(id: Id, myNum: MyNum)

private implicit val myRowFormats: Format[MyRow] =
    ((JsPath \ "id").format[Id] and
        (JsPath \ "num").format[MyNum]) (MyRow, unlift(MyRow.unapply))

Body:
If you really want Id to be serialized as a JSON string, here you go:

import play.api.libs.json._
import play.api.libs.functional.syntax._

case class Id(value: String)

implicit val idFormats: Format[Id] =
  implicitly[Format[String]].inmap(Id, unlift(Id.unapply))

Json.toJson(Id("asd")) == JsString("asd")
Json.toJson(Id("asd")).toString == "\"asd\""
Json.parse(Json.toJson(Id("asd")).toString).as[Id] == Id("asd")

I wrote it this way to clearly illustrate that you use nothing else that a basic String formatter, which is defined in play-json.


问:
Expanding a list to include all possible pairwise combinations within a group
I am currently running a randomization where individuals of a given population are sampled and placed into groups of defined size. The result is a data frame seen below:

```<code>Ind Group
Sally   1
Bob 1
Sue 1
Joe 2
Jeff    2
Jess    2
Mary    2
Jim 3
James   3
</code>```

Is there a function which will allow me to expand the data set to show every possible within group pairing? (Desired output below). The pairings do not need to be reciprocal.

```<code>Group   Ind1    Ind2
1   Sally   Bob
1   Sally   Sue
1   Sue Bob
2   Joe Jeff
2   Joe Jess
2   Joe Mary
2   Jeff    Jess
2   Jess    Mary
2   Jeff    Mary
3   Jim James
</code>```

I feel like there must be a way to do this in dplyr, but for the life of me I can't seem to sort it out.

答:
Here is an option using data.table.  Convert to data.table (setDT(dt)), Do a cross join (CJ) grouped by 'Group' and remove the duplicated elements

```<code>library(data.table)
setDT(dt)[, CJ(Ind1 = Ind, Ind2 = Ind, unique = TRUE)[Ind1 != Ind2],
             Group][!duplicated(data.table(pmax(Ind1, Ind2), pmin(Ind1, Ind2)))]
#   Group  Ind1  Ind2
#1:     1   Bob Sally
#2:     1   Bob   Sue
#3:     1 Sally   Sue
#4:     2  Jeff  Jess
#5:     2  Jeff   Joe
#6:     2  Jeff  Mary
#7:     2  Jess   Joe
#8:     2  Jess  Mary
#9:     2   Joe  Mary
#10:    3 James   Jim
</code>```

Or using combn by 'Group'

```<code>setDT(dt)[, {temp <- combn(Ind, 2); .(Ind1 = temp[1,], Ind2 = temp[2,])}, Group]
</code>```

Body:
I am currently running a randomization where individuals of a given population are sampled and placed into groups of defined size. The result is a data frame seen below:

Ind Group
Sally   1
Bob 1
Sue 1
Joe 2
Jeff    2
Jess    2
Mary    2
Jim 3
James   3

Is there a function which will allow me to expand the data set to show every possible within group pairing? (Desired output below). The pairings do not need to be reciprocal.

Group   Ind1    Ind2
1   Sally   Bob
1   Sally   Sue
1   Sue Bob
2   Joe Jeff
2   Joe Jess
2   Joe Mary
2   Jeff    Jess
2   Jess    Mary
2   Jeff    Mary
3   Jim James

I feel like there must be a way to do this in dplyr, but for the life of me I can't seem to sort it out.

Body:
Here is an option using data.table.  Convert to data.table (setDT(dt)), Do a cross join (CJ) grouped by 'Group' and remove the duplicated elements

library(data.table)
setDT(dt)[, CJ(Ind1 = Ind, Ind2 = Ind, unique = TRUE)[Ind1 != Ind2],
             Group][!duplicated(data.table(pmax(Ind1, Ind2), pmin(Ind1, Ind2)))]
#   Group  Ind1  Ind2
#1:     1   Bob Sally
#2:     1   Bob   Sue
#3:     1 Sally   Sue
#4:     2  Jeff  Jess
#5:     2  Jeff   Joe
#6:     2  Jeff  Mary
#7:     2  Jess   Joe
#8:     2  Jess  Mary
#9:     2   Joe  Mary
#10:    3 James   Jim

Or using combn by 'Group'

setDT(dt)[, {temp <- combn(Ind, 2); .(Ind1 = temp[1,], Ind2 = temp[2,])}, Group]


问:
How to install Xamarin without Android SDKs for Visual Studio 2017?
I'm trying to install Visual Studio 2017 with Xamarin using its online installer. But when I tick "Mobile development with .NET" under Workloads it selects an Android SDK setup as well. If I try to untick it (Android SDK setup) then Xamarin will also be unticked.

How can I install only Xamarin without any Android SDKs for Visual Studio 2017?

答:
If you are freshly installing Visual Studio 2017, rather than checking Mobile development with .NET under Workloads you have to tick Xamarin under Individual Components in the installer window.

If you had already installed Visual Studio 17 without Xamarin, then go to,

Control Panel > Programs > Programs and Features

Select Microsoft Visual Studio 2017 and click on Change. In the appeared Window, select Modify under your specific Visual Studio version listed.

Go to the Individual components tab, now you can select only Xamarin and no other components will be attached to it.

This was my selections under Individual Components to install Xamarin without android. The Green Ticks would be a sufficiently enough selection.


问:
cvs2git checkout aborted with options-file (Windows)
I am trying to convert a CVS repositorys to GIT. But I only want to convert module by module because otherwise i get fals commits and file differences.
The repository contains 1 CVSROOT and 4 modules.

All commands are from this cvs2git documentation.
When i do it with the command-line options:

```<code>python path\to\cvs2git --blobfile=cvs2svn-tmp\git-blob.dat --dumpfile=cvs2svn-tmp\git-dump.dat "--username=cvs2git" \\remoteServer\path\to\myrepo\module
</code>```

the migration works.

The repository lies on a remote server and the git-blob.dat and git-dump.dat  are created on my pc.

To be more fexlible and to convert CVS-authors to git authors I want to use the options-file method but i get an error when doing so.

The steps

pass1 (CollectRevsPass)

pass2 (CleanMetadataPass)

pass3 (CollateSymbolsPass)

working fine but in pass4 (FilterSymbolsPass) i get an error:
The path to the module i want to convert is \\remoteServer\path\to\myrepo\module.

Filtering out excluded symbols and summarizing items... ERROR: The
  command 'cvs -Q -R -f -d :local:\\remoteServer\path\to\myrepo
  K co -r1.1 -p -kb module/.cvsignore' failed with exit status=1 and the
  following output: cvs [checkout aborted]: Local access to network
  share not supported (Use -N to o verride this error).

I dont know why this is because I used the same path to the repository in both the options-file and the command- line method.

So how do I solve this problem?

答:
If you run cvs2git from the command line, the default is to read data out of CVS using internal code. But if you run it using the options file method, the default is to use CVSRevisionReader, which uses the cvs command to get information out of your CVS repository.

One option would be to tell the options method to use ExternalBlobGenerator rather than GitRevisionCollector. But if your repository was in fact written by CVSNT (as opposed to standard CVS), then it is recommended that you use CVSRevisionReader.

The problem with "Local access to network share is not supported" is a CVSNT peculiarity. The error message also suggests the solution: add -N to the options. You can do that by following the instructions here and adjusting the parameters passed to the CVSRevisionReader constructor:

```<code>CVSRevisionReader(cvs_executable=r'cvs', global_options=['-q', '-N', '-f']),
</code>```

Hope that helps!

Body:
I am trying to convert a CVS repositorys to GIT. But I only want to convert module by module because otherwise i get fals commits and file differences.
The repository contains 1 CVSROOT and 4 modules.

All commands are from this cvs2git documentation.
When i do it with the command-line options:

python path\to\cvs2git --blobfile=cvs2svn-tmp\git-blob.dat --dumpfile=cvs2svn-tmp\git-dump.dat "--username=cvs2git" \\remoteServer\path\to\myrepo\module

the migration works.

The repository lies on a remote server and the git-blob.dat and git-dump.dat  are created on my pc.

To be more fexlible and to convert CVS-authors to git authors I want to use the options-file method but i get an error when doing so.

The steps

pass1 (CollectRevsPass)

pass2 (CleanMetadataPass)

pass3 (CollateSymbolsPass)

working fine but in pass4 (FilterSymbolsPass) i get an error:
The path to the module i want to convert is \\remoteServer\path\to\myrepo\module.

Filtering out excluded symbols and summarizing items... ERROR: The
  command 'cvs -Q -R -f -d :local:\\remoteServer\path\to\myrepo
  K co -r1.1 -p -kb module/.cvsignore' failed with exit status=1 and the
  following output: cvs [checkout aborted]: Local access to network
  share not supported (Use -N to o verride this error).

I dont know why this is because I used the same path to the repository in both the options-file and the command- line method.

So how do I solve this problem?

Body:
If you run cvs2git from the command line, the default is to read data out of CVS using internal code. But if you run it using the options file method, the default is to use CVSRevisionReader, which uses the cvs command to get information out of your CVS repository.

One option would be to tell the options method to use ExternalBlobGenerator rather than GitRevisionCollector. But if your repository was in fact written by CVSNT (as opposed to standard CVS), then it is recommended that you use CVSRevisionReader.

The problem with "Local access to network share is not supported" is a CVSNT peculiarity. The error message also suggests the solution: add -N to the options. You can do that by following the instructions here and adjusting the parameters passed to the CVSRevisionReader constructor:

CVSRevisionReader(cvs_executable=r'cvs', global_options=['-q', '-N', '-f']),

Hope that helps!


问:
partial search a dash value in a field in mysql
my mysql table name is: student having 3 fields id(pk, auto increment), name(varchar 200) and student_id(varchar 200)
values are lik

```<code>id name  student_id
1  abc   123-234
2  efg   2345678
3  xyz   1234-9
4. pxy   323-289
</code>```

now i want to select those students whose id like 3-2

```<code>SELECT * FROM student
WHERE student_id like '%3-2%'
</code>```

unfortunately the query return zero result.
any help is highly appreciable.

答:
```<code>SELECT * FROM student
WHERE student_id like '%3-2%'
</code>```

This works alright when I tested on MySql using PhpMyadmin.
If you use some other SQL, then try replacing single quotes to double quotes (' ' to " ").

Try firing the following query.

```<code>SELECT * FROM student
WHERE student_id like "%3-2%"
</code>```

Body:
my mysql table name is: student having 3 fields id(pk, auto increment), name(varchar 200) and student_id(varchar 200)
values are lik

id name  student_id
1  abc   123-234
2  efg   2345678
3  xyz   1234-9
4. pxy   323-289

now i want to select those students whose id like 3-2

SELECT * FROM student
WHERE student_id like '%3-2%'

unfortunately the query return zero result.
any help is highly appreciable.

Body:
SELECT * FROM student
WHERE student_id like '%3-2%'

This works alright when I tested on MySql using PhpMyadmin.
If you use some other SQL, then try replacing single quotes to double quotes (' ' to " ").

Try firing the following query.

SELECT * FROM student
WHERE student_id like "%3-2%"


问:
twilio react native integration
I'm trying to create a react native app that allows the user to click a button and a call to their phone will be placed using the TWILIO API. I have it working from terminal by typing node make_call.js(name of file) but i want the user to be able to make the call when they want to by inputing their phone number and clicking a call button. Heres my code. the credentials are fake. Is this possible??</p>

```<code>var accountSid = 'AC76d99966f35141f7c8585e31ed740480'
var authToken = '6470ce0905736f0f9da91456f088e97cc2'

var client = require('twilio')(accountSid, authToken);

client.calls.create({

url: 'https://demo.twilio.com/welcome/voice/',

to: '7781234564',
from: '6042322056',

}, function(err, call) {
if(err) {

    console.log(err);

} else {

    console.log(call.sid);
}

})
</code>```

答:
Twilio developer evangelist here.

You can actually build phone calling directly into your application using the Twilio Voice SDK.

There is already available to, built by the community, a React Native wrapper for the Twilio Voice SDK.

Let me know if that helps at all.

Title: twilio react native integration

Body:
I'm trying to create a react native app that allows the user to click a button and a call to their phone will be placed using the TWILIO API. I have it working from terminal by typing node make_call.js(name of file) but i want the user to be able to make the call when they want to by inputing their phone number and clicking a call button. Heres my code. the credentials are fake. Is this possible??

var accountSid = 'AC76d99966f35141f7c8585e31ed740480'
var authToken = '6470ce0905736f0f9da91456f088e97cc2'

var client = require('twilio')(accountSid, authToken);

client.calls.create({

url: 'https://demo.twilio.com/welcome/voice/',

to: '7781234564',
from: '6042322056',

}, function(err, call) {
if(err) {

    console.log(err);

} else {

    console.log(call.sid);
}

})


问:
Python : how to count amount of letters of alphabet in string in parts
How to count the amount of letters in this string between the different parts?
And the other way around: how to get the alphabetical string representation when the numbers are given?

Input: 'A-G H-O P Q-Z'

Output: (7, 8, 1, 10)

```<code>  q = list()

    for i in seq:
        if i is char:
            n = ord(i+1) - ord(i)
            q.append(n)
</code>```

答:
```<code>a = "A-G  N B-Z"
a = a.split()
b = []
for i in a:
    b.extend([i.split("-")])
print(b)
for lists in b:
    if len(lists) > 1:
        print(lists, ":", ord(lists[1]) - ord(lists[0]) + 1)
    else:
        print(lists, ":", 1)
</code>```

Output

```<code>[['A', 'G'], ['N'], ['B', 'Z']]
['A', 'G'] : 7
['N'] : 1
['B', 'Z'] : 25
</code>```

Using list comprehension

```<code>a = "A-G  N B-Z"

b = [i.split("-") for i in a.split()]

print(b)
for lists in b:
    if len(lists) > 1:
        print(lists, ":", ord(lists[1]) - ord(lists[0]) + 1)
    else:
        print(lists, ":", 1)
</code>```

Output

```<code>[['A', 'G'], ['N'], ['B', 'Z']]
['A', 'G'] : 7
['N'] : 1
['B', 'Z'] : 25
</code>```

Body:
How to count the amount of letters in this string between the different parts?
And the other way around: how to get the alphabetical string representation when the numbers are given?

Input: 'A-G H-O P Q-Z'

Output: (7, 8, 1, 10)

  q = list()

    for i in seq:
        if i is char:
            n = ord(i+1) - ord(i)
            q.append(n)

Body:
a = "A-G  N B-Z"
a = a.split()
b = []
for i in a:
    b.extend([i.split("-")])
print(b)
for lists in b:
    if len(lists) > 1:
        print(lists, ":", ord(lists[1]) - ord(lists[0]) + 1)
    else:
        print(lists, ":", 1)

Output

[['A', 'G'], ['N'], ['B', 'Z']]
['A', 'G'] : 7
['N'] : 1
['B', 'Z'] : 25

Using list comprehension

a = "A-G  N B-Z"

b = [i.split("-") for i in a.split()]

print(b)
for lists in b:
    if len(lists) > 1:
        print(lists, ":", ord(lists[1]) - ord(lists[0]) + 1)
    else:
        print(lists, ":", 1)

Output

[['A', 'G'], ['N'], ['B', 'Z']]
['A', 'G'] : 7
['N'] : 1
['B', 'Z'] : 25


问:
AbstractTable.update() - more complex condition?
From the docs:

```<code>int SqlUtil::AbstractTable::update (
hash  set,
hash  cond,
reference< string >   sql,
hash  opt
)
</code>```

updates rows in the table matching an optional condition and returns
  the count of rows updated; no transaction management is performed with
  this method
  Example:

int ucnt = table.update(("id": id), ("name": name));

where ("name": name) is a condition hash. Can the condition be more complex though? What if I had a list or a hash names and wanted to update all rows with a name that is in it? Is it possible to do it with one update statement or do I need to iterate through names?

答:
Yes, the where condition can be complex with update statements generated by SqlUtil.

The where condition is represented by the cond parameter in the method docs in your question.

To update rows based on a match from a list of values, use op_in() as follows:

```<code>int rows = table.update(("col1": val1, "col2": val2), ("col3": op_in(my_list)));
</code>```

This will generate SQL like:

```<code>update table set col1 = %v, col2 = %v where col3 in (%v)
</code>```

(NOTE: the exact SQL generated will differ depending on the underlying database, and the %v characters are placeholder specifications for bind by value operations in the generated SQL where the actual values are sent separately to the SQL server for reasons described in the previous link)

To update values based on a match of a another column value, use op_like() as in:

```<code>int rows = table.update(("col1": val1, "col2": val2), ("col3": op_like("%some value%")));
</code>```

Which will generate SQL like:

```<code>update table set col1 = %v, col2 = %v where col3 like %v
</code>```

In general you can use any SQL operator function in the where clause of the update method.

Body:
From the docs:

int SqlUtil::AbstractTable::update (
hash  set,
hash  cond,
reference< string >   sql,
hash  opt
)

updates rows in the table matching an optional condition and returns
  the count of rows updated; no transaction management is performed with
  this method
  Example:

int ucnt = table.update(("id": id), ("name": name));

where ("name": name) is a condition hash. Can the condition be more complex though? What if I had a list or a hash names and wanted to update all rows with a name that is in it? Is it possible to do it with one update statement or do I need to iterate through names?

Body:
Yes, the where condition can be complex with update statements generated by SqlUtil.

The where condition is represented by the cond parameter in the method docs in your question.

To update rows based on a match from a list of values, use op_in() as follows:

int rows = table.update(("col1": val1, "col2": val2), ("col3": op_in(my_list)));

This will generate SQL like:

update table set col1 = %v, col2 = %v where col3 in (%v)

(NOTE: the exact SQL generated will differ depending on the underlying database, and the %v characters are placeholder specifications for bind by value operations in the generated SQL where the actual values are sent separately to the SQL server for reasons described in the previous link)

To update values based on a match of a another column value, use op_like() as in:

int rows = table.update(("col1": val1, "col2": val2), ("col3": op_like("%some value%")));

Which will generate SQL like:

update table set col1 = %v, col2 = %v where col3 like %v

In general you can use any SQL operator function in the where clause of the update method.


问:
The behavior of virtual property in C#
I have next code:

```<code>FileStream fs = new FileStream("test.crp",FileMode.Create);
Aes aes = Aes.Create();
FileStream fsKeys = new FileStream("keys.key",FileMode.Open);
fsKeys.Read(aes.IV,0,16);
fsKeys.Read(aes.Key,0,32);
fsKeys.Close();
</code>```

And the problem is that: aes.IV and aes.Key are not changed during the Read operation from file.

And I can only assign a new value to them using the assignment operators:

```<code> byte [] iv = new byte[16];
 byte [] key = new byte[32];
 aes.IV = iv;
 aes.Key = key;
</code>```

Is it a right behavior?
If so, Then to what memory block do I read, when I use fs.Read?

答:
That is because Aes.IV and Aes.Key are returning "cloned" byte array of its member variables.

By fsKeys.Read(aes.IV,0,16);, you are modifying the cloned IV array, not the member variable behind aes.IV.

You can check the source code here:
https://referencesource.microsoft.com/#mscorlib/system/security/cryptography/symmetricalgorithm.cs,97c6f2476150a40d

Title: The behavior of virtual property in C#

Body:
I have next code:

FileStream fs = new FileStream("test.crp",FileMode.Create);
Aes aes = Aes.Create();
FileStream fsKeys = new FileStream("keys.key",FileMode.Open);
fsKeys.Read(aes.IV,0,16);
fsKeys.Read(aes.Key,0,32);
fsKeys.Close();

And the problem is that: aes.IV and aes.Key are not changed during the Read operation from file.

And I can only assign a new value to them using the assignment operators:

 byte [] iv = new byte[16];
 byte [] key = new byte[32];
 aes.IV = iv;
 aes.Key = key;

Is it a right behavior?
If so, Then to what memory block do I read, when I use fs.Read?


问:
Apple Appstore Screenshot Submission issue
I am having trouble submitting screenshots to the app store even with the right metadata.   I tried generating screenshots myself as well as using a third-party service.  I even created a new app to submit the screenshots with.   Is anyone else having the issue?  I went through the questions on this site where people had similar issues in the past and tried all of them.

答: Alright - strangely enough I can upload images using Safari browser and a hotspot from my phone.  Looks like Chrome and iTunes Connect are not friends anymore.</p>


问:
in AIML, can I give priority to the pattern matching
in AIML, if I have multiple files matching for the same pattern, how can I give precedence to match in one file ?</p>

答:
The AIML 1.0 wildcards * and _ are defined so that they match one or more words.   AIML 2.0 introduces two new wildcards, ^ and #, defined to match zero or more words.  As a shorthand description, we refer to these as “zero+ wildcards”.
Both ^ and # are defined to match 0 or more words.   The difference between them is the same as the difference between * and _.   The # matching operator has the highest priority in matching, followed by _, followed by an exact word match, followed by ^, and finally * has the lowest matching priority.
When defining a zero+ wildcard it is necessary to consider what the value of  (as well as  and ) should be when the wildcard match has zero length.   In AIML 2.0 we leave this up to the botmaster.  Each bot can have a global property named nullstar which the botmaster can set to “”, “unknown”, or any other value.
What’s new in AIML 2.0?


问:
modify output from 1 query
need Your suggestion Guy's. I don't know what the title of my question. but I has 1 query which give an ouput like this picture :

and this is my query :

```<code>select to_char(aa.DATE_AWAL, 'dd/mm/yyyy hh24:mi') DATE_AWAL, to_char(aa.DATE_AKHIR, 'dd/mm/yyyy hh24:mi') DATE_AKHIR,
to_char(aa.DATE_AWAL, 'hh24:mi') TIME_AWAL, to_char(aa.DATE_AKHIR, 'hh24:mi') TIME_AKHIR,
 cc.NAMARUANG,aa.IDMEETING from TMEETING_ROOM aa
inner join MMEETING_TYPE bb on aa.IDTYPE=bb.IDMEETING
inner join MMEETING_ROOM cc on aa.IDMEETINGROOM = cc.IDMEETINGROOM
inner join HR.VWKARYAWAN dd on aa.IDPENGUSUL=dd.IDKARYAWAN
inner join HR.MLOKASI ee on aa.IDLOKASI = ee.IDLOKASI
where aa.IS_DELETE IS NULL
and aa.IDCANCEL IS NULL
and (
wm_overlaps (
wm_period(aa.DATE_AWAL, aa.DATE_AKHIR),
wm_period(
TO_DATE(TO_CHAR(trunc(sysdate) + 08/24, 'yyyy-mm-dd hh24:mi'), 'yyyy-mm-dd hh24:mi'),
TO_DATE(TO_CHAR(trunc(sysdate) + 23/24, 'yyyy-mm-dd hh24:mi'), 'yyyy-mm-dd hh24:mi')
)
) = 1
) and aa.idlokasi = 'I' order by cc.NAMARUANG asc, aa.DATE_AWAL asc;
</code>```

Can any body give me suggestion how to make from this query can like this picture:

I'm newbie using oracle SQL

Note: the time and room are dynamic.

答:
Here is an example of how you might achieve a "generic" pivot table in MySQL.

The technique used requires row numbering (and in v8 of MySQL there will be an easier way to do this) but for now it requires using @variables.

Then, with each row number, we "transform" rows to columns using case expressions inside he max() function (conditional aggregates).

You will need to decide how many columns you need, and note that the order by inside the subquery t is vital to successfully arranging the data.

SQL Fiddle

MySQL 5.6 Schema Setup:

```<code>CREATE TABLE YourQueryHere
    (`id` int, `date_column` datetime, `code_column` varchar(7), `data_for_cells1` varchar(5), `data_for_cells2` varchar(5))
;

INSERT INTO YourQueryHere
    (`id`, `date_column`, `code_column`, `data_for_cells1`, `data_for_cells2`)
VALUES
    (1, '2017-11-14 00:00:00', 'Bintang', '09:00', '10:30'),
    (2, '2017-11-14 00:00:00', 'Bintang', '11:00', '12:30'),
    (3, '2017-11-14 00:00:00', 'Bintang', '14:00', '17:00'),
    (4, '2017-11-14 00:00:00', 'Sapporo', '11:30', '14:00'),
    (5, '2017-11-14 00:00:00', 'Sapporo', '14:30', '15:00'),
    (6, '2017-11-14 00:00:00', 'Tiger', '08:00', '09:30'),
    (7, '2017-11-14 00:00:00', 'Tiger', '11:00', '12:00')
;
</code>```

Query 1:

```<code>select
    code_column
  , max(case when RowNumber = 1 then concat(data_for_cells1, ' ', data_for_cells2) end) as pivcol1
  , max(case when RowNumber = 2 then concat(data_for_cells1, ' ', data_for_cells2) end) as pivcol2
  , max(case when RowNumber = 3 then concat(data_for_cells1, ' ', data_for_cells2) end) as pivcol3
  , max(case when RowNumber = 4 then concat(data_for_cells1, ' ', data_for_cells2) end) as pivcol4
from (
      select *
           , @counter :=IF(@prev=code_column,@counter+1,1)AS RowNumber
           , @prev := code_column
      from YourQueryHere
      cross join (select @counter:=0, @prev:= '') vars
      order by
            code_column, date_column
      ) t
group by
    code_column
order by
    code_column

;
</code>```

Results:

```<code>| code_column |     pivcol1 |     pivcol2 |     pivcol3 | pivcol4 |
|-------------|-------------|-------------|-------------|---------|
|     Bintang | 09:00 10:30 | 11:00 12:30 | 14:00 17:00 |  (null) |
|     Sapporo | 11:30 14:00 | 14:30 15:00 |      (null) |  (null) |
|       Tiger | 08:00 09:30 | 11:00 12:00 |      (null) |  (null) |
</code>```

Title: modify output from 1 query

Body:
need Your suggestion Guy's. I don't know what the title of my question. but I has 1 query which give an ouput like this picture :

and this is my query :

select to_char(aa.DATE_AWAL, 'dd/mm/yyyy hh24:mi') DATE_AWAL, to_char(aa.DATE_AKHIR, 'dd/mm/yyyy hh24:mi') DATE_AKHIR,
to_char(aa.DATE_AWAL, 'hh24:mi') TIME_AWAL, to_char(aa.DATE_AKHIR, 'hh24:mi') TIME_AKHIR,
 cc.NAMARUANG,aa.IDMEETING from TMEETING_ROOM aa
inner join MMEETING_TYPE bb on aa.IDTYPE=bb.IDMEETING
inner join MMEETING_ROOM cc on aa.IDMEETINGROOM = cc.IDMEETINGROOM
inner join HR.VWKARYAWAN dd on aa.IDPENGUSUL=dd.IDKARYAWAN
inner join HR.MLOKASI ee on aa.IDLOKASI = ee.IDLOKASI
where aa.IS_DELETE IS NULL
and aa.IDCANCEL IS NULL
and (
wm_overlaps (
wm_period(aa.DATE_AWAL, aa.DATE_AKHIR),
wm_period(
TO_DATE(TO_CHAR(trunc(sysdate) + 08/24, 'yyyy-mm-dd hh24:mi'), 'yyyy-mm-dd hh24:mi'),
TO_DATE(TO_CHAR(trunc(sysdate) + 23/24, 'yyyy-mm-dd hh24:mi'), 'yyyy-mm-dd hh24:mi')
)
) = 1
) and aa.idlokasi = 'I' order by cc.NAMARUANG asc, aa.DATE_AWAL asc;

Can any body give me suggestion how to make from this query can like this picture:

I'm newbie using oracle SQL

Note: the time and room are dynamic.

Body:
Here is an example of how you might achieve a "generic" pivot table in MySQL.

The technique used requires row numbering (and in v8 of MySQL there will be an easier way to do this) but for now it requires using @variables.

Then, with each row number, we "transform" rows to columns using case expressions inside he max() function (conditional aggregates).

You will need to decide how many columns you need, and note that the order by inside the subquery t is vital to successfully arranging the data.

SQL Fiddle

MySQL 5.6 Schema Setup:

CREATE TABLE YourQueryHere
    (`id` int, `date_column` datetime, `code_column` varchar(7), `data_for_cells1` varchar(5), `data_for_cells2` varchar(5))
;

INSERT INTO YourQueryHere
    (`id`, `date_column`, `code_column`, `data_for_cells1`, `data_for_cells2`)
VALUES
    (1, '2017-11-14 00:00:00', 'Bintang', '09:00', '10:30'),
    (2, '2017-11-14 00:00:00', 'Bintang', '11:00', '12:30'),
    (3, '2017-11-14 00:00:00', 'Bintang', '14:00', '17:00'),
    (4, '2017-11-14 00:00:00', 'Sapporo', '11:30', '14:00'),
    (5, '2017-11-14 00:00:00', 'Sapporo', '14:30', '15:00'),
    (6, '2017-11-14 00:00:00', 'Tiger', '08:00', '09:30'),
    (7, '2017-11-14 00:00:00', 'Tiger', '11:00', '12:00')
;

Query 1:

select
    code_column
  , max(case when RowNumber = 1 then concat(data_for_cells1, ' ', data_for_cells2) end) as pivcol1
  , max(case when RowNumber = 2 then concat(data_for_cells1, ' ', data_for_cells2) end) as pivcol2
  , max(case when RowNumber = 3 then concat(data_for_cells1, ' ', data_for_cells2) end) as pivcol3
  , max(case when RowNumber = 4 then concat(data_for_cells1, ' ', data_for_cells2) end) as pivcol4
from (
      select *
           , @counter :=IF(@prev=code_column,@counter+1,1)AS RowNumber
           , @prev := code_column
      from YourQueryHere
      cross join (select @counter:=0, @prev:= '') vars
      order by
            code_column, date_column
      ) t
group by
    code_column
order by
    code_column

;

Results:

| code_column |     pivcol1 |     pivcol2 |     pivcol3 | pivcol4 |
|-------------|-------------|-------------|-------------|---------|
|     Bintang | 09:00 10:30 | 11:00 12:30 | 14:00 17:00 |  (null) |
|     Sapporo | 11:30 14:00 | 14:30 15:00 |      (null) |  (null) |
|       Tiger | 08:00 09:30 | 11:00 12:00 |      (null) |  (null) |


问:
How to store the others option value and dropdown selected value based on the selected one in Ruby on Rails

I am new to ruby on rails, here i do hava drop down select box in that
  few options if i select any one of that it should be store, incase if
  i selected  others means one more text box should be appear and that
  value should be store in the database

ezetabs_controller.rb

```<code>def create
        @ezetab = Ezetab.new(ezetab_params)
        if @ezetab.save
            redirect_to @ezetab
        else
            render 'new'
        end
    end

    private

    def ezetab_params
       ep = params.require(:ezetab).permit(:name, :email, :phonenumber, :organization, :city)
       ep[:city] = params[:others] if params[:others].present?
       ep
    end
</code>```

ezetab.rb

```<code>validates :city, presence: true
</code>```

new.html.erb

```<code><div class="form-group clearfix">
                <div class="col-sm-2" id="mainone">
                    <%#= form.text_field :city, placeholder: "CITY", class: 'form-control required' %>
                    <%= form.select :city, options_for_select([['DELHI'],['GURGAON'],['FARIDABAD'],['GHAZIABAD'],['NOIDA'],['MUMBAI'],['THANE'], ['BANGALORE'],['OTHERS']]), {include_blank: 'CITY*'}, class: 'form-control required', name: 'city', :onchange => 'Checkselectedone(this.value);' %>
                        <% if @ezetab.errors[:city].present? %>
                            <span class="error_msg"><%= @ezetab.errors[:city][0]%></span>
                        <% end %>
                </div>
            </div>
            <div class="form-group clearfix">
                <div class="col-sm-2">
                    <%#= form.text_field :others, "", id: 'newtext',style: 'display:none;' %>
                    <%= text_field_tag :others, "", class: 'form-control', id: 'newtext', style: 'display:none;' %>

                </div>
            </div>

<script type="text/javascript">
function Checkselectedone(val){
    alert("one more text box is coming");
 var element=document.getElementById('newtext');
 if(val=='OTHERS')
   element.style.display='block';
 else
   element.style.display='none';
}
</code>```

can any one let me know that how to store the dropdown selected one
  because i can able to store only other oprtion text_field only
  selected drop down i am unable to select please let me know, since i
  am donig from yesterday to finish this one,   thanks in advance

答:
Have you tried like this?</p>

```<code>ezetabs_controller.rb

def create

    if params[:ezetab][:others] != nil
      eze_params = ezetab_params.merge!(city: params[:ezetab][:others])
    else
      eze_params = ezetab_params
    end

    @ezetab = Ezetab.new(eze_params)
    if @ezetab.save
        redirect_to @ezetab
    else
        render 'new'
    end
end

private

def ezetab_params
   ep = params.require(:ezetab).permit(:name, :email, :phonenumber, :organization, :city)
end
</code>```

Body:
I am new to ruby on rails, here i do hava drop down select box in that
  few options if i select any one of that it should be store, incase if
  i selected  others means one more text box should be appear and that
  value should be store in the database

ezetabs_controller.rb

def create
        @ezetab = Ezetab.new(ezetab_params)
        if @ezetab.save
            redirect_to @ezetab
        else
            render 'new'
        end
    end

    private

    def ezetab_params
       ep = params.require(:ezetab).permit(:name, :email, :phonenumber, :organization, :city)
       ep[:city] = params[:others] if params[:others].present?
       ep
    end

ezetab.rb

validates :city, presence: true

new.html.erb

                    <%#= form.text_field :city, placeholder: "CITY", class: 'form-control required' %>
                    <%= form.select :city, options_for_select([['DELHI'],['GURGAON'],['FARIDABAD'],['GHAZIABAD'],['NOIDA'],['MUMBAI'],['THANE'], ['BANGALORE'],['OTHERS']]), {include_blank: 'CITY*'}, class: 'form-control required', name: 'city', :onchange => 'Checkselectedone(this.value);' %>
                        <% if @ezetab.errors[:city].present? %>
                            <%= @ezetab.errors[:city][0]%>
                        <% end %>

                    <%#= form.text_field :others, "", id: 'newtext',style: 'display:none;' %>
                    <%= text_field_tag :others, "", class: 'form-control', id: 'newtext', style: 'display:none;' %>

Body:
Have you tried like this?

ezetabs_controller.rb

def create

    if params[:ezetab][:others] != nil
      eze_params = ezetab_params.merge!(city: params[:ezetab][:others])
    else
      eze_params = ezetab_params
    end

    @ezetab = Ezetab.new(eze_params)
    if @ezetab.save
        redirect_to @ezetab
    else
        render 'new'
    end
end

private

def ezetab_params
   ep = params.require(:ezetab).permit(:name, :email, :phonenumber, :organization, :city)
end


问:
Soap Client Complex Type PHP Request
I have a web-service with following link
I'm trying to access the function name with SubmitRequestType but it seems the function is not exist instead submitAnsiSingle this is the correct function name what I tried so far is ,

```<code>$wsdl = 'https://ww3.navicure.com:7000/webservices/NavicureSubmissionService?WSDL';

class SecurityHeaderType {
        private $submitterIdentifier;
        private $originatingIdentifier;
        private $submitterPassword;
        private $submissionId;
        function SecurityHeaderType() {
            $this->submitterIdentifier = '***';
            $this->originatingIdentifier = '****';
            $this->submitterPassword = '****';
            $this->submissionId = '';

        }
}

class SubmitRequestType {

        private $submitterIdentifier;
        private $originatingIdentifier;
        private $submitterPassword;
        private $submissionId;
        private $timeout;
        private $transactionType;
        private $submittedAnsiVersion;
        private $resultAnsiVersion;
        private $submitterSubmissionId;
        private $processingOption;
        private $payload;
        private $exceptions;

        function SubmitRequestType() {

        $this->submitterIdentifier = '***';
        $this->originatingIdentifier = '***';
        $this->submitterPassword = '**';
        $this->submissionId = '**';
        $this->timeout = 60 ;
        $this->transactionType = "E";
        $this->submittedAnsiVersion = '5010';
        $this->resultAnsiVersion = '5010';
        $this->submitterSubmissionId = '**';
        $this->processingOption = 'R';
        $this->payload = 'EDI-270-Request';
        $this->exceptions = true;
        }
}

$soapheader = new SecurityHeaderType();

$submitrequest = new SubmitRequestType();

    $service = new \SoapClient($wsdl);
    $result= $service->SubmitAnsiSingle($submitrequest);
    echo "<pre/>";print_r($result);

    $types = $service->__getTypes ();
    $functions = $service->__getFunctions ();
    //echo "<pre/>";print_r($types);
    //echo "<pre/>";print_r($functions);
</code>```

But I'm getting the response like below it seems the request is processing on their end but the SecurityHeaderType is not parsing their end.

```<code>stdClass Object
(
    [transactionTyp] => E
    [submitterSubmissionId] => ****
    [submittedAnsiVersion] => 5010
    [resultAnsiVersion] => 5010
    [statusHeader] => stdClass Object
        (
            [statusCode] => 1150
            [statusMessage] => com.navicure.webservices.core.WSCoreException: Account does not exist for ''
            [requestProcessed] =>
        )

)
</code>```

Any hint will be highly appreciate

Thanks in advance.

答:
I found the solution!. It seems the PHP -> .NET web service comparability issue. So from PHP the complex type SOAP (this kind of format) can't access I found some usefull post here. So I switched SOAP to plain XML request with CURL and it seems working fine!. Also from WSDL link we can extract the request template using this online service .
So my final code look like below.

```<code>$xml_data = "<?xml version='1.0' encoding='UTF-8'?>
<s12:Envelope xmlns:s12='http://www.w3.org/2003/05/soap-envelope'>
  <s12:Header>
    <ns1:SecurityHeaderElement xmlns:ns1='http://www.navicure.com/2009/11/NavicureSubmissionService'>
      <ns1:originatingIdentifier>****</ns1:originatingIdentifier>
      <ns1:submitterIdentifier>****</ns1:submitterIdentifier>
      <ns1:submitterPassword>***</ns1:submitterPassword>
      <ns1:submissionId>?999?</ns1:submissionId>
    </ns1:SecurityHeaderElement>
  </s12:Header>
  <s12:Body>
    <ns1:SubmitAnsiSingleRequestElement xmlns:ns1='http://www.navicure.com/2009/11/NavicureSubmissionService'>
      <ns1:timeout>60</ns1:timeout>
      <ns1:transactionType>E</ns1:transactionType>
      <ns1:submittedAnsiVersion>5010</ns1:submittedAnsiVersion>
      <ns1:resultAnsiVersion>5010</ns1:resultAnsiVersion>
      <ns1:submitterSubmissionId></ns1:submitterSubmissionId>
      <ns1:processingOption>R</ns1:processingOption>
      <ns1:payload>EDI270Payload</ns1:payload>
    </ns1:SubmitAnsiSingleRequestElement>
  </s12:Body>
</s12:Envelope>";
$URL = "https://ww3.navicure.com:7000/webservices/NavicureSubmissionService";

$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);

print_r($output);
</code>```

Hope this will help someone else in future.

Title: Soap Client Complex Type PHP Request

Body:
I have a web-service with following link
I'm trying to access the function name with SubmitRequestType but it seems the function is not exist instead submitAnsiSingle this is the correct function name what I tried so far is ,

$wsdl = 'https://ww3.navicure.com:7000/webservices/NavicureSubmissionService?WSDL';

class SecurityHeaderType {
        private $submitterIdentifier;
        private $originatingIdentifier;
        private $submitterPassword;
        private $submissionId;
        function SecurityHeaderType() {
            $this->submitterIdentifier = '***';
            $this->originatingIdentifier = '****';
            $this->submitterPassword = '****';
            $this->submissionId = '';

        }
}

class SubmitRequestType {

        private $submitterIdentifier;
        private $originatingIdentifier;
        private $submitterPassword;
        private $submissionId;
        private $timeout;
        private $transactionType;
        private $submittedAnsiVersion;
        private $resultAnsiVersion;
        private $submitterSubmissionId;
        private $processingOption;
        private $payload;
        private $exceptions;

        function SubmitRequestType() {

        $this->submitterIdentifier = '***';
        $this->originatingIdentifier = '***';
        $this->submitterPassword = '**';
        $this->submissionId = '**';
        $this->timeout = 60 ;
        $this->transactionType = "E";
        $this->submittedAnsiVersion = '5010';
        $this->resultAnsiVersion = '5010';
        $this->submitterSubmissionId = '**';
        $this->processingOption = 'R';
        $this->payload = 'EDI-270-Request';
        $this->exceptions = true;
        }
}

$soapheader = new SecurityHeaderType();

$submitrequest = new SubmitRequestType();

    $service = new \SoapClient($wsdl);
    $result= $service->SubmitAnsiSingle($submitrequest);
    echo "
";print_r($result);

    $types = $service->__getTypes ();
    $functions = $service->__getFunctions ();
    //echo "
";print_r($types);
    //echo "
";print_r($functions);

But I'm getting the response like below it seems the request is processing on their end but the SecurityHeaderType is not parsing their end.

stdClass Object
(
    [transactionTyp] => E
    [submitterSubmissionId] => ****
    [submittedAnsiVersion] => 5010
    [resultAnsiVersion] => 5010
    [statusHeader] => stdClass Object
        (
            [statusCode] => 1150
            [statusMessage] => com.navicure.webservices.core.WSCoreException: Account does not exist for ''
            [requestProcessed] =>
        )

)

Any hint will be highly appreciate

Thanks in advance.

Body:
I found the solution!. It seems the PHP -> .NET web service comparability issue. So from PHP the complex type SOAP (this kind of format) can't access I found some usefull post here. So I switched SOAP to plain XML request with CURL and it seems working fine!. Also from WSDL link we can extract the request template using this online service .
So my final code look like below.

$xml_data = "<?xml version='1.0' encoding='UTF-8'?>
<s12:Envelope xmlns:s12='http://www.w3.org/2003/05/soap-envelope'>
  <s12:Header>
    <ns1:SecurityHeaderElement xmlns:ns1='http://www.navicure.com/2009/11/NavicureSubmissionService'>
      <ns1:originatingIdentifier>****</ns1:originatingIdentifier>
      <ns1:submitterIdentifier>****</ns1:submitterIdentifier>
      <ns1:submitterPassword>***</ns1:submitterPassword>
      <ns1:submissionId>?999?</ns1:submissionId>
    </ns1:SecurityHeaderElement>
  </s12:Header>
  <s12:Body>
    <ns1:SubmitAnsiSingleRequestElement xmlns:ns1='http://www.navicure.com/2009/11/NavicureSubmissionService'>
      <ns1:timeout>60</ns1:timeout>
      <ns1:transactionType>E</ns1:transactionType>
      <ns1:submittedAnsiVersion>5010</ns1:submittedAnsiVersion>
      <ns1:resultAnsiVersion>5010</ns1:resultAnsiVersion>
      <ns1:submitterSubmissionId></ns1:submitterSubmissionId>
      <ns1:processingOption>R</ns1:processingOption>
      <ns1:payload>EDI270Payload</ns1:payload>
    </ns1:SubmitAnsiSingleRequestElement>
  </s12:Body>
</s12:Envelope>";
$URL = "https://ww3.navicure.com:7000/webservices/NavicureSubmissionService";

$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);

print_r($output);

Hope this will help someone else in future.


问:
Software for taking notes on programming
What type of software is good for taking notes on programming?  For example, if I want to jot down different methods/functions that are useful for different things.  Ideally, the software would have  syntax highlighting.

The software would need to support Mac OS X.  I will most probably be using this for Objective-C/iPhone development and Ruby on Rails development.

I want something that can shift between ordinary text and coding syntax.  For example if I was to type:

In order to create a rectangle in Objective-C with a name square use: (CGRect *) square...........

I would like the objective-C code to have syntax highlighting but not the rest of the text.

Thanks!

P.S. I use textmate generally for coding.

答: I usually just use an editor for simple notes. If I'm on Linux, I usually choose gedit. If I'm on something else, Scite is nice. I think it's very specific to what your needs are. Are you looking for a document editor which happens to be able to do syntax highlighting also?</p>


问:
Adding inner shadow to top of UIView
I looked up but I couldn't find how I can add an inner shadow to UIView, only top (from top to bottom) for Swift. What is the best way add inner circle in Swift?

Edit: I've found some questions & answers on SO however they are either in obj-c or looks so complicated. I was just looking for a more Swifty way, if there is any

What I want to achieve:

答:
I updated @NRitH's answer and made an extension out of it also modified so that you can manipulate multiple edges in one go

usage

myview.addShadow(to: [.top,.bottom], radius: 15.0)

```<code>extension UIView{

    func addShadow(to edges:[UIRectEdge], radius:CGFloat){

        let toColor = UIColor(colorLiteralRed: 235.0/255.0, green: 235.0/255.0, blue: 235.0/255.0, alpha: 1.0)
        let fromColor = UIColor(colorLiteralRed: 188.0/255.0, green: 188.0/255.0, blue: 188.0/255.0, alpha: 1.0)
        // Set up its frame.
        let viewFrame = self.frame
        for edge in edges{
            let gradientlayer          = CAGradientLayer()
            gradientlayer.colors       = [fromColor.cgColor,toColor.cgColor]
            gradientlayer.shadowRadius = radius

            switch edge {
            case UIRectEdge.top:
                gradientlayer.startPoint = CGPoint(x: 0.5, y: 0.0)
                gradientlayer.endPoint = CGPoint(x: 0.5, y: 1.0)
                gradientlayer.frame = CGRect(x: 0.0, y: 0.0, width: viewFrame.width, height: gradientlayer.shadowRadius)
            case UIRectEdge.bottom:
                gradientlayer.startPoint = CGPoint(x: 0.5, y: 1.0)
                gradientlayer.endPoint = CGPoint(x: 0.5, y: 0.0)
                gradientlayer.frame = CGRect(x: 0.0, y: viewFrame.height - gradientlayer.shadowRadius, width: viewFrame.width, height: gradientlayer.shadowRadius)
            case UIRectEdge.left:
                gradientlayer.startPoint = CGPoint(x: 0.0, y: 0.5)
                gradientlayer.endPoint = CGPoint(x: 1.0, y: 0.5)
                gradientlayer.frame = CGRect(x: 0.0, y: 0.0, width: gradientlayer.shadowRadius, height: viewFrame.height)
            case UIRectEdge.right:
                gradientlayer.startPoint = CGPoint(x: 1.0, y: 0.5)
                gradientlayer.endPoint = CGPoint(x: 0.0, y: 0.5)
                gradientlayer.frame = CGRect(x: viewFrame.width - gradientlayer.shadowRadius, y: 0.0, width: gradientlayer.shadowRadius, height: viewFrame.height)
            default:
                break
            }
            self.layer.addSublayer(gradientlayer)
        }

    }

    func removeAllSublayers(){
        if let sublayers = self.layer.sublayers, !sublayers.isEmpty{
            for sublayer in sublayers{
                sublayer.removeFromSuperlayer()
            }
        }
    }

}
</code>```

Title: Adding inner shadow to top of UIView

Body:
I updated @NRitH's answer and made an extension out of it also modified so that you can manipulate multiple edges in one go

usage

myview.addShadow(to: [.top,.bottom], radius: 15.0)

extension UIView{

    func addShadow(to edges:[UIRectEdge], radius:CGFloat){

        let toColor = UIColor(colorLiteralRed: 235.0/255.0, green: 235.0/255.0, blue: 235.0/255.0, alpha: 1.0)
        let fromColor = UIColor(colorLiteralRed: 188.0/255.0, green: 188.0/255.0, blue: 188.0/255.0, alpha: 1.0)
        // Set up its frame.
        let viewFrame = self.frame
        for edge in edges{
            let gradientlayer          = CAGradientLayer()
            gradientlayer.colors       = [fromColor.cgColor,toColor.cgColor]
            gradientlayer.shadowRadius = radius

            switch edge {
            case UIRectEdge.top:
                gradientlayer.startPoint = CGPoint(x: 0.5, y: 0.0)
                gradientlayer.endPoint = CGPoint(x: 0.5, y: 1.0)
                gradientlayer.frame = CGRect(x: 0.0, y: 0.0, width: viewFrame.width, height: gradientlayer.shadowRadius)
            case UIRectEdge.bottom:
                gradientlayer.startPoint = CGPoint(x: 0.5, y: 1.0)
                gradientlayer.endPoint = CGPoint(x: 0.5, y: 0.0)
                gradientlayer.frame = CGRect(x: 0.0, y: viewFrame.height - gradientlayer.shadowRadius, width: viewFrame.width, height: gradientlayer.shadowRadius)
            case UIRectEdge.left:
                gradientlayer.startPoint = CGPoint(x: 0.0, y: 0.5)
                gradientlayer.endPoint = CGPoint(x: 1.0, y: 0.5)
                gradientlayer.frame = CGRect(x: 0.0, y: 0.0, width: gradientlayer.shadowRadius, height: viewFrame.height)
            case UIRectEdge.right:
                gradientlayer.startPoint = CGPoint(x: 1.0, y: 0.5)
                gradientlayer.endPoint = CGPoint(x: 0.0, y: 0.5)
                gradientlayer.frame = CGRect(x: viewFrame.width - gradientlayer.shadowRadius, y: 0.0, width: gradientlayer.shadowRadius, height: viewFrame.height)
            default:
                break
            }
            self.layer.addSublayer(gradientlayer)
        }

    }

    func removeAllSublayers(){
        if let sublayers = self.layer.sublayers, !sublayers.isEmpty{
            for sublayer in sublayers{
                sublayer.removeFromSuperlayer()
            }
        }
    }

}


问:
BULK INSERT Incorrect syntax near 'BULK'. / BCP pushing to prod instead of dev
First problem: I'm new to SSMS and trying to fill an empty table with a csv file:

```<code>BULK INSERT database.schema.ExpectedValuesBASE
FROM 'bla\bla\bla\output_teaching.csv'
WITH
    (
        FIRSTROW = 2,
        FIELDTERMINATOR = ',',  --CSV field delimiter
        ROWTERMINATOR = '\n',   --Use to shift the control to next row
        TABLOCK
    );
</code>```

I'm getting the following error:

Parse error at line: 1, column: 1: Incorrect syntax near 'BULK'.

Second problem:

```<code>BCP database.schema.ExpectedValuesBASE in blah/bla/output.csv -S DEVSERVERNAME -U ******** -P ****** -t ',' -q -c
</code>```

This is writing the values to the production server, rather than the specified DEVSERVERNAME

答:
This query uses bulk insert to store the file in a #temptable and then inserts the contents from this temp table into the table you want in the database.

```<code> CREATE TABLE #temptable (col1,col2,col3)
 BULK INSERT #temptable from 'C:\yourfilelocation\yourfile.csv'
 WITH
    (
    FIRSTROW = 2,
    fieldterminator = ',',
    rowterminator = '0x0A'
    ) `

INSERT INTO yourTableInDataBase (col1,col2,col3)
SELECT (col1,col2,col3)
FROM #temptable
</code>```

You can either execute query above in SQL Server, or  you can put it inside a stored procedure and call the stored procedure using batch. copy the following code and put this inside textfile and save as .cmd extension and run.

```<code>set MYDB= yourDBname
set MYUSER=youruser
set MYPASSWORD=yourpassword
set MYSERVER=yourservername
sqlcmd -S %MYSERVER% -d %MYDB% -U %MYUSER% -P %MYPASSWORD% -h -1 -s "," -W -Q "exec yourstoredprocedure"
</code>```

Body:
First problem: I'm new to SSMS and trying to fill an empty table with a csv file:

BULK INSERT database.schema.ExpectedValuesBASE
FROM 'bla\bla\bla\output_teaching.csv'
WITH
    (
        FIRSTROW = 2,
        FIELDTERMINATOR = ',',  --CSV field delimiter
        ROWTERMINATOR = '\n',   --Use to shift the control to next row
        TABLOCK
    );

I'm getting the following error:

Parse error at line: 1, column: 1: Incorrect syntax near 'BULK'.

Second problem:

BCP database.schema.ExpectedValuesBASE in blah/bla/output.csv -S DEVSERVERNAME -U ******** -P ****** -t ',' -q -c

This is writing the values to the production server, rather than the specified DEVSERVERNAME

Body:
This query uses bulk insert to store the file in a #temptable and then inserts the contents from this temp table into the table you want in the database.

 CREATE TABLE #temptable (col1,col2,col3)
 BULK INSERT #temptable from 'C:\yourfilelocation\yourfile.csv'
 WITH
    (
    FIRSTROW = 2,
    fieldterminator = ',',
    rowterminator = '0x0A'
    ) `

INSERT INTO yourTableInDataBase (col1,col2,col3)
SELECT (col1,col2,col3)
FROM #temptable

You can either execute query above in SQL Server, or  you can put it inside a stored procedure and call the stored procedure using batch. copy the following code and put this inside textfile and save as .cmd extension and run.

set MYDB= yourDBname
set MYUSER=youruser
set MYPASSWORD=yourpassword
set MYSERVER=yourservername
sqlcmd -S %MYSERVER% -d %MYDB% -U %MYUSER% -P %MYPASSWORD% -h -1 -s "," -W -Q "exec yourstoredprocedure"


问:
jQuery slide in and out issue
Here is my URL site.

Here you can see a search bar on the top right corner. If you click on the search icon it will show you a search box. Now again, If you click on the search icon again then it's should close the search box like sliding effect but it's not working.

JQuery code:

```<code>jQuery(document).ready(function(){
  jQuery('#search2').on("click",(function(e){
    jQuery(".form-group").addClass("sb-search-open");
      e.stopPropagation()
    }));
    jQuery(document).on("click", function(e) {
      if (jQuery(e.target).is("#search2") === false && jQuery(".form-control").val().length == 0) {
        jQuery(".form-group").removeClass("sb-search-open");
      }
    });
    jQuery(".form-control-submit").click(function(e){
      jQuery(".form-control").each(function(){
      if(jQuery(".form-control").val().length == 0){
        e.preventDefault();
        jQuery(this).css('border', '2px solid red');
      }
    })
  })
})
</code>```

How can I fix it?

答:
Based on your code, looks like you are closing the search bar when clicking anywhere else except the search icon itself

```<code>jQuery(e.target).is("#search2") === false
</code>```

And it works as expected, if you want it to behave otherwise then replace false with true.

Title: jQuery slide in and out issue

Body:
Here is my URL site.

Here you can see a search bar on the top right corner. If you click on the search icon it will show you a search box. Now again, If you click on the search icon again then it's should close the search box like sliding effect but it's not working.

JQuery code:

jQuery(document).ready(function(){
  jQuery('#search2').on("click",(function(e){
    jQuery(".form-group").addClass("sb-search-open");
      e.stopPropagation()
    }));
    jQuery(document).on("click", function(e) {
      if (jQuery(e.target).is("#search2") === false && jQuery(".form-control").val().length == 0) {
        jQuery(".form-group").removeClass("sb-search-open");
      }
    });
    jQuery(".form-control-submit").click(function(e){
      jQuery(".form-control").each(function(){
      if(jQuery(".form-control").val().length == 0){
        e.preventDefault();
        jQuery(this).css('border', '2px solid red');
      }
    })
  })
})

How can I fix it?

Body:
Based on your code, looks like you are closing the search bar when clicking anywhere else except the search icon itself

jQuery(e.target).is("#search2") === false

And it works as expected, if you want it to behave otherwise then replace false with true.


问:
Distribution Profile requesting a Developer certificate
Using Xcode 9.1, after building an iOS app, I try to archive it.
But I get the following error message:

Provisioning profile "MyAppProfile" doesn't include signing certificate "iPhone Developer: My Name (X1YZ2AB3CD)".

After looking closer, I see that MyAppProfile is a Distribution Provisioning Profile (this is what I want) and X1YZ2AB3CD matches a Developer certificate.But when building MyAppProfile (for App Store) I was provided with the choice of a unique Distribution certificate (No Developer certificate). So why do I get this message complaining about MyAppProfile not including a Developer certificate. I am kind of lost. Anyone can shed some light here?

In case I give up with manual signing, here is what I get when trying to upload to appStore:

Automatic signing is unable to resolve an issue with the "MyApp.app" target's entitlements.
Switch to manual signing and resolve the issue by downloading a matching provisioning profile from the developer website. Atlernatively, to continue using automatic signing, remove these entitlements from your entitlements file and their associated functionality from your code. Then rebuild your archive and try again.

Provisioning profile failed qualification
Profile doesn't match the entitlements file's value for the application-identifier entitlement.

答:
Remove certificates from your keychain access which doesn't include private keys. I mean the certificates which does not have arrow(play button type) on left side of name.

and then from your xcode select your team from general and unable automatic code signing and then try!

You can refer this post or this post


问:
list file extensions supported by OpenCV
In OpenCV, I see imread() and VideoCapture() both take a string to a file path of multiple extensions. Is there a way to get a list of extensions that are supported by them? For example, getting a list of "jpg", "png", "mov", "mpg", etc.? I assume this is system dependent and others have needed to query this at runtime.

Furthermore, how is support determined? If have something like the below code and the Mat I get back always seems partially corrupted (I can see a bit of the image). It doesn't seem to change regardless of the frame number I ask for. I can play this video in my video player "totem", but I'm not even sure if totem and OpenCV are even using the same codec for this file.

```<code>Mat fromVideo(std::string _videoPath, int frame) {
    VideoCapture capture(_videoPath);

    Mat f;
    for (int i = 0; i < frame; i++) {
        capture >> f;
    }
    return f;
}
</code>```

答:
Just update:

```<code>cv::VideoCapture cap("D:\\test.mp4")
</code>```

works for me.

Body:
In OpenCV, I see imread() and VideoCapture() both take a string to a file path of multiple extensions. Is there a way to get a list of extensions that are supported by them? For example, getting a list of "jpg", "png", "mov", "mpg", etc.? I assume this is system dependent and others have needed to query this at runtime.

Furthermore, how is support determined? If have something like the below code and the Mat I get back always seems partially corrupted (I can see a bit of the image). It doesn't seem to change regardless of the frame number I ask for. I can play this video in my video player "totem", but I'm not even sure if totem and OpenCV are even using the same codec for this file.

Mat fromVideo(std::string _videoPath, int frame) {
    VideoCapture capture(_videoPath);

    Mat f;
    for (int i = 0; i < frame; i++) {
        capture >> f;
    }
    return f;
}

Body:
Just update:

cv::VideoCapture cap("D:\\test.mp4")

works for me.