问:
VBS unzipping - object required: 'objshell.NameSpace(...)'
I know very little about bash or vbs. I am trying to make a script that will automatically unzip a zip called 'dungeon.zip', which contains a little game I programmed. I want to unzip it to a folder called dungeon in the same directory that the zip file was in. I used the code from this answer, and replaced the files with my files:

```<code>strZipFile  = "dungeon.zip"
strUnzipped = "dungeon\"

Sub UnZip(ExtractTo,ZipFile)

Set fso = CreateObject("Scripting.FileSystemObject")
    If NOT fso.FolderExists(ExtractTo) Then
       fso.CreateFolder(ExtractTo)
End If

Set objShell = CreateObject("Shell.Application")
Set FilesInZip=objShell.NameSpace(ZipFile).items

ObjShell.NameSpace(ExtractTo).CopyHere(FilesInZip)
Set fso = Nothing
Set objShell = Nothing
End Sub

set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("MyDocuments")

strZipPath   = strDesktop & strZipFile
strUnzipPath = strDesktop & strUnzipped

UnZip strUnzipPath , strZipPath
</code>```

As in his answer, I run the .vbs from a cmd file:

```<code>cscript UnzipZip.vbs
</code>```

Here is the error:

```<code>C:\Users\Brett\Downloads\UnzipZip.vbs(12, 1) Microsoft VBScript runtime error: Object required: 'objShell.NameSpace(...)'
</code>```

Any idea on how to fix this?

答: Just to elaborate the cause of the error. I also encountered the same scenario and it is because the zip file location is not valid or does not exists. Try to put the exact path of the zip file and it will work.</p>

Body:
I know very little about bash or vbs. I am trying to make a script that will automatically unzip a zip called 'dungeon.zip', which contains a little game I programmed. I want to unzip it to a folder called dungeon in the same directory that the zip file was in. I used the code from this answer, and replaced the files with my files:

strZipFile  = "dungeon.zip"
strUnzipped = "dungeon\"

Sub UnZip(ExtractTo,ZipFile)

Set fso = CreateObject("Scripting.FileSystemObject")
    If NOT fso.FolderExists(ExtractTo) Then
       fso.CreateFolder(ExtractTo)
End If

Set objShell = CreateObject("Shell.Application")
Set FilesInZip=objShell.NameSpace(ZipFile).items

ObjShell.NameSpace(ExtractTo).CopyHere(FilesInZip)
Set fso = Nothing
Set objShell = Nothing
End Sub

set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("MyDocuments")

strZipPath   = strDesktop & strZipFile
strUnzipPath = strDesktop & strUnzipped

UnZip strUnzipPath , strZipPath

As in his answer, I run the .vbs from a cmd file:

cscript UnzipZip.vbs

Here is the error:

C:\Users\Brett\Downloads\UnzipZip.vbs(12, 1) Microsoft VBScript runtime error: Object required: 'objShell.NameSpace(...)'

Any idea on how to fix this?

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Md-chip-list is not a known element
I have been trying to insert some md-chip elements in my project. All I get is "md-chip-list is not a known element".

HTML:

<md-chip-list>
    <md-chip *ngFor="let dependency of externalDependencies" color="primary" class="chip">
        {{dependency.name}}
    </md-chip>
</md-chip-list>
```

<p>I have imported MdChipsModule, as I have seen in other answers:</p>

<pre class="lang-ts prettyprint-override"><code>import { MdChipsModule } from '@angular/material';
</code>```

The code works if I leave out the md-chip-list tag, but the format is not as expected. I am new to Angular Material, so I would really appreciate some help.

答:
The problem was module not included in the imports .

```<code>npm install --save @angular/material
</code>```

In code

```<code>import { MdChipsModule } from '@angular/material';

@NgModule({
  ...
  imports: [MdChipsModule],
  ...
})
export class PizzaPartyAppModule { }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Md-chip-list is not a known element

Body:
I have been trying to insert some md-chip elements in my project. All I get is "md-chip-list is not a known element".

HTML:

<md-chip-list>
    <md-chip *ngFor="let dependency of externalDependencies" color="primary" class="chip">
        {{dependency.name}}
    </md-chip>
</md-chip-list>

I have imported MdChipsModule, as I have seen in other answers:

import { MdChipsModule } from '@angular/material';

The code works if I leave out the md-chip-list tag, but the format is not as expected. I am new to Angular Material, so I would really appreciate some help.

Body:
The problem was module not included in the imports .

npm install --save @angular/material

In code

import { MdChipsModule } from '@angular/material';

@NgModule({
  ...
  imports: [MdChipsModule],
  ...
})
export class PizzaPartyAppModule { }


问:
Method generalization in Scala
I tried to generalize a method to provide a type safe API as follows:

```<code>abstract class AbstractCommand {
  type T = this.type
  def shuffler(s: T => Seq[AbstractCommand])
}

class TestCommand extends AbstractCommand {
  override def shuffler(s: (TestCommand) => Seq[AbstractCommand]): Unit = ??? //error
}
</code>```

I wanted the expected type of the function argument to be the most specific in this hierarchy. But it didn't work.

Is there a way to do something like that in Scala without introducing some helper type parameters?

答:
I'm not entirely sure it fits your need, but I've been able to compile and run the following, let me know if it helps:</p>

```<code>abstract class AbstractCommand {
  def shuffler(s: this.type => Seq[AbstractCommand])
}

class TestCommand extends AbstractCommand {
  override def shuffler(s: (TestCommand.this.type) => Seq[AbstractCommand]): Unit = {
    s(this)
    println("success")
  }
}

new TestCommand().shuffler(_ => Seq.empty) // prints "success"
</code>```

Title: Method generalization in Scala

Body:
I tried to generalize a method to provide a type safe API as follows:

abstract class AbstractCommand {
  type T = this.type
  def shuffler(s: T => Seq[AbstractCommand])
}

class TestCommand extends AbstractCommand {
  override def shuffler(s: (TestCommand) => Seq[AbstractCommand]): Unit = ??? //error
}

I wanted the expected type of the function argument to be the most specific in this hierarchy. But it didn't work.

Is there a way to do something like that in Scala without introducing some helper type parameters?

Body:
I'm not entirely sure it fits your need, but I've been able to compile and run the following, let me know if it helps:

abstract class AbstractCommand {
  def shuffler(s: this.type => Seq[AbstractCommand])
}

class TestCommand extends AbstractCommand {
  override def shuffler(s: (TestCommand.this.type) => Seq[AbstractCommand]): Unit = {
    s(this)
    println("success")
  }
}

new TestCommand().shuffler(_ => Seq.empty) // prints "success"


问:
Symfony 2: How to get route defaults by route name?
Is it possible to retrieve info about a certain route by its name, or get a list of all routes?

I need to be able to fetch the _controller value in defaults for any route, not only the current.

Is this possible and how?

P.S.: I found I could get the path to the routes YAML being used, but reparsing it seems unnecessary and heavy.

答:
As described in my comment above Router::getRouteCollection is really slow and not intended for use in production code.

So if you really need it fast, you have to hack your way through it. Be warned, this is going to be hackish:

Directly accessing the dumped route data

To speed up route matching, Symfony compiles all static routes into one big PHP class file. This file is generated by Symfony\Component\Routing\Generator\Dumper\PhpGeneratorDumper and declares a Symfony\Component\Routing\Generator\UrlGenerator that stores all route definitions in a private static called $declaredRoutes.

$declaredRoutes is an array of compiled route fields indexed by the route's name. Among others (see below) these fields also contain the route defaults.

In order to access $declaredRoutes we have to use a \ReflectionProperty.

So the actual code is:

```<code>// If you don't use a custom Router (e.g., a chained router) you normally
// get the Symfony router from the container using:
// $symfonyRouter = $container->get('router');
// After that, you need to get the UrlGenerator from it.
$generator = $symfonyRouter->getGenerator();

// Now read the dumped routes.
$reflectionProperty = new \ReflectionProperty($generator, 'declaredRoutes');
$reflectionProperty->setAccessible(true);
$dumpedRoutes = $reflectionProperty->getValue($generator);

// The defaults are at index #1 of the route array (see below).
$routeDefaults = $dumpedRoutes['my_route'][1];
</code>```

Fields of the route array

The fields of each route are filled by the above mentioned Symfony\Component\Routing\Generator\Dumper\PhpGeneratorDumper like this:

```<code>// [...]
$compiledRoute = $route->compile();

$properties = array();
$properties[] = $compiledRoute->getVariables();
$properties[] = $route->getDefaults();
$properties[] = $route->getRequirements();
$properties[] = $compiledRoute->getTokens();
$properties[] = $compiledRoute->getHostTokens();
$properties[] = $route->getSchemes();
// [...]
</code>```

So to access its requirements you would use:

```<code>$routeRequirements = $dumpedRoutes['my_route'][2];
</code>```

Bottom line

I've looked through the Symfony manual, the source code, forums, stackoverflow etc. but still wasn't able to find a better way of doing this.

It's brutal, ignores the API, and might break in future updates (although it hasn't changed in the most recent Symfony 4.1: PhpGeneratorDumper on GitHub).

But it's rather short and fast enough to be used in production.

Body:
As described in my comment above Router::getRouteCollection is really slow and not intended for use in production code.

So if you really need it fast, you have to hack your way through it. Be warned, this is going to be hackish:

Directly accessing the dumped route data

To speed up route matching, Symfony compiles all static routes into one big PHP class file. This file is generated by Symfony\Component\Routing\Generator\Dumper\PhpGeneratorDumper and declares a Symfony\Component\Routing\Generator\UrlGenerator that stores all route definitions in a private static called $declaredRoutes.

$declaredRoutes is an array of compiled route fields indexed by the route's name. Among others (see below) these fields also contain the route defaults.

In order to access $declaredRoutes we have to use a \ReflectionProperty.

So the actual code is:

// If you don't use a custom Router (e.g., a chained router) you normally
// get the Symfony router from the container using:
// $symfonyRouter = $container->get('router');
// After that, you need to get the UrlGenerator from it.
$generator = $symfonyRouter->getGenerator();

// Now read the dumped routes.
$reflectionProperty = new \ReflectionProperty($generator, 'declaredRoutes');
$reflectionProperty->setAccessible(true);
$dumpedRoutes = $reflectionProperty->getValue($generator);

// The defaults are at index #1 of the route array (see below).
$routeDefaults = $dumpedRoutes['my_route'][1];

Fields of the route array

The fields of each route are filled by the above mentioned Symfony\Component\Routing\Generator\Dumper\PhpGeneratorDumper like this:

// [...]
$compiledRoute = $route->compile();

$properties = array();
$properties[] = $compiledRoute->getVariables();
$properties[] = $route->getDefaults();
$properties[] = $route->getRequirements();
$properties[] = $compiledRoute->getTokens();
$properties[] = $compiledRoute->getHostTokens();
$properties[] = $route->getSchemes();
// [...]

So to access its requirements you would use:

$routeRequirements = $dumpedRoutes['my_route'][2];

Bottom line

I've looked through the Symfony manual, the source code, forums, stackoverflow etc. but still wasn't able to find a better way of doing this.

It's brutal, ignores the API, and might break in future updates (although it hasn't changed in the most recent Symfony 4.1: PhpGeneratorDumper on GitHub).

But it's rather short and fast enough to be used in production.


问:
The best way to let asp.net fire events and methods automatically -according to a schedule-
Well, I'm sure this is not the first time to see this question. and TBH you can find this question answered on many other websites and blogs -not only here-

But I never saw a complete answer for this question, I mean no one talked about the advantages and the disadvantages. no one shared a real experience.

Although Quartz.NET seems like a good solution but yet, there's no enough reviews or a good comparison between the different ways to achieve such a thing.

As far as I read about it I found this are the possible ways of doing this :

Using a:  Web Service, Windows Appliction, Console Application, Quartz.NET.

Examples of stuff I want to achieve with the scheduled or automatic methods/events are like archiving after a certain period, auto deleting/moving records in the database, setting a property of an object after a certain time, automatically run some methods according to my holiday schedule.

I hope you'd share your experience either with one of those approaches or share a new way of doing this.

答:
I've seen this question asked in at least a 100 ways.  In my experience the best way to go about scheduling is to start with a well thought out n-tier design.  This allows you the flexibility to change out front ends as needed.  For example, a console application to call Method1() which is handled by the windows task scheduler.  I firmly suggest you stick to the windows task scheduler unless requirements drive you to do otherwise.

Timer's are a great idea, in concept.  In execution they can be buggy or simply not function whatsoever depending on the environment (some timers don't work in win services).

As far as a Windows Application, I have never used this for a scheduled task (outside of compiling a console app as a winform app so the console window won't display).  As it displays unecessary UI, confusing the user.

On the DB side you have new options like jobs and Triggers.

In summary, there is no silver bullet.  I suggest you default to a console app and refactor your code so you have a nice design.  Read a design pattern book if you need to.

ContentLicense: CC BY-SA 2.5


问:
Do not allow cross-domain redirection intentionally – Struts2 web application url redirection issue
I have developed a web application using JSP + Struts2 + Hibernate with MYSQL as the back-end. While performing security testing of my application URL redirects to cross – domain websites. For an example, I am running my application in Google chrome browser

localhost:8080/test/welcome.action

It works fine. While entering redirect:http://google.com application allowing to redirect google home page instead of application home page or custom page.

localhost:8080/test/welcome.action?redirect:http://google.com

The above action should not be allowed in security testing, because hackers can get the data(session information) from my application to some other application.

I need solution to stop above redirect to some other URL. Please advise or suggest me how can I prevent to show my application home page instead of cross-domain page.

答:
The best solution to restrict third party URL. The solution to update latest versions of Struts 2 jar files. It will be automatically works correctly. To include Struts 2 and dependency jar file as

commons-fileupload-1.3.2

commons-io-2.4

commons-io-2.4

commons-lang-2.4

commons-lang3-3.4

commons-logging-1.1.3

freemarker-2.3.23

javassist-3.20.0-GA

ognl-3.1.12

struts2-core-2.5.10.1

Refer below link:
https://struts.apache.org/docs/s2-016.html


问:
C# object to array
Using reflection I have an object which I need to cast into an iterable list of items (type unknown, will be object). Using the Watch window I can see my object is an array of some type as it tells me the number of elements and I can explode the tree view to see the elements themselves.

Firstly, I need to check that the object passed is some kind of array (might be List, might be object[], etc). Then I need to iterate through that array. However, I can't do the type conversion.

Here's how I'm using it (abbreviated):

```<code>    private static void Example(object instance, PropertyInfo propInfo)
    {
        object anArray = propInfo.GetValue(instance, null);
        ArrayList myList = anArray as ArrayList;
        foreach (object element in myList)
        {
            // etc
        }
    }
</code>```

I've tried various different casts. The above doesn't raise an exception but mylist is null when anArray actually exists and contains items. The actual instance being saved is a strongly-typed List<> but could take a limited subset of forms if necessary. But the point of the exercise is that this Example() method doesn't know the basic type of the property.

答:
Simply Try This</p>

```<code> string[] arr = ((IEnumerable)yourOjbect).Cast<object>()
                             .Select(x => x.ToString())
                             .ToArray();
</code>```

Title: C# object to array

Body:
Using reflection I have an object which I need to cast into an iterable list of items (type unknown, will be object). Using the Watch window I can see my object is an array of some type as it tells me the number of elements and I can explode the tree view to see the elements themselves.

Firstly, I need to check that the object passed is some kind of array (might be List, might be object[], etc). Then I need to iterate through that array. However, I can't do the type conversion.

Here's how I'm using it (abbreviated):

    private static void Example(object instance, PropertyInfo propInfo)
    {
        object anArray = propInfo.GetValue(instance, null);
        ArrayList myList = anArray as ArrayList;
        foreach (object element in myList)
        {
            // etc
        }
    }

I've tried various different casts. The above doesn't raise an exception but mylist is null when anArray actually exists and contains items. The actual instance being saved is a strongly-typed List<> but could take a limited subset of forms if necessary. But the point of the exercise is that this Example() method doesn't know the basic type of the property.

Body:
Simply Try This

 string[] arr = ((IEnumerable)yourOjbect).Cast<object>()
                             .Select(x => x.ToString())
                             .ToArray();


问:
Bash preserve tab on large text
I have the following echo string:

```<code>echo "Title"
echo -e "\t Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
</code>```

My output is:

```<code>> [mymachine ~]$ example.sh
> Title
>        Lorem Ipsum is simply dummy text of the printing and typesetting
> industry. Lorem Ipsum has been the industry's standard dummy text ever
> since the 1500s, when an unknown printer took a galley of type and
> scrambled it to make a type specimen book.
</code>```

As you can see in this example the text string is too large and console put it in four lines but only the first one preserve tab.

I'm looking for this output:

```<code>> [mymachine ~]$ example.sh
> Title
>        Lorem Ipsum is simply dummy text of the printing and typesetting
>        industry. Lorem Ipsum has been the industry's standard dummy text
>        ever since the 1500s, when an unknown printer took a galley of type
>        and scrambled it to make a type specimen book.
</code>```

Is there any way to make large text string preserve tab for each line on console?

答:
I suspect you are looking for something like fmt:

```<code>echo "Title"
printf "\tLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.\n" \
| fmt
</code>```

Surprisingly, gnu fmt (version 8.25) does not honor $COLUMNS, so you may want to use:

```<code>fmt -w ${COLUMNS:-80}
</code>```

Title: Bash preserve tab on large text

Body:
I have the following echo string:

echo "Title"
echo -e "\t Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."

My output is:

> [mymachine ~]$ example.sh
> Title
>        Lorem Ipsum is simply dummy text of the printing and typesetting
> industry. Lorem Ipsum has been the industry's standard dummy text ever
> since the 1500s, when an unknown printer took a galley of type and
> scrambled it to make a type specimen book.

As you can see in this example the text string is too large and console put it in four lines but only the first one preserve tab.

I'm looking for this output:

> [mymachine ~]$ example.sh
> Title
>        Lorem Ipsum is simply dummy text of the printing and typesetting
>        industry. Lorem Ipsum has been the industry's standard dummy text
>        ever since the 1500s, when an unknown printer took a galley of type
>        and scrambled it to make a type specimen book.

Is there any way to make large text string preserve tab for each line on console?

Body:
I suspect you are looking for something like fmt:

echo "Title"
printf "\tLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.\n" \
| fmt

Surprisingly, gnu fmt (version 8.25) does not honor $COLUMNS, so you may want to use:

fmt -w ${COLUMNS:-80}


问:
How to implement unit tests on IEqualityComparer?
I have a class and a comparer for this class that implements IEqualityComparer:

```<code>class Foo
{
    public int Int { get; set; }
    public string Str { get; set; }

    public Foo(int i, string s)
    {
        Int = i;
        Str = s;
    }

    private sealed class FooEqualityComparer : IEqualityComparer<Foo>
    {
        public bool Equals(Foo x, Foo y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (ReferenceEquals(x, null)) return false;
            if (ReferenceEquals(y, null)) return false;
            if (x.GetType() != y.GetType()) return false;
            return x.Int == y.Int && string.Equals(x.Str, y.Str);
        }

        public int GetHashCode(Foo obj)
        {
            unchecked
            {
                return (obj.Int * 397) ^ (obj.Str != null ? obj.Str.GetHashCode() : 0);
            }
        }
    }

    public static IEqualityComparer<Foo> Comparer { get; } = new FooEqualityComparer();
}
</code>```

The two methods Equals and GetHashCode are used for example in List.Except via an instance of the comparer.

My question is: how to implement properly unit tests on this comparer? I want to detect if someone adds a public property in Foo without modifying the comparer, because in this case the comparer becomes invalid.

If I do something like:

```<code>Assert.That(new Foo(42, "answer"), Is.EqualTo(new Foo(42, "answer")));
</code>```

This cannot detect that a new property was added, and that this property differs in the two objects.

Is there any way to do this?

If it is possible, can we add an attribute to a property to say that this property is not relevant in the comparison?

答:
I guess you can check properties count inside the comparer. Something like this:</p>

```<code>private sealed class FooEqualityComparer : IEqualityComparer<Foo>
{
    private List<bool> comparisonResults = new List<bool>();
    private List<Func<Foo, Foo, bool>> conditions = new List<Func<Foo, Foo, bool>>{
        (x, y) => x.Int == y.Int,
        (x, y) => string.Equals(x.Str, y.Str)
    };
    private int propertiesCount = typeof(Foo)
                .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                //.Where(someLogicToExclde(e.g attribute))
                .Count();

    public bool Equals(Foo x, Foo y)
    {
        if (ReferenceEquals(x, y)) return true;
        if (ReferenceEquals(x, null)) return false;
        if (ReferenceEquals(y, null)) return false;
        if (x.GetType() != y.GetType()) return false;
        //has new property which is not presented in the conditions list and not excluded
        if (conditions.Count() != propertiesCount) return false;

        foreach(var func in conditions)
            if(!func(x, y)) return false;//returns false on first mismatch

        return true;//only if all conditions are satisfied
    }

    public int GetHashCode(Foo obj)
    {
        unchecked
        {
            return (obj.Int * 397) ^ (obj.Str != null ? obj.Str.GetHashCode() : 0);
        }
    }
}
</code>```

Body:
I have a class and a comparer for this class that implements IEqualityComparer:

class Foo
{
    public int Int { get; set; }
    public string Str { get; set; }

    public Foo(int i, string s)
    {
        Int = i;
        Str = s;
    }

    private sealed class FooEqualityComparer : IEqualityComparer<Foo>
    {
        public bool Equals(Foo x, Foo y)
        {
            if (ReferenceEquals(x, y)) return true;
            if (ReferenceEquals(x, null)) return false;
            if (ReferenceEquals(y, null)) return false;
            if (x.GetType() != y.GetType()) return false;
            return x.Int == y.Int && string.Equals(x.Str, y.Str);
        }

        public int GetHashCode(Foo obj)
        {
            unchecked
            {
                return (obj.Int * 397) ^ (obj.Str != null ? obj.Str.GetHashCode() : 0);
            }
        }
    }

    public static IEqualityComparer<Foo> Comparer { get; } = new FooEqualityComparer();
}

The two methods Equals and GetHashCode are used for example in List.Except via an instance of the comparer.

My question is: how to implement properly unit tests on this comparer? I want to detect if someone adds a public property in Foo without modifying the comparer, because in this case the comparer becomes invalid.

If I do something like:

Assert.That(new Foo(42, "answer"), Is.EqualTo(new Foo(42, "answer")));

This cannot detect that a new property was added, and that this property differs in the two objects.

Is there any way to do this?

If it is possible, can we add an attribute to a property to say that this property is not relevant in the comparison?

Body:
I guess you can check properties count inside the comparer. Something like this:

private sealed class FooEqualityComparer : IEqualityComparer<Foo>
{
    private List<bool> comparisonResults = new List<bool>();
    private List<Func<Foo, Foo, bool>> conditions = new List<Func<Foo, Foo, bool>>{
        (x, y) => x.Int == y.Int,
        (x, y) => string.Equals(x.Str, y.Str)
    };
    private int propertiesCount = typeof(Foo)
                .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                //.Where(someLogicToExclde(e.g attribute))
                .Count();

    public bool Equals(Foo x, Foo y)
    {
        if (ReferenceEquals(x, y)) return true;
        if (ReferenceEquals(x, null)) return false;
        if (ReferenceEquals(y, null)) return false;
        if (x.GetType() != y.GetType()) return false;
        //has new property which is not presented in the conditions list and not excluded
        if (conditions.Count() != propertiesCount) return false;

        foreach(var func in conditions)
            if(!func(x, y)) return false;//returns false on first mismatch

        return true;//only if all conditions are satisfied
    }

    public int GetHashCode(Foo obj)
    {
        unchecked
        {
            return (obj.Int * 397) ^ (obj.Str != null ? obj.Str.GetHashCode() : 0);
        }
    }
}


问:
how to stop user after inserting 5 rows into table while userid is same in all 5 rows in codeigniter?
code:

```<code><?php
        if($this->input->post('insert'))
        {
            $data = array(
                'college_name' => $college_name,
                'name' => $_POST['name'],
                'student_id' => $student_id,
                'email' => $_POST['email'],
                'mobile' => $_POST['phone'],
                'city' => $_POST['city'],
                'course' => $_POST['course'],
                'inquiry' => $_POST['inquiry'],
                'query' => $_POST['query'],
                'date' => date('Y-m-d')
                );

            $query = $this->db->insert('college_contact',$data);
            if($query == true)
            {
                echo "<script>alert('your enquiry submitted successfully');</script>";
            }

            $this->db->select('name');
            $this->db->from('college_contact');
            $where = "student_id = '$student_id'";
            $this->db->where($where);
            $query = $this->db->get();
            $result = $query->num_rows();
            if($result > 0)
            {
                echo "you are not allow";
            }
        }
    ?>
</code>```

I am new in codeigniter. In this code I have created form and inserting its value into the database and now I want that if a particular student inserting 5 time data into table then he would be not allowed to insert more data into database. So, How can I do this ? Please help me.

Thank You

答:
I think,

Step:1, First you selected row count in table where userid='$userid', you get current student record count.Not work data inserted to the first.

Step:2, You continue work to insert record or not allow to insert record with condition liked

```<code>if($record > 5){
 echo "not allowed new record";
}else{
 //continue insert query work
 *$query = $this->db->insert('college_contact',$data);*
 echo "your record is inserted";
}
</code>```

I mean not allowed for new record if current student recored is 5 times.So, I first selected his record count and continous condition.Thank.

Body:
code:

<?php
        if($this->input->post('insert'))
        {
            $data = array(
                'college_name' => $college_name,
                'name' => $_POST['name'],
                'student_id' => $student_id,
                'email' => $_POST['email'],
                'mobile' => $_POST['phone'],
                'city' => $_POST['city'],
                'course' => $_POST['course'],
                'inquiry' => $_POST['inquiry'],
                'query' => $_POST['query'],
                'date' => date('Y-m-d')
                );

            $query = $this->db->insert('college_contact',$data);
            if($query == true)
            {
                echo "";
            }

            $this->db->select('name');
            $this->db->from('college_contact');
            $where = "student_id = '$student_id'";
            $this->db->where($where);
            $query = $this->db->get();
            $result = $query->num_rows();
            if($result > 0)
            {
                echo "you are not allow";
            }
        }
    ?>

I am new in codeigniter. In this code I have created form and inserting its value into the database and now I want that if a particular student inserting 5 time data into table then he would be not allowed to insert more data into database. So, How can I do this ? Please help me.

Thank You

Body:
I think,

Step:1, First you selected row count in table where userid='$userid', you get current student record count.Not work data inserted to the first.

Step:2, You continue work to insert record or not allow to insert record with condition liked

if($record > 5){
 echo "not allowed new record";
}else{
 //continue insert query work
 *$query = $this->db->insert('college_contact',$data);*
 echo "your record is inserted";
}

I mean not allowed for new record if current student recored is 5 times.So, I first selected his record count and continous condition.Thank.


问:
Combining two generators to a single arbitrary in FsCheck
I have a property I want to test on a collection of Stuff, where one of the Stuff satisfies a certain property. I have a way to generate a Stuff satisfying the property, and a way to generate a Stuff that doesn't.

Today, I'm doing something like this (yes, I'm using FsCheck in C#):

```<code>IEnumerable<Stuff> GetStuffCollection(int input)
{
    yield return GenerateStuffSatisfyingProperty(input);
    yield return GenerateStuffNotSatisfyingProperty(input);
}

[Fact]
public void PropertyForCollectionHolds()
{
    Prop.ForAll(Arb.Choose(1,5), input =>
    {
        var collection = GetStuffCollection(input);

        return collection.SatisfiesProperty();
    }).VerboseCheckThrowOnFailure();
}
</code>```

but this hard-codes the ordering, i.e. which Stuff in the collection that satisfies the property; I'd like to arbitrate that as well.

One way to do it would be to nest Prop.ForAll calls; an outer one that generates something that determines the ordering, and an inner one which is the one I have above but passing a parameter controlling ordering to the collection builder:

```<code>IEnumerable<Stuff> GetStuffCollection(int input, bool first)
{
    if (first)
    {
        yield return GenerateStuffSatisfyingProperty(input);
        yield return GenerateStuffNotSatisfyingProperty(input);
    }
    else
    {
        yield return GenerateStuffNotSatisfyingProperty(input);
        yield return GenerateStuffSatisfyingProperty(input);
    }
}

[Fact]
public void PropertyForCollectionHolds()
{
    Prop.ForAll(Arb.Default.Bool(), first =>
        Prop.ForAll(Arb.Choose(1,5), input =>
        {
            var collection = GetStuffCollection(input, first);

            return collection.SatisfiesProperty();
        }).VerboseCheckThrowOnFailure()
    ).VerboseCheckThrowOnFailure();
}
</code>```

But this feels klunky and convoluted. Is there a simpler and/or more idiomatic way to achieve the same thing, i.e. testing the cartesian product of the output of two arbitraries?

答:
You can use Gen.Shuffle to generate sequences in different orders:

```<code>var gen = from input in Gen.Choose(1, 5)
          let sc = GetStuffCollection(input)
          from shuffled in Gen.Shuffle(sc)
          select shuffled
</code>```

then

```<code>Prop.ForAll(gen, collection => { ... })
</code>```

Body:
I have a property I want to test on a collection of Stuff, where one of the Stuff satisfies a certain property. I have a way to generate a Stuff satisfying the property, and a way to generate a Stuff that doesn't.

Today, I'm doing something like this (yes, I'm using FsCheck in C#):

IEnumerable<Stuff> GetStuffCollection(int input)
{
    yield return GenerateStuffSatisfyingProperty(input);
    yield return GenerateStuffNotSatisfyingProperty(input);
}

[Fact]
public void PropertyForCollectionHolds()
{
    Prop.ForAll(Arb.Choose(1,5), input =>
    {
        var collection = GetStuffCollection(input);

        return collection.SatisfiesProperty();
    }).VerboseCheckThrowOnFailure();
}

but this hard-codes the ordering, i.e. which Stuff in the collection that satisfies the property; I'd like to arbitrate that as well.

One way to do it would be to nest Prop.ForAll calls; an outer one that generates something that determines the ordering, and an inner one which is the one I have above but passing a parameter controlling ordering to the collection builder:

IEnumerable<Stuff> GetStuffCollection(int input, bool first)
{
    if (first)
    {
        yield return GenerateStuffSatisfyingProperty(input);
        yield return GenerateStuffNotSatisfyingProperty(input);
    }
    else
    {
        yield return GenerateStuffNotSatisfyingProperty(input);
        yield return GenerateStuffSatisfyingProperty(input);
    }
}

[Fact]
public void PropertyForCollectionHolds()
{
    Prop.ForAll(Arb.Default.Bool(), first =>
        Prop.ForAll(Arb.Choose(1,5), input =>
        {
            var collection = GetStuffCollection(input, first);

            return collection.SatisfiesProperty();
        }).VerboseCheckThrowOnFailure()
    ).VerboseCheckThrowOnFailure();
}

But this feels klunky and convoluted. Is there a simpler and/or more idiomatic way to achieve the same thing, i.e. testing the cartesian product of the output of two arbitraries?

Body:
You can use Gen.Shuffle to generate sequences in different orders:

var gen = from input in Gen.Choose(1, 5)
          let sc = GetStuffCollection(input)
          from shuffled in Gen.Shuffle(sc)
          select shuffled

then

Prop.ForAll(gen, collection => { ... })


问:
How can I combine 2 django query into one with object limit
I have multiple type of obj_type in database

What i am currently doing is

```<code>a =  Search_model.objects.filter(obj_type="mall", city=city)[:2]

b = Search_model.objects.filter(obj_type="store", city=city)[:2]
</code>```

and then combine a and b so it gives me:-

```<code>[{"name":"a","obj_type":"mall"}, {"name":"b","obj_type":"mall"}{"name":"c","obj_type":"store"}, {"name":"d","obj_type":"store"}]
</code>```

what i want is something like this

```<code>    if not search_in == None:
        search_in_queries = [q for q in re.split(",", search_in) if q]

        for query in search_in_queries:
            search_in_dict.append(('obj_type__contains', query))

        search_in_query = [Q(x) for x in search_in_dict]
    else:
        search_in_query = None
</code>```

such that value of search_in is "mall,store"

```<code>a =  Search_model.objects.filter(reduce(operator.or_, search_in_query), city=city)[:4]
</code>```

but it gives me all mall type obj

```<code>[{"name":"a","obj_type":"mall"}, {"name":"b","obj_type":"mall"}{"name":"c","obj_type":"mall"}, {"name":"d","obj_type":"mall"}]
</code>```

so my query is how can i achieve the above result in one query

答:
Have you tried searching with a list user __in. So construct a list of the things you want to filter.

```<code>Search_model.objects.filter(obj_type__in=["mall", "store"], city=city)
</code>```

See: https://docs.djangoproject.com/en/1.11/ref/models/querysets/#in

Body:
I have multiple type of obj_type in database

What i am currently doing is

a =  Search_model.objects.filter(obj_type="mall", city=city)[:2]

b = Search_model.objects.filter(obj_type="store", city=city)[:2]

and then combine a and b so it gives me:-

[{"name":"a","obj_type":"mall"}, {"name":"b","obj_type":"mall"}{"name":"c","obj_type":"store"}, {"name":"d","obj_type":"store"}]

what i want is something like this

    if not search_in == None:
        search_in_queries = [q for q in re.split(",", search_in) if q]

        for query in search_in_queries:
            search_in_dict.append(('obj_type__contains', query))

        search_in_query = [Q(x) for x in search_in_dict]
    else:
        search_in_query = None

such that value of search_in is "mall,store"

a =  Search_model.objects.filter(reduce(operator.or_, search_in_query), city=city)[:4]

but it gives me all mall type obj

[{"name":"a","obj_type":"mall"}, {"name":"b","obj_type":"mall"}{"name":"c","obj_type":"mall"}, {"name":"d","obj_type":"mall"}]

so my query is how can i achieve the above result in one query

Body:
Have you tried searching with a list user __in. So construct a list of the things you want to filter.

Search_model.objects.filter(obj_type__in=["mall", "store"], city=city)

See: https://docs.djangoproject.com/en/1.11/ref/models/querysets/#in


问:
How to get loaded web page title in Android WebView?
I'm using a WebView in my application, I have a requirement to change the app title based on the page user is on. How can I do this in Android WebView?

I did this in iphone by following line

```<code>self.title = [webPage stringByEvaluatingJavaScriptFromString:@"document.title"]

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Adds Progrss bar Support
        this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.webview );

        // Makes Progress bar Visible
        getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);

        mWebView = (WebView) findViewById( R.id.webview ); //This is the id you gave
        //to the WebView in the main.xml
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setSupportZoom(true);       //Zoom Control on web (You don't need this
        //if ROM supports Multi-Touch
        mWebView.getSettings().setBuiltInZoomControls(true); //Enable Multitouch if supported by ROM

        // Load URL
        Bundle b = getIntent().getExtras();
        String url = b.getString("url");
        Log.d(TAG, "url " + url);
        mWebView.loadUrl(url);

        // Sets the Chrome Client, and defines the onProgressChanged
        // This makes the Progress bar be updated.
        mWebView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress){
                //Make the bar disappear after URL is loaded, and changes string to Loading...
                myActivity.setTitle("Loading...");
                myActivity.setProgress(progress * 100); //Make the bar disappear after URL is loaded

                // Return the app name after finish loading
                if(progress == 100)
                    myActivity.setTitle(R.string.app_name);
            }
        });

        mWebView.setWebViewClient(new WebViewClient(){

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
                // return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onLoadResource(view, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                ImageView logoImageView = (ImageView)findViewById(R.id.logoimage);
                logoImageView.setVisibility(View.GONE);
                Log.d(TAG, "view.getTitle() " + view.getTitle());
                myActivity.setTitle(view.getTitle());
            }

        });

    }
</code>```

答:
```<code>private WebViewClient mWvClient = new WebViewClient() {

        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {

            String title = view.getTitle();//getTitle
            super.doUpdateVisitedHistory(view, url, isReload);
        }
    }
</code>```

Body:
I'm using a WebView in my application, I have a requirement to change the app title based on the page user is on. How can I do this in Android WebView?

I did this in iphone by following line

self.title = [webPage stringByEvaluatingJavaScriptFromString:@"document.title"]

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Adds Progrss bar Support
        this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.webview );

        // Makes Progress bar Visible
        getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);

        mWebView = (WebView) findViewById( R.id.webview ); //This is the id you gave
        //to the WebView in the main.xml
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setSupportZoom(true);       //Zoom Control on web (You don't need this
        //if ROM supports Multi-Touch
        mWebView.getSettings().setBuiltInZoomControls(true); //Enable Multitouch if supported by ROM

        // Load URL
        Bundle b = getIntent().getExtras();
        String url = b.getString("url");
        Log.d(TAG, "url " + url);
        mWebView.loadUrl(url);

        // Sets the Chrome Client, and defines the onProgressChanged
        // This makes the Progress bar be updated.
        mWebView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress){
                //Make the bar disappear after URL is loaded, and changes string to Loading...
                myActivity.setTitle("Loading...");
                myActivity.setProgress(progress * 100); //Make the bar disappear after URL is loaded

                // Return the app name after finish loading
                if(progress == 100)
                    myActivity.setTitle(R.string.app_name);
            }
        });

        mWebView.setWebViewClient(new WebViewClient(){

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
                // return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onLoadResource(view, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                ImageView logoImageView = (ImageView)findViewById(R.id.logoimage);
                logoImageView.setVisibility(View.GONE);
                Log.d(TAG, "view.getTitle() " + view.getTitle());
                myActivity.setTitle(view.getTitle());
            }

        });

    }


问:
Python socket sends faster than receiver
So, I have a server sending responses to a client with the socket.send() method. From time to time testing the code on localhost, the socket.recv() method, used by the client to receive the server responses, gets two different messages in one, when the server uses socket.send() twice in a row.
For example:
Server:

```<code>from socket import *

serverSocket = socket(AF_INET, SOCK_STREAM)
serverPort = 13005
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
connection_socket, client_ip = serverSocket.accept()
connection_socket.send('Message one')
connection_socket.send('Message two')
</code>```

Client:

```<code>from socket import *

serverName = 'localhost'
serverPort = 13005
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
print clientSocket.recv(1024)
print clientSocket.recv(1024)
</code>```

The result from running the client, at random times, is

```<code>Message oneMessage two
</code>```

unless I put a sleep(0.1) between the two send(). Is there a way to avoid using sleep? Do I need to put the exact number of bytes to receive in the recv() method?

答:
TCP is a stream oriented protocol and don't send message one by one. A easy way to split the messages that you can set a split string in the end of message like \r\n

Example:

Client:

```<code>#!/usr/bin/env python

import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 13005

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send('Message one\r\n')
s.send('Message two\r\n')
s.close()
</code>```

Server:

```<code>#!/usr/bin/env python

import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 13005
BUFFER_SIZE = 20  # Normally 1024, but we want test

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)

conn, addr = s.accept()
data = ''
while 1:
    data += conn.recv(BUFFER_SIZE)
    if not data: break
    if not data.endswith('\r\n'):
        continue
    lines = data.split('\r\n')
    for line in lines:
        print line
    data = ''
conn.close()
</code>```

If your message is complicated and long, you can see: Python Socket Receive Large Amount of Data

Body:
So, I have a server sending responses to a client with the socket.send() method. From time to time testing the code on localhost, the socket.recv() method, used by the client to receive the server responses, gets two different messages in one, when the server uses socket.send() twice in a row.
For example:
Server:

from socket import *

serverSocket = socket(AF_INET, SOCK_STREAM)
serverPort = 13005
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
connection_socket, client_ip = serverSocket.accept()
connection_socket.send('Message one')
connection_socket.send('Message two')

Client:

from socket import *

serverName = 'localhost'
serverPort = 13005
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
print clientSocket.recv(1024)
print clientSocket.recv(1024)

The result from running the client, at random times, is

Message oneMessage two

unless I put a sleep(0.1) between the two send(). Is there a way to avoid using sleep? Do I need to put the exact number of bytes to receive in the recv() method?

Body:
TCP is a stream oriented protocol and don't send message one by one. A easy way to split the messages that you can set a split string in the end of message like \r\n

Example:

Client:

#!/usr/bin/env python

import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 13005

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send('Message one\r\n')
s.send('Message two\r\n')
s.close()

Server:

#!/usr/bin/env python

import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 13005
BUFFER_SIZE = 20  # Normally 1024, but we want test

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)

conn, addr = s.accept()
data = ''
while 1:
    data += conn.recv(BUFFER_SIZE)
    if not data: break
    if not data.endswith('\r\n'):
        continue
    lines = data.split('\r\n')
    for line in lines:
        print line
    data = ''
conn.close()

If your message is complicated and long, you can see: Python Socket Receive Large Amount of Data


问:
How to compare to List<WebElement> in webdriver?
I am trying to automate Dual list Box testing. I want to compare the selected values(left side) vs moved values (into right side list). Here is the code.

```<code>Select allFromListData = new Select(listData);
    // values selection
    allFromListData.selectByIndex(0);
    allFromListData.selectByVisibleText("Helena");
    List<WebElement> selectedList=allFromListData.getAllSelectedOptions();
    //clicking on add button

    for(int i=0;i<selectedList.size();i++)
        System.out.println(selectedList.get(i).getText());
    WebElement addButton = driver.findElement(By.xpath("//*[@id='pickList']/div/div[2]/button[1]"));
    addButton.click();

    //Verification of selected content...
    WebElement toListData=driver.findElement(By.xpath("//*[@id='pickList']/div/div[3]/select"));
    Select allToListData = new Select(toListData);
    List<WebElement> movedData=allToListData.getOptions();
</code>```

Question is how to compare the data between List<WebElement> selectedList=allFromListData.getAllSelectedOptions(); and List<WebElement> movedData=allToListData.getOptions();

答:
You can try intersection() and subtract() methods from CollectionUtils( java.lang.object).

```<code>subtract(Collection a, Collection b)
</code>```

Returns a new Collection containing a - b.

```<code>intersection(Collection a, Collection b)
</code>```

Returns a Collection containing the intersection of the given Collections.

Body:
I am trying to automate Dual list Box testing. I want to compare the selected values(left side) vs moved values (into right side list). Here is the code.

Select allFromListData = new Select(listData);
    // values selection
    allFromListData.selectByIndex(0);
    allFromListData.selectByVisibleText("Helena");
    List<WebElement> selectedList=allFromListData.getAllSelectedOptions();
    //clicking on add button

    for(int i=0;i<selectedList.size();i++)
        System.out.println(selectedList.get(i).getText());
    WebElement addButton = driver.findElement(By.xpath("//*[@id='pickList']/div/div[2]/button[1]"));
    addButton.click();

    //Verification of selected content...
    WebElement toListData=driver.findElement(By.xpath("//*[@id='pickList']/div/div[3]/select"));
    Select allToListData = new Select(toListData);
    List<WebElement> movedData=allToListData.getOptions();

Question is how to compare the data between List<WebElement> selectedList=allFromListData.getAllSelectedOptions(); and List<WebElement> movedData=allToListData.getOptions();

Body:
You can try intersection() and subtract() methods from CollectionUtils( java.lang.object).

subtract(Collection a, Collection b)

Returns a new Collection containing a - b.

intersection(Collection a, Collection b)

Returns a Collection containing the intersection of the given Collections.


问:
Using Applescript To Adjust Colors In Preview
I'm very new to Applescripts.

My Goal: Automatically open (in one window/instance) all of the pictures located within a directory using the "Preview" application, access the "Adjust Colors" toolbox [Tools > Adjust Colors...], click the "Auto Level" button said toolbox, proceed to the next image and click "Auto Level", etc. , and Save All.

I've been using the Xcode "Accessibility Inspector" utility in an attempt to get the names and classes of these buttons and such, but I am also new to using the Accessibility Inspector, so I'm mostly playing at this point.

So far, this is my hodgepodge of an Applescript; Having done some crude assembling of some snippets of others' Applescripts, I've been able to open the pictures with only partial repeatable success:

```<code>tell application "Finder"
    activate
    open folder "Import" of folder "Shared" of folder "Users" of startup disk
    set pics to select every item of folder "Import" of folder "Shared" of folder "Users" of startup disk
    open pics
end tell
tell application "System Events" to tell Application "Preview"
    click menu item "Adjust Color..." of menu bar item "Tools" of window 1
end tell
</code>```

I understand that there are just so....so many things that would make your grandmother cringe about this code, but I was hoping to break it down...

I am not sure how to open all of the images in one window. The [open pics] line seems to open each file separately, even though they've all been selected.

Applescripts doesn't seem to like the fact that I'm telling an Application to click a menu item. But I don't think Preview constitutes a "Process" (i.e. changing "tell application"... to "tell process".. allows the code to compile, but the process "Preview" doesn't exist... oi!

Looking forward to the point when I can start telling it to click the "Auto Level" button in the toolbox, what might be the class (?) of the toolbox? I see "floating window" in the Accessibility Inspector, but errors have been thrown at my attempts...

Thank you for any insight, resources, or pep talks...

答:
Building strongly on vadian's answer, I'd delete the activate application "Preview" line. For me it interferes when first starting up Preview and when opening picture after picture. Make sure, preview is your standard application for opening picture files and it shoud work fine. Also for other ppl interested, I worked out on how to manipulate the sliders. When working with pictures that have a large file size, preview seems to become unstable so working with delays can help. Following is the altered vode from vadian for a folder on your desktop, containing pictures. Just change *Username* and create a Folder (here named APPLESCRIPT) on your desktop:

```<code>tell application "Finder"
    set desktopFolder to folder "Macintosh HD:Users:*Username*:Desktop"
    set allImages to every item of folder "APPLESCRIPT" of desktopFolder
end tell

set adjustColorWindow to missing value
repeat with anImage in allImages
    delay 5.0
    tell application "Finder" to open anImage
    -- activate application "Preview"
    tell application "System Events"
        tell process "Preview"
            repeat until exists (1st window whose value of attribute "AXSubRole" is "AXStandardWindow")
                delay 1.0
            end repeat
            set documentWindow to (name of 1st window whose value of attribute "AXSubRole" is "AXStandardWindow")
            if adjustColorWindow is missing value then
                click menu item "Adjust Color ..." of menu 1 of menu bar item "Tools" of menu bar 1
                repeat until exists (1st window whose title starts with "Adjust Color")
                    delay 1.0
                end repeat
            end if
            set adjustColorWindow to (1st window whose title starts with "Adjust Color")
            tell adjustColorWindow

                -- click button "Auto Levels"
                -- get value of slider x
                -- slider 1: exposure (-2.0; 2.0)
                -- slider 2: contrast (-1.0; 1.0)
                -- slider 3: highlights (-1.0; -0.3)
                -- slider 4: shadows (0.0; 1.0)
                -- slider 5: saturation (0.0; 2.0)
                -- slider 6: temperature (3500.0; 6500.0)
                -- slider 7: hue (-150.0; 150.0)
                -- slider 8: eepia (0.0; 1.0)
                -- slider 9: sharpness (-1.0; 1.0)

                set value of slider 1 to 2.0
                delay 3.0

                set value of slider 6 to 3500.0
                delay 3.0

                set value of slider 9 to 1.0
                delay 3.0

                set value of slider 2 to -0.95
                delay 3.0

            end tell
        end tell

        tell application "Preview" to close every window

    end tell
end repeat
tell application "System Events" to quit application "Preview"
</code>```

Body:
I'm very new to Applescripts.

My Goal: Automatically open (in one window/instance) all of the pictures located within a directory using the "Preview" application, access the "Adjust Colors" toolbox [Tools > Adjust Colors...], click the "Auto Level" button said toolbox, proceed to the next image and click "Auto Level", etc. , and Save All.

I've been using the Xcode "Accessibility Inspector" utility in an attempt to get the names and classes of these buttons and such, but I am also new to using the Accessibility Inspector, so I'm mostly playing at this point.

So far, this is my hodgepodge of an Applescript; Having done some crude assembling of some snippets of others' Applescripts, I've been able to open the pictures with only partial repeatable success:

tell application "Finder"
    activate
    open folder "Import" of folder "Shared" of folder "Users" of startup disk
    set pics to select every item of folder "Import" of folder "Shared" of folder "Users" of startup disk
    open pics
end tell
tell application "System Events" to tell Application "Preview"
    click menu item "Adjust Color..." of menu bar item "Tools" of window 1
end tell

I understand that there are just so....so many things that would make your grandmother cringe about this code, but I was hoping to break it down...

I am not sure how to open all of the images in one window. The [open pics] line seems to open each file separately, even though they've all been selected.

Applescripts doesn't seem to like the fact that I'm telling an Application to click a menu item. But I don't think Preview constitutes a "Process" (i.e. changing "tell application"... to "tell process".. allows the code to compile, but the process "Preview" doesn't exist... oi!

Looking forward to the point when I can start telling it to click the "Auto Level" button in the toolbox, what might be the class (?) of the toolbox? I see "floating window" in the Accessibility Inspector, but errors have been thrown at my attempts...

Thank you for any insight, resources, or pep talks...

Body:
Building strongly on vadian's answer, I'd delete the activate application "Preview" line. For me it interferes when first starting up Preview and when opening picture after picture. Make sure, preview is your standard application for opening picture files and it shoud work fine. Also for other ppl interested, I worked out on how to manipulate the sliders. When working with pictures that have a large file size, preview seems to become unstable so working with delays can help. Following is the altered vode from vadian for a folder on your desktop, containing pictures. Just change *Username* and create a Folder (here named APPLESCRIPT) on your desktop:

tell application "Finder"
    set desktopFolder to folder "Macintosh HD:Users:*Username*:Desktop"
    set allImages to every item of folder "APPLESCRIPT" of desktopFolder
end tell

set adjustColorWindow to missing value
repeat with anImage in allImages
    delay 5.0
    tell application "Finder" to open anImage
    -- activate application "Preview"
    tell application "System Events"
        tell process "Preview"
            repeat until exists (1st window whose value of attribute "AXSubRole" is "AXStandardWindow")
                delay 1.0
            end repeat
            set documentWindow to (name of 1st window whose value of attribute "AXSubRole" is "AXStandardWindow")
            if adjustColorWindow is missing value then
                click menu item "Adjust Color ..." of menu 1 of menu bar item "Tools" of menu bar 1
                repeat until exists (1st window whose title starts with "Adjust Color")
                    delay 1.0
                end repeat
            end if
            set adjustColorWindow to (1st window whose title starts with "Adjust Color")
            tell adjustColorWindow

                -- click button "Auto Levels"
                -- get value of slider x
                -- slider 1: exposure (-2.0; 2.0)
                -- slider 2: contrast (-1.0; 1.0)
                -- slider 3: highlights (-1.0; -0.3)
                -- slider 4: shadows (0.0; 1.0)
                -- slider 5: saturation (0.0; 2.0)
                -- slider 6: temperature (3500.0; 6500.0)
                -- slider 7: hue (-150.0; 150.0)
                -- slider 8: eepia (0.0; 1.0)
                -- slider 9: sharpness (-1.0; 1.0)

                set value of slider 1 to 2.0
                delay 3.0

                set value of slider 6 to 3500.0
                delay 3.0

                set value of slider 9 to 1.0
                delay 3.0

                set value of slider 2 to -0.95
                delay 3.0

            end tell
        end tell

        tell application "Preview" to close every window

    end tell
end repeat
tell application "System Events" to quit application "Preview"


问:
Setting Caret Position to End of Multiple Textboxes
I'm trying to set the caret of a number of TextBoxes to the end of the text one after another after all have been populated with text. I understand that there is a number of ways of setting this but all appear to require the TextBox to be in Focus. My issue is that doing this all at once means that only the last TextBox is affected. I believe this is because the UI is only affected all at once so only one Focus is applied. Any workaround to set multiple caret positionings at once?

```<code>        txtImagesFolder.Select(txtImagesFolder.Text.Length, 0);
        txtImagesFolder.Focus();

        txtTextFolder.Select(txtTextFolder.Text.Length, 0);
        txtTextFolder.Focus();
</code>```

答:
You could scroll each TextBox to the right like this:

```<code>txtImagesFolder.CaretIndex = txtImagesFolder.Text.Length - 1;
var rect = t1.GetRectFromCharacterIndex(txtImagesFolder.CaretIndex);
txtImagesFolder.ScrollToHorizontalOffset(rect.Right);
</code>```

Create a method and call it for each TextBox:

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
    ScrollToRight(txtImagesFolder);
    ScrollToRight(txtTextFolder);
}

private void ScrollToRight(TextBox textBox)
{
    textBox.CaretIndex = textBox.Text.Length - 1;
    var rect = textBox.GetRectFromCharacterIndex(textBox.CaretIndex);
    textBox.ScrollToHorizontalOffset(rect.Right);
}
</code>```

This appears to work for me. However, a follow on issue I'm having is that just before I call my ScrollToRights I'm uncollapsing a StackPanel that holds them. This means that the rect does not receive any co ordinates. I tried calling this from the IsVisibleChanged event of the StackPanel but this of course also occurs before the UI update. Any thoughts on a workaround?

Use the dispatcher:

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
    sp.Visibility = Visibility.Visible;

    Dispatcher.BeginInvoke(new Action(() =>
    {
        ScrollToRight(txtImagesFolder);
        ScrollToRight(txtTextFolder);
    }), System.Windows.Threading.DispatcherPriority.Background);
}
</code>```

Body:
I'm trying to set the caret of a number of TextBoxes to the end of the text one after another after all have been populated with text. I understand that there is a number of ways of setting this but all appear to require the TextBox to be in Focus. My issue is that doing this all at once means that only the last TextBox is affected. I believe this is because the UI is only affected all at once so only one Focus is applied. Any workaround to set multiple caret positionings at once?

        txtImagesFolder.Select(txtImagesFolder.Text.Length, 0);
        txtImagesFolder.Focus();

        txtTextFolder.Select(txtTextFolder.Text.Length, 0);
        txtTextFolder.Focus();

Body:
You could scroll each TextBox to the right like this:

txtImagesFolder.CaretIndex = txtImagesFolder.Text.Length - 1;
var rect = t1.GetRectFromCharacterIndex(txtImagesFolder.CaretIndex);
txtImagesFolder.ScrollToHorizontalOffset(rect.Right);

Create a method and call it for each TextBox:

private void Button_Click(object sender, RoutedEventArgs e)
{
    ScrollToRight(txtImagesFolder);
    ScrollToRight(txtTextFolder);
}

private void ScrollToRight(TextBox textBox)
{
    textBox.CaretIndex = textBox.Text.Length - 1;
    var rect = textBox.GetRectFromCharacterIndex(textBox.CaretIndex);
    textBox.ScrollToHorizontalOffset(rect.Right);
}

This appears to work for me. However, a follow on issue I'm having is that just before I call my ScrollToRights I'm uncollapsing a StackPanel that holds them. This means that the rect does not receive any co ordinates. I tried calling this from the IsVisibleChanged event of the StackPanel but this of course also occurs before the UI update. Any thoughts on a workaround?

Use the dispatcher:

private void Button_Click(object sender, RoutedEventArgs e)
{
    sp.Visibility = Visibility.Visible;

    Dispatcher.BeginInvoke(new Action(() =>
    {
        ScrollToRight(txtImagesFolder);
        ScrollToRight(txtTextFolder);
    }), System.Windows.Threading.DispatcherPriority.Background);
}


问:
login and signup tab does not work xml
I am trying to create login and signup tab on the same page. so everytime I press signup on the login screen, it change to the signup screen as expected, so does the signup screen. On the signup screen, everytime I press the login tab, it works too. But on the login screen, everytime I press login, it goes to signup screen but I want it to stay on login screen. The weird thing is that everytime I press signup, it stays on the signup screen . Can anyone help? any help would be appreciated.

Android classes

SignUpScreen.java

```<code> final Intent i = new Intent(SignUpScreen.this, LoginScreen.class);
    TextView b = (TextView) findViewById(R.id.text1);

    b.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {

            setContentView(R.layout.login_screen);
            SignUpScreen.this.startActivity(i);
        }
    });
</code>```

my LoginScreen.java

```<code>final Intent i = new Intent(LoginScreen.this,SignUpScreen.class);
    TextView c = (TextView) findViewById(R.id.text4);

    c.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {

            setContentView(R.layout.sign_up_screen);
            LoginScreen.this.startActivity(i);
        }
    });
</code>```

答:
You must call setContentView in onCreate method and do something like this :</p>

```<code>protected void onCreate(Bundle savedInstanceState){

   if(forLoginScreen) {
     setContentView(R.layout.login_screen);
   }else {
    setContentView(R.layout.sign_up_screen);
   }

}
</code>```

Title: login and signup tab does not work xml

Body:
I am trying to create login and signup tab on the same page. so everytime I press signup on the login screen, it change to the signup screen as expected, so does the signup screen. On the signup screen, everytime I press the login tab, it works too. But on the login screen, everytime I press login, it goes to signup screen but I want it to stay on login screen. The weird thing is that everytime I press signup, it stays on the signup screen . Can anyone help? any help would be appreciated.

Android classes

SignUpScreen.java

 final Intent i = new Intent(SignUpScreen.this, LoginScreen.class);
    TextView b = (TextView) findViewById(R.id.text1);

    b.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {

            setContentView(R.layout.login_screen);
            SignUpScreen.this.startActivity(i);
        }
    });

my LoginScreen.java

final Intent i = new Intent(LoginScreen.this,SignUpScreen.class);
    TextView c = (TextView) findViewById(R.id.text4);

    c.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {

            setContentView(R.layout.sign_up_screen);
            LoginScreen.this.startActivity(i);
        }
    });

Body:
You must call setContentView in onCreate method and do something like this :

protected void onCreate(Bundle savedInstanceState){

   if(forLoginScreen) {
     setContentView(R.layout.login_screen);
   }else {
    setContentView(R.layout.sign_up_screen);
   }

}


问:
UIDeviceRGBColor isEqualToString:]: unrecognized selector
Can someone tell me what exactly is that about?
I have table and inside the tableCell I have a pickerview and some textfields in other cells.
When i'm scrolling the table up and down 8-10 times app crashes and gives me this error:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIDeviceRGBColor isEqualToString:]: unrecognized selector sent to instance 0x5834850'

答:
Short answer: it is trying to call -isEqualToString: on an instance of UIDeviceRGBColor, which is doesn't respond to it.

Long answer: you're either asking for the wrong object at some point, or quite possibly trying to access an object that has been released, but who's pointer has not been set to nil. Sometimes when this happens you'll get a straight crash as the memory in the new location isn't a proper object. Sometimes a new object takes its place. The best way to find out is to turn on Zombies.

This is a good overview of how to use Zombies: http://iosdevelopertips.com/debugging/tracking-down-exc_bad_access-errors-with-nszombieenabled.html

You may start seeing messages saying "-[NSCFString isEqualToString:] message sent to deallocated instance". If so then this is a memory management problem and you need to double check your retains & releases. If you don't get this message then you are likely calling the wrong method and so getting the wrong object back.


问:
React Router v4 :param conflicting with 404
I'm currently trying to wrap my head around react router. At the moment I'm trying to accomplish a router that looks something like this:

```<code><BrowserRouter>
    <div>
        <Switch>
            <Route exact path="/" component={App} />
            <Route exact path="/:pageName" component={Page} />
            <Route component={NotFound}/>
        </Switch>
    </div>
</BrowserRouter>
</code>```

The idea is that the Page component will use the :pageName to render the correct title and content. However, if the pageName doesn't exist, it should render the notFound (404) page.

At the moment the 404 page will never render, as all urls matches the Page route.

What is the conventional way to check if the pageName exist, and only match the Page component in cases where it does? should I set up the 's dynamically, or should the Page component check and redirect? How should I think about this?

答:
If you would like that parameter pageName lies within certain set of predefined values, I would just list each of those values as separate route:

```<code><BrowserRouter>
    <div>
        <Switch>
            <Route exact path="/" component={App} />
            <Route exact path="/page1" component={Page} />
            <Route exact path="/page2" component={Page} />
            <Route exact path="/pagexyz" component={Page} />
            <Route path="*" component={NotFound}/>
        </Switch>
    </div>
</BrowserRouter>
</code>```

If you insist to have just one route for all pages, according to this article you can use regexp to specify path so ou can write regexp that will accept only page names you will have and reject others.

If set of existing pages is not predefined but contained in array I would use map to generate routes like in:

```<code>pageNames.map((name) => (<Route exact path={'/'+name} component={Page} />
</code>```

Body:
I'm currently trying to wrap my head around react router. At the moment I'm trying to accomplish a router that looks something like this:

<BrowserRouter>

        <Switch>
            <Route exact path="/" component={App} />
            <Route exact path="/:pageName" component={Page} />
            <Route component={NotFound}/>
        </Switch>

</BrowserRouter>

The idea is that the Page component will use the :pageName to render the correct title and content. However, if the pageName doesn't exist, it should render the notFound (404) page.

At the moment the 404 page will never render, as all urls matches the Page route.

What is the conventional way to check if the pageName exist, and only match the Page component in cases where it does? should I set up the 's dynamically, or should the Page component check and redirect? How should I think about this?

Body:
If you would like that parameter pageName lies within certain set of predefined values, I would just list each of those values as separate route:

<BrowserRouter>
    <div>
        <Switch>
            <Route exact path="/" component={App} />
            <Route exact path="/page1" component={Page} />
            <Route exact path="/page2" component={Page} />
            <Route exact path="/pagexyz" component={Page} />
            <Route path="*" component={NotFound}/>
        </Switch>
    </div>
</BrowserRouter>

If you insist to have just one route for all pages, according to this article you can use regexp to specify path so ou can write regexp that will accept only page names you will have and reject others.

If set of existing pages is not predefined but contained in array I would use map to generate routes like in:

pageNames.map((name) => (<Route exact path={'/'+name} component={Page} />


问:
Use external javaScript library in angular application
I have an angular 4 application and I have a javascript component that I created in a javascript file : timeline.js. The javascript component works well but I want to use it with angular 4. So, I put my js file in the folder assets/js/timeline.js.

In the file index.html, I call my js file with  and in app.component.ts, I have :

```<code>var timeline = new Timeline("timelineVisualization")
</code>```

So, normally, the timeline is created in the div which has id="timelineVisualization".

But it doesn't work  and I have an error on the new Timeline : Cannot find name Timeline.

So, do you know how I can do to call the Timeline constructor from timeline.js ?

答:
you simply need to do

```<code> import * as Timeline from '../assets/js/timeline.js';
</code>```

You can also do (at the top of your file) :

```<code>declare var Timeline: any;
</code>```

Check also below for good practices.

Body:
I have an angular 4 application and I have a javascript component that I created in a javascript file : timeline.js. The javascript component works well but I want to use it with angular 4. So, I put my js file in the folder assets/js/timeline.js.

In the file index.html, I call my js file with  and in app.component.ts, I have :

var timeline = new Timeline("timelineVisualization")

So, normally, the timeline is created in the div which has id="timelineVisualization".

But it doesn't work  and I have an error on the new Timeline : Cannot find name Timeline.

So, do you know how I can do to call the Timeline constructor from timeline.js ?

Body:
you simply need to do

 import * as Timeline from '../assets/js/timeline.js';

You can also do (at the top of your file) :

declare var Timeline: any;

Check also below for good practices.


问:
TYPO3 query equals by another table
I have TYPO3 7.6.18, and I have problem with query.

this works

```<code>public function getFiltered($offset = 0, $limit = 5){
    $query = $this->createQuery();
    $query->matching($query->equals('cruserId', 3));
    return $query->execute();
</code>```

But this not works

```<code>public function getFiltered($offset = 0, $limit = 5){
    $query = $this->createQuery();
    $query->matching($query->equals('cruserId.uid', 3));

    return $query->execute();
</code>```

this return empty. Why? I filter by condition in another table(fe_users). I  need filter by uid, gender or other fields. I don't know where is a problem.

TCA:

```<code>'cruser_id' => [
    'exclude' => 1,
    'label' => 'LLL:EXT:fefiles/Resources/Private/Language/locallang_db.xlf:tx_fefiles_domain_model_photo.cruser_id',
    'config' => [
        'type' => 'inline',
        'foreign_table' => 'fe_users',
        'minitems' => 0,
        'maxitems' => 1,
        'appearance' => [
            'collapseAll' => 0,
            'levelLinksPosition' => 'top',
            'showSynchronizationLink' => 1,
            'showPossibleLocalizationRecords' => 1,
            'showAllLocalizationLink' => 1
        ],
    ]
],
</code>```

Model:

```<code>  /**
     * CruserId
     *
     * @var \Fhk\Feusersplus\Domain\Model\User
     * @inject
     */
    protected $cruserId;

    /**
     * Returns the cruserId
     *
     * @return \Fhk\Feusersplus\Domain\Model\User $cruserId
     */
    public function getCruserId()
    {
        return $this->cruserId;
    }

    /**
     * Sets the cruserId
     *
     * @return void
     */
    public function setCruserId($cruserId)
    {
        $this->cruserId = $cruserId;
    }
</code>```

If I use cruserId.uid - it just return empty. I had specially create test ext by extension builder and make my model, tca the same, but it return empty. Help me please, good people) Do you now where is problem?

答:
I think cruserId.uid is not your Tables fields. in TYPO3 Extabase query syntax you need to pass always feilds name like.

$query->equals($propertyName, $operand, $caseSensitive = true )

Parameters

string   $propertyName   The name of the property to compare against

mixed    $operand    The value to compare with

bool $caseSensitive  Whether the equality test should be done
case-sensitive

For more infromation TYPO3 Query syntax

Title: TYPO3 query equals by another table

Body:
I have TYPO3 7.6.18, and I have problem with query.

this works

public function getFiltered($offset = 0, $limit = 5){
    $query = $this->createQuery();
    $query->matching($query->equals('cruserId', 3));
    return $query->execute();

But this not works

public function getFiltered($offset = 0, $limit = 5){
    $query = $this->createQuery();
    $query->matching($query->equals('cruserId.uid', 3));

    return $query->execute();

this return empty. Why? I filter by condition in another table(fe_users). I  need filter by uid, gender or other fields. I don't know where is a problem.

TCA:

'cruser_id' => [
    'exclude' => 1,
    'label' => 'LLL:EXT:fefiles/Resources/Private/Language/locallang_db.xlf:tx_fefiles_domain_model_photo.cruser_id',
    'config' => [
        'type' => 'inline',
        'foreign_table' => 'fe_users',
        'minitems' => 0,
        'maxitems' => 1,
        'appearance' => [
            'collapseAll' => 0,
            'levelLinksPosition' => 'top',
            'showSynchronizationLink' => 1,
            'showPossibleLocalizationRecords' => 1,
            'showAllLocalizationLink' => 1
        ],
    ]
],

Model:

  /**
     * CruserId
     *
     * @var \Fhk\Feusersplus\Domain\Model\User
     * @inject
     */
    protected $cruserId;

    /**
     * Returns the cruserId
     *
     * @return \Fhk\Feusersplus\Domain\Model\User $cruserId
     */
    public function getCruserId()
    {
        return $this->cruserId;
    }

    /**
     * Sets the cruserId
     *
     * @return void
     */
    public function setCruserId($cruserId)
    {
        $this->cruserId = $cruserId;
    }

If I use cruserId.uid - it just return empty. I had specially create test ext by extension builder and make my model, tca the same, but it return empty. Help me please, good people) Do you now where is problem?


问:
Statement outside watch not run
I'm new to Node.JS and I'm trying to run an example in the book Node.js The Right Way. The following code is saved in a file called watcher.js and the text file target.txt is in the same directory.

```<code>const fs = require('fs');
fs.watch('target.txt',function(){
    console.log("File 'target.txt' just changed!");
});
console.log("Now watching target.txt for changes...");
</code>```

When I run the file with the node command, the last line of the file, which should naturally be output first, is never seen. The log statement inside fs.watch() works fine and outputs the message every time the file changes.

There is a big gap between my version of Node.js (v6.11.0) and the one in the book (v0.10.20).

Is there something I am missing?

答: I've tested, your code works perfectly on node v7.1:

Title: Statement outside watch not run

Body:
I'm new to Node.JS and I'm trying to run an example in the book Node.js The Right Way. The following code is saved in a file called watcher.js and the text file target.txt is in the same directory.

const fs = require('fs');
fs.watch('target.txt',function(){
    console.log("File 'target.txt' just changed!");
});
console.log("Now watching target.txt for changes...");

When I run the file with the node command, the last line of the file, which should naturally be output first, is never seen. The log statement inside fs.watch() works fine and outputs the message every time the file changes.

There is a big gap between my version of Node.js (v6.11.0) and the one in the book (v0.10.20).

Is there something I am missing?


问:
How do you send images to node js with Axios?
Is there a way to send an array of images (or a single image) to node using axios?

The axios code I'm using(I'm using react js on the front end):

onFormSubmit(event){
    event.preventDefault();
    let payload = this.state;
    console.log("in onFormSubmit!!! with state: ", this.state, "and payload: ", payload);
    axios.post('/api/art', payload)
    .then(function(response){
    console.log('saved successfully')
  });
```

The research I've done suggests that perhaps there isn't a supported way to send image files to node using axios, but this seems strange to me. Is there a way?

答:
Here is how I implemented it:

```<code>onFormSubmit(event){
    var form = new FormData();
    files.forEach(file => {
        form.append(file.name, file);
    });
    form.append('foo', 'bar');
    axios.post('/api/art', form)
});
</code>```

On node js server make sure to use some middle-ware which handles multipart requests. I used multer.

Here are my results on the endpoint:

```<code>req.body - { foo: 'bar' }
req.files - {
    'r1.jpg': {
      fieldname: 'r1.jpg',
      originalname: 'r1.jpg',
      name: 'e2f4b9874fd7d6115b9f7440b9ead3a0.jpg',
      encoding: '7bit',
      mimetype: 'image/jpeg',
      path: '/tmp/e2f4b9874fd7d6115b9f7440b9ead3a0.jpg',
      extension: 'jpg',
      size: 45641,
      truncated: false,
      buffer: null
    }, ...
}
</code>```

Body:
Is there a way to send an array of images (or a single image) to node using axios?

The axios code I'm using(I'm using react js on the front end):

onFormSubmit(event){
    event.preventDefault();
    let payload = this.state;
    console.log("in onFormSubmit!!! with state: ", this.state, "and payload: ", payload);
    axios.post('/api/art', payload)
    .then(function(response){
    console.log('saved successfully')
  });

The research I've done suggests that perhaps there isn't a supported way to send image files to node using axios, but this seems strange to me. Is there a way?

Body:
Here is how I implemented it:

onFormSubmit(event){
    var form = new FormData();
    files.forEach(file => {
        form.append(file.name, file);
    });
    form.append('foo', 'bar');
    axios.post('/api/art', form)
});

On node js server make sure to use some middle-ware which handles multipart requests. I used multer.

Here are my results on the endpoint:

req.body - { foo: 'bar' }
req.files - {
    'r1.jpg': {
      fieldname: 'r1.jpg',
      originalname: 'r1.jpg',
      name: 'e2f4b9874fd7d6115b9f7440b9ead3a0.jpg',
      encoding: '7bit',
      mimetype: 'image/jpeg',
      path: '/tmp/e2f4b9874fd7d6115b9f7440b9ead3a0.jpg',
      extension: 'jpg',
      size: 45641,
      truncated: false,
      buffer: null
    }, ...
}


问:
How can I get the absolute path to the Eclipse install directory?
I am writing an Eclipse product, composed of plugins.

In one of my plugins, I need to get the absolute path to the directory where Eclipse is installed.

(i.e. /Applications/Eclipse on Mac or C:\Program Files\Eclipse on Win).

Can't find an API for this. Ideas?

答:
codejammer suggests:

The following gives you the installed location

```<code>Platform.getInstallLocation().getURL()
</code>```

See the org.eclipse.core.runtime.Platform API

```<code>/**
 * Returns the location of the base installation for the running platform
 * <code>null</code> is returned if the platform is running without a configuration location.
 * <p>
 * This method is equivalent to acquiring the <code>org.eclipse.osgi.service.datalocation.Location</code>
 * service with the property "type" equal to {@link Location#INSTALL_FILTER}.
 *</p>
 * @return the location of the platform's installation area or <code>null</code> if none
 * @since 3.0
 * @see Location#INSTALL_FILTER
 */
</code>```

Body:
codejammer suggests:

The following gives you the installed location

Platform.getInstallLocation().getURL()

See the org.eclipse.core.runtime.Platform API

/**
 * Returns the location of the base installation for the running platform
 * <code>null</code> is returned if the platform is running without a configuration location.
 * <p>
 * This method is equivalent to acquiring the <code>org.eclipse.osgi.service.datalocation.Location</code>
 * service with the property "type" equal to {@link Location#INSTALL_FILTER}.
 *</p>
 * @return the location of the platform's installation area or <code>null</code> if none
 * @since 3.0
 * @see Location#INSTALL_FILTER
 */


问:
boostrap inline form not styling
I am trying to create a inline form, but its not styling correctly.

Below is the code I am using:

body {
  background-color: #a7cdf2;
}

#map {
  height: 70%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <link href="/static/css/bootstrap.min.css" rel="stylesheet" media="screen">
  <link href="/static/css/bootstrap-responsive.min.css" rel="stylesheet">
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script src="/static/js/bootstrap.min.js"></script>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
  <form class="inline" action="" method="post" name="search">
    <input id="csrf_token" name="csrf_token" type="hidden" value="xxx">
      <datalist id="id_datalist">
        <option value="CLARENVILLE, CA">
    </datalist>
    <div class="form-group">
      <label for="origin">Origin:</label>
      <input class="form-control" id="origin" list="id_datalist" name="origin" size="40" type="text" value="SHANGHAI, CN">
    </div>
    <div class="form-group">
      <label for="speed">Speed (knots):</label>
      <input class="form-control" id="speed" name="speed" size="5" type="text" value="14.0">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>
</body>
</html></code>```

This is how it renders in Chrome:

答:
It seems your boostrap links are incorrect... I played around with your code and replaced the links and it worked fine. It looks like either you have put the downloaded files in the wrong place, or perhaps the example you found wasn't clear. When the src has a value like /static/css/bootstrap.min.css it is looking at the files on the server hosting the site. Perhaps you should use CDN links instead?

```<code><head>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" media="screen">
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
</code>```

body {
  background-color: #a7cdf2;
}

#map {
  height: 70%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" media="screen">
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
  <form class="inline" action="" method="post" name="search">
    <input id="csrf_token" name="csrf_token" type="hidden" value="xxx">
    <datalist id="id_datalist">
        <option value="CLARENVILLE, CA">
    </datalist>
    <div class="form-group">
      <label for="origin">Origin:</label>
      <input class="form-control" id="origin" list="id_datalist" name="origin" size="40" type="text" value="SHANGHAI, CN">
    </div>
    <div class="form-group">
      <label for="speed">Speed (knots):</label>
      <input class="form-control" id="speed" name="speed" size="5" type="text" value="14.0">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>
</body>

</html></code>```

Title: boostrap inline form not styling

Body:
I am trying to create a inline form, but its not styling correctly.

Below is the code I am using:

body {
  background-color: #a7cdf2;
}

#map {
  height: 70%;
}

<!DOCTYPE html>

  <link href="/static/css/bootstrap.min.css" rel="stylesheet" media="screen">
  <link href="/static/css/bootstrap-responsive.min.css" rel="stylesheet">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <form class="inline" action="" method="post" name="search">
    <input id="csrf_token" name="csrf_token" type="hidden" value="xxx">
      <datalist id="id_datalist">
        <option value="CLARENVILLE, CA">
    </datalist>

      Origin:
      <input class="form-control" id="origin" list="id_datalist" name="origin" size="40" type="text" value="SHANGHAI, CN">

      Speed (knots):
      <input class="form-control" id="speed" name="speed" size="5" type="text" value="14.0">

    <button type="submit" class="btn btn-default">Submit</button>
  </form>

This is how it renders in Chrome:

Body:
It seems your boostrap links are incorrect... I played around with your code and replaced the links and it worked fine. It looks like either you have put the downloaded files in the wrong place, or perhaps the example you found wasn't clear. When the src has a value like /static/css/bootstrap.min.css it is looking at the files on the server hosting the site. Perhaps you should use CDN links instead?

<head>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" media="screen">
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

body {
  background-color: #a7cdf2;
}

#map {
  height: 70%;
}

<!DOCTYPE html>
<html>
<head>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" media="screen">
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
  <form class="inline" action="" method="post" name="search">
    <input id="csrf_token" name="csrf_token" type="hidden" value="xxx">
    <datalist id="id_datalist">
        <option value="CLARENVILLE, CA">
    </datalist>
    <div class="form-group">
      <label for="origin">Origin:</label>
      <input class="form-control" id="origin" list="id_datalist" name="origin" size="40" type="text" value="SHANGHAI, CN">
    </div>
    <div class="form-group">
      <label for="speed">Speed (knots):</label>
      <input class="form-control" id="speed" name="speed" size="5" type="text" value="14.0">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>
</body>

</html>


问:
I want to extract the tag name using sql from table with XML stored as clob. (ORACLE)
Sample XML as below:

```<code><Root>
...
<XMLNSC>
...
<SOAP-ENV:Envelope>
...
<SOAP-ENV:Body>
<typesNS0:getABCD xmlns:typesNS0="http://xxx.xx/xxxxxx/xxxxxxxxx/x/" xmlns:xalan="http://xml.apache.org/xslt">
</code>```

last tag typesNS0:getABCD want to select

答:
```<code>select xmltype(a).extract('//typesNS0:getABCD','xmlns:typesNS0="http://xxx.xx/xxxxxx/xxxxxxxxx/x/"')
from (
  select
  '<Root xmlns:SOAP-ENV="http://a.b.org/">
    <XMLNSC />
    <SOAP-ENV:Envelope/>
    <SOAP-ENV:Body/>
    <typesNS0:getABCD xmlns:typesNS0="http://xxx.xx/xxxxxx/xxxxxxxxx/x/" xmlns:xalan="http://xml.apache.org/xslt">123</typesNS0:getABCD>
  </Root>' a from dual
)
</code>```

Body:
Sample XML as below:

<Root>
...
<XMLNSC>
...
<SOAP-ENV:Envelope>
...
<SOAP-ENV:Body>
<typesNS0:getABCD xmlns:typesNS0="http://xxx.xx/xxxxxx/xxxxxxxxx/x/" xmlns:xalan="http://xml.apache.org/xslt">

last tag typesNS0:getABCD want to select


问:
Ajax calling situation on asynchorous call
I am stuck with my specific problem.
I want to return false if the data comes using ajax.
Here is my code:

```<code>  <script>
    function verifydom(form)
        {
            var domnam = form.domname.value;
            if (domnam == "")
            {
                alert("Please enter the Domain Name");
                    form.domname.focus();
                    return false;
            }
            else if(domnam.indexOf('.gov.in') <= 0){
                alert("Please enter valid domain name");
                    form.domname.focus();
                    return false;
            }
            else{
                $.ajax({
                   type: "get",
                    url: "calling.php",
                    data: "domnam="+domnam,
                    success: function(msg){
                        if(msg!== ""){
                            alert(msg);
                        }
                    }
                });
                return false;
            }
            return true;
        }
     </script>
    <form name="frmDelegate" action="dlgdetail.php" method="POST"
    onsubmit="return verifydom(document.frmDelegate);" autocomplete="off">
    input type="text" name="domname" id= "domname"
    onkeyup="showResult(this.value);"/>            <input type="hidden"
    id="chkmsg" value=""/>
    <input type="submit" value="Go" name="submit" />
    </form>
</code>```

The ajax call under 'else condition' would return some error message, So if an error comes, I want the form not to be submitted.
Okay, the problem is 'Else will work every time whether Ajax gives a message or not.
How can I overcome this situation?

答:
Rather than blank message I would prefer to return a JSON message from the calling.php file.

```<code>$arr = array( "status" => "error", "message" => "error found");
echo json_encode($arr);
</code>```

By doing this you are easily allowed to check whether the error is there or not. If JSON have any message then you should check by below code.

```<code>$.ajax({
   type: "get",
   url: "calling.php",
   data: "domnam="+domnam,
   success: function(msg){
   var data = jQuery.parseJSON(msg);
       if(data.status == "error"){ // no need to check strictly
          return false;
       }
    }
});
</code>```

Body:
I am stuck with my specific problem.
I want to return false if the data comes using ajax.
Here is my code:

    <form name="frmDelegate" action="dlgdetail.php" method="POST"
    onsubmit="return verifydom(document.frmDelegate);" autocomplete="off">
    input type="text" name="domname" id= "domname"
    onkeyup="showResult(this.value);"/>            <input type="hidden"
    id="chkmsg" value=""/>
    <input type="submit" value="Go" name="submit" />
    </form>

The ajax call under 'else condition' would return some error message, So if an error comes, I want the form not to be submitted.
Okay, the problem is 'Else will work every time whether Ajax gives a message or not.
How can I overcome this situation?

Body:
Rather than blank message I would prefer to return a JSON message from the calling.php file.

$arr = array( "status" => "error", "message" => "error found");
echo json_encode($arr);

By doing this you are easily allowed to check whether the error is there or not. If JSON have any message then you should check by below code.

$.ajax({
   type: "get",
   url: "calling.php",
   data: "domnam="+domnam,
   success: function(msg){
   var data = jQuery.parseJSON(msg);
       if(data.status == "error"){ // no need to check strictly
          return false;
       }
    }
});