问:
Extract images from word file in C#
I have a problem in image extraction. I have written this code to extract all images from word file but this code works for some images means it does save some image files but on the other hand this code does not extract images from Word file. I'm using office interop library.</p>

```<code>    protected void ExtractImage(string imagename, int imagenum)
    {

        word.InlineShape shape = oword.ActiveDocument.InlineShapes[imagenum];
        int dones = oword.ActiveDocument.InlineShapes.Count;           //Counts number of images in word document
        for(int i =1 ; i <= dones; i++)
        {
            shape = oword.ActiveDocument.InlineShapes[i];
            shape.Select();
            oword.Selection.Copy();

            if (Clipboard.GetDataObject() != null)
            {
                IDataObject data = Clipboard.GetDataObject();
                if (data.GetDataPresent(DataFormats.Bitmap))
                {
                    System.Drawing.Bitmap image = (System.Drawing.Bitmap)data.GetData(typeof(System.Drawing.Bitmap));
                    image.Save(@"C:\Upload2\" + imagename, System.Drawing.Imaging.ImageFormat.Jpeg);
                    Clipboard.Clear();
                }
            }
        }
     }
</code>```

答:
I don't like messing with the Clipboard because the user might be using it...

So, instead I did this using the following code:

```<code>private IEnumerable<Image> GetImagesFromXml(string xml)
{
    XDocument doc = XDocument.Parse(xml);

    var ns = doc.Root.Name.Namespace;
    var images = doc.Descendants(ns + "part").Where(a => a.Attribute(ns + "contentType") != null && a.Attribute(ns + "contentType").Value.Contains("image"))
    .Select(a => new { Name = a.Attribute(ns + "name").Value, Type = a.Attribute(ns + "contentType").Value, D64 = a.Descendants(ns + "binaryData").First().Value, Compression = a.Attribute(ns + "compression").Value });

    return images.Select(i => Image.FromStream(new MemoryStream(Convert.FromBase64String(i.D64)), false, false));
}
</code>```

Title: Extract images from word file in C#

Body:
I have a problem in image extraction. I have written this code to extract all images from word file but this code works for some images means it does save some image files but on the other hand this code does not extract images from Word file. I'm using office interop library.

    protected void ExtractImage(string imagename, int imagenum)
    {

        word.InlineShape shape = oword.ActiveDocument.InlineShapes[imagenum];
        int dones = oword.ActiveDocument.InlineShapes.Count;           //Counts number of images in word document
        for(int i =1 ; i <= dones; i++)
        {
            shape = oword.ActiveDocument.InlineShapes[i];
            shape.Select();
            oword.Selection.Copy();

            if (Clipboard.GetDataObject() != null)
            {
                IDataObject data = Clipboard.GetDataObject();
                if (data.GetDataPresent(DataFormats.Bitmap))
                {
                    System.Drawing.Bitmap image = (System.Drawing.Bitmap)data.GetData(typeof(System.Drawing.Bitmap));
                    image.Save(@"C:\Upload2\" + imagename, System.Drawing.Imaging.ImageFormat.Jpeg);
                    Clipboard.Clear();
                }
            }
        }
     }

Body:
I don't like messing with the Clipboard because the user might be using it...

So, instead I did this using the following code:

private IEnumerable<Image> GetImagesFromXml(string xml)
{
    XDocument doc = XDocument.Parse(xml);

    var ns = doc.Root.Name.Namespace;
    var images = doc.Descendants(ns + "part").Where(a => a.Attribute(ns + "contentType") != null && a.Attribute(ns + "contentType").Value.Contains("image"))
    .Select(a => new { Name = a.Attribute(ns + "name").Value, Type = a.Attribute(ns + "contentType").Value, D64 = a.Descendants(ns + "binaryData").First().Value, Compression = a.Attribute(ns + "compression").Value });

    return images.Select(i => Image.FromStream(new MemoryStream(Convert.FromBase64String(i.D64)), false, false));
}


来源: stackexchange

问:
Creating CGImageContext for resizing UIImage fails in simulator
I've got some code to resize a UIImage (in a category to UIImage), that first generates an Image Context:

```<code>CGImageRef oldImage = [self CGImage];
CGSize oldSize = [self size];

CGContextRef context = CGBitmapContextCreate(NULL, //Data
    newSize.width, //Width
    newSize.height, //Height
    CGImageGetBitsPerComponent(oldImage), // Bits per Component
    4 * newSize.width, //Bytes per Row
    CGImageGetColorSpace(oldImage), //Color Space
    CGImageGetBitmapInfo(oldImage)); //Info
</code>```

On the device, this code works well, but on the simulator it fails with the following error:

```<code><Error>: CGBitmapContextCreate: unsupported parameter combination: 8 integer bits/component; 24 bits/pixel; 3-component colorspace; kCGImageAlphaNone; 428 bytes/row.
</code>```

Does anyone have an explanation for this? If I remember correctly, it worked fine prior to 2.2 Thanks!

答:
I know very little about this, but my wild guess would be that your Bytes Per Row argument needs to be 3 * newSize.width since the image is reporting that there's no alpha component.

If that doesn't work, you might want to look at the Quartz 2D Programming Guide's Supported Pixel Formats for more info. What's distressing is that there are no entries for 24 bpp, even though that's what's being reported by the error. You may want to log the relevant values in both the simulator and the device to see if there are any other discrepancies.

OwnerDisplayName: Gernot

ContentLicense: CC BY-SA 2.5

Body:
I've got some code to resize a UIImage (in a category to UIImage), that first generates an Image Context:

CGImageRef oldImage = [self CGImage];
CGSize oldSize = [self size];

CGContextRef context = CGBitmapContextCreate(NULL, //Data
    newSize.width, //Width
    newSize.height, //Height
    CGImageGetBitsPerComponent(oldImage), // Bits per Component
    4 * newSize.width, //Bytes per Row
    CGImageGetColorSpace(oldImage), //Color Space
    CGImageGetBitmapInfo(oldImage)); //Info

On the device, this code works well, but on the simulator it fails with the following error:

<Error>: CGBitmapContextCreate: unsupported parameter combination: 8 integer bits/component; 24 bits/pixel; 3-component colorspace; kCGImageAlphaNone; 428 bytes/row.

Does anyone have an explanation for this? If I remember correctly, it worked fine prior to 2.2 Thanks!

LastEditorDisplayName: Chris Hanson

OwnerDisplayName: Martin Gordon


问:
How can i Pass the arguments in the button selector method in iPhone?
Now i want to pass the arguments in the button selector method, so how can i pass that arguments in the button selector method?

```<code>    //Button creation

    -(void) viewDidLoad
    {
         UIButton *imageOverlayBtn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];

     imageOverlayBtn.frame = CGRectMake(xOrigin, yOrigin, theSize.width, theSize.height);

            //Pass this string into selector method
     NSString *passString = [feedArray objectForKey:@"URLString"];

     [imageOverlayBtn addTarget:self action:@selector(overlayBtnAction:) forControlEvents:UIControlEventTouchUpInside];

       }

    // Button Action
    -(void) overlayBtnAction : (NSString *) getString
    {
          NSLog(@"The get string is %@", getString)
    }
</code>```

So how can i pass the string to the selector method?. Please Help me out.

Thanks.

答:
First of all your action method should be implemented with this signature:

```<code>-(void) overlayBtnAction : (id) sender
{
...
}
</code>```

Where sender is the pointer to the UIButton (in general case to a UIControl) which have invoked this handler.

Your target is self, so you can declare a NSString variable being member of this class.

So in viewDidLoad you will have:

```<code>  self.passString = [feedArray objectForKey:@"URLString"];
</code>```

And in handler just use its value:

```<code>-(void) overlayBtnAction : (id) sender
{
    NSString *localVar = self.passString;
}
</code>```

Body:
Now i want to pass the arguments in the button selector method, so how can i pass that arguments in the button selector method?

    //Button creation

    -(void) viewDidLoad
    {
         UIButton *imageOverlayBtn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];

     imageOverlayBtn.frame = CGRectMake(xOrigin, yOrigin, theSize.width, theSize.height);

            //Pass this string into selector method
     NSString *passString = [feedArray objectForKey:@"URLString"];

     [imageOverlayBtn addTarget:self action:@selector(overlayBtnAction:) forControlEvents:UIControlEventTouchUpInside];

       }

    // Button Action
    -(void) overlayBtnAction : (NSString *) getString
    {
          NSLog(@"The get string is %@", getString)
    }

So how can i pass the string to the selector method?. Please Help me out.

Thanks.

Body:
First of all your action method should be implemented with this signature:

-(void) overlayBtnAction : (id) sender
{
...
}

Where sender is the pointer to the UIButton (in general case to a UIControl) which have invoked this handler.

Your target is self, so you can declare a NSString variable being member of this class.

So in viewDidLoad you will have:

  self.passString = [feedArray objectForKey:@"URLString"];

And in handler just use its value:

-(void) overlayBtnAction : (id) sender
{
    NSString *localVar = self.passString;
}


问:
qr function in R and matlab
I have a question about converting a matlab function into R, and I was hoping that someone could help.

The standard QR decomposition used in both matlab and R is referred to as qr(). To my understanding, the standard way of performing a qr decomposition in both languages is:

Matlab:
[Q,R] = qr(A) satisfying QR=A

R:

```<code>z <- qr(A)
Q <- qr.Q(z)
R <- qr.R(z)
</code>```

Both of which provide me with the same results, unfortunately, this is not what I need. What I need is this:

Matlab:
[Q,R,e] = qr(A,0) which produces an economy-size decomposition in which e is a permutation vector so that A(:,e) = Q*R.

R:
No clue

I have tried comparing [Q,R,E] = qr(A) with

```<code>z <- qr(A);
Q <- qr.Q(z);
R <- qr.R(z);
E <- diag(ncol(A))[z$pivot]
</code>```

and results seem identical for variables Q and E (but different for R). So depending on the defined inputs/outputs there will be different results (which makes sense).

So my question is:
Is there a way in R that can mimic this [Q,R,e]=qr(A,0) in Matlab?

I have tried digging into the matlab function but it leads to a long and torturous road of endless function definitions and I was hoping for a better solution.

Any help would be much appreciated, and if I've missed something obvious, I apologize.

答:
I think the difference comes down to the numerical library underlying the calculations. By default, R's qr function uses the (very old) LINPACK routines, but if I do

```<code>z <- qr(X,LAPACK=T)
</code>```

then R uses LAPACK and the results seem to match MATLAB's (which is probably also using LAPACK underneath). Either way we see the expected relationship with X:

```<code>z <- qr(X,LAPACK=F)
all.equal(X[,z$pivot], qr.Q(z)%*%qr.R(z), check.attributes=FALSE)
# [1] TRUE

z <- qr(X,LAPACK=T)
all.equal(X[,z$pivot], qr.Q(z)%*%qr.R(z), check.attributes=FALSE)
# [1] TRUE
</code>```

ContentLicense: CC BY-SA 3.0

Title: qr function in R and matlab

Body:
I have a question about converting a matlab function into R, and I was hoping that someone could help.

The standard QR decomposition used in both matlab and R is referred to as qr(). To my understanding, the standard way of performing a qr decomposition in both languages is:

Matlab:
[Q,R] = qr(A) satisfying QR=A

R:

z <- qr(A)
Q <- qr.Q(z)
R <- qr.R(z)

Both of which provide me with the same results, unfortunately, this is not what I need. What I need is this:

Matlab:
[Q,R,e] = qr(A,0) which produces an economy-size decomposition in which e is a permutation vector so that A(:,e) = Q*R.

R:
No clue

I have tried comparing [Q,R,E] = qr(A) with

z <- qr(A);
Q <- qr.Q(z);
R <- qr.R(z);
E <- diag(ncol(A))[z$pivot]

and results seem identical for variables Q and E (but different for R). So depending on the defined inputs/outputs there will be different results (which makes sense).

So my question is:
Is there a way in R that can mimic this [Q,R,e]=qr(A,0) in Matlab?

I have tried digging into the matlab function but it leads to a long and torturous road of endless function definitions and I was hoping for a better solution.

Any help would be much appreciated, and if I've missed something obvious, I apologize.

Body:
I think the difference comes down to the numerical library underlying the calculations. By default, R's qr function uses the (very old) LINPACK routines, but if I do

z <- qr(X,LAPACK=T)

then R uses LAPACK and the results seem to match MATLAB's (which is probably also using LAPACK underneath). Either way we see the expected relationship with X:

z <- qr(X,LAPACK=F)
all.equal(X[,z$pivot], qr.Q(z)%*%qr.R(z), check.attributes=FALSE)
# [1] TRUE

z <- qr(X,LAPACK=T)
all.equal(X[,z$pivot], qr.Q(z)%*%qr.R(z), check.attributes=FALSE)
# [1] TRUE


问:
Haskell recursive function add to the end of a list
I have a recursive Haskell function that takes a number n and generates a list that is n long of squared numbers from 1 up.

The code works but instead of the list for n=3 being [9,4,1] I want it to be [1,4,9].

```<code>sqNList :: Int -> [Int]
sqNList 0  = []
sqNList n  = n*n : sqNList (n-1)
</code>```

I've tried swappig the : for a ++ but then the pattern matching doesn't work. I have only just started Haskell today so may be obvious

答:
This is a more advanced technique, so you may want to just save this for future study.

Most recursive functions tend to use one of the same general forms of recursion, so knowing which higher-order function to use saves you the effort of reimplementing (possibly incorrectly) the recursion, and lets you focus on the work that is unique to your problem.

This particular type of recursion is captured by the unfoldr function, defined in Data.List, which lets you generate a (possibly infinite) list using a generator function and an initial seed value.

Its definition can be as simple as

```<code>unfoldr f x = case f x of
                    Nothing -> []
                    Just (new, next) = new : unfoldr f next
</code>```

although the actual definition is slightly more complicated for efficiency.

Essentially, you just call the generator f on the seed value x. If the result is Nothing, return an empty list. Otherwise, build a list containing a result and the list produced by a recursive call with a new seed value.

Applying this to your problem, we produce a square and the next integer as long as the input is still small enough.

```<code>import Data.List (unfoldr)
sqNList n = unfoldr generator 1
            where generator x = if x > n then Nothing else Just (x*x, x+1)
</code>```

So for a simple example like sqNList 3, it proceeds as follows:

Call generator 1 and get back Just (1, 2); the accumulator is now [1].

Call generator 2 and get back Just (4, 3); the accumulator is now
[1,4].

Call generator 3 and get back Just (9, 4); the accumulator is now [1,4,9].

Call generator 4 and get back Nothing. Return the accumulator [1,4,9] as the result.

Note that you generate the infinite list of all squares simply by never returning Nothing:

```<code>allSquares = unfoldr (\x -> Just (x*x, x+1)) 1
</code>```

Haskell, being lazy, only generates elements in the list as you need them, so you could also define sqNList by taking only the first n items of the infinite list.

```<code>sqNList n = take n (unfoldr (\x -> Just (x*x, x+1)) 1)
</code>```

Body:
I have a recursive Haskell function that takes a number n and generates a list that is n long of squared numbers from 1 up.

The code works but instead of the list for n=3 being [9,4,1] I want it to be [1,4,9].

sqNList :: Int -> [Int]
sqNList 0  = []
sqNList n  = n*n : sqNList (n-1)

I've tried swappig the : for a ++ but then the pattern matching doesn't work. I have only just started Haskell today so may be obvious

Body:
This is a more advanced technique, so you may want to just save this for future study.

Most recursive functions tend to use one of the same general forms of recursion, so knowing which higher-order function to use saves you the effort of reimplementing (possibly incorrectly) the recursion, and lets you focus on the work that is unique to your problem.

This particular type of recursion is captured by the unfoldr function, defined in Data.List, which lets you generate a (possibly infinite) list using a generator function and an initial seed value.

Its definition can be as simple as

unfoldr f x = case f x of
                    Nothing -> []
                    Just (new, next) = new : unfoldr f next

although the actual definition is slightly more complicated for efficiency.

Essentially, you just call the generator f on the seed value x. If the result is Nothing, return an empty list. Otherwise, build a list containing a result and the list produced by a recursive call with a new seed value.

Applying this to your problem, we produce a square and the next integer as long as the input is still small enough.

import Data.List (unfoldr)
sqNList n = unfoldr generator 1
            where generator x = if x > n then Nothing else Just (x*x, x+1)

So for a simple example like sqNList 3, it proceeds as follows:

Call generator 1 and get back Just (1, 2); the accumulator is now [1].

Call generator 2 and get back Just (4, 3); the accumulator is now
[1,4].

Call generator 3 and get back Just (9, 4); the accumulator is now [1,4,9].

Call generator 4 and get back Nothing. Return the accumulator [1,4,9] as the result.

Note that you generate the infinite list of all squares simply by never returning Nothing:

allSquares = unfoldr (\x -> Just (x*x, x+1)) 1

Haskell, being lazy, only generates elements in the list as you need them, so you could also define sqNList by taking only the first n items of the infinite list.

sqNList n = take n (unfoldr (\x -> Just (x*x, x+1)) 1)


问:
How to avoid casting?
I add new global hight level interface:

```<code>    public interface MvpView {
    }
</code>```

My hight level interface:

```<code>public interface OfferDetailsView extends MvpView {

   public void showProgress();
}
</code>```

Another interface:

```<code>public interface OfferDetailsPdfMvp {

    interface View extends OfferDetailsView  {

        public void openLocalPdfFile(File file, int pageNumber);

    }

    interface Presenter extends OfferDetailsPresenter {

        public void onPageScrolled(int page, int pageCount);

    }
}
</code>```

Another interface:

```<code>public interface OfferDetailsPresenter extends MvpPresenter {

    public void downloadToAppDir(boolean isDownloadToAppCacheDir);

    public void onClickScreen(boolean isVisibleTopContainer);
}
</code>```

Another interface:

```<code>public interface MvpPresenter<V extends MvpView> {
    public void attachView(V mvpView);
}
</code>```

Base abstract class:

```<code>public abstract class BaseOfferDetailsPresenter<T extends MvpView> implements MvpPresenter<T> {
    private T view;

     @Override
    public void attachView(T mvpView) {
        this.view = mvpView;
    }

   public T getView() {
         return view;
    }
}
</code>```

And conrete class that extend from Base class:

```<code>public class OfferDetailsPdfPresenterImpl extends BaseOfferDetailsPresenter<OfferDetailsPdfMvp.View> implements OfferDetailsPdfMvp.Presenter {

    public void viewIsReady() {
      getView().showProgress(); //no cast
      getView().openLocalPdfFile(file, currentPageNumber); // no cast
    }
</code>```

But I get compile error:

```<code>myproject\app\src\main\java\com\myproject\android\customer\presenter\OfferDetailsPdfPresenterImpl.java:35: error: MvpPresenter cannot be inherited with different arguments: <> and <com.myproject.android.customer.mvp.OfferDetailsPdfMvp.View>
    public class OfferDetailsPdfPresenterImpl extends BaseOfferDetailsPresenter<OfferDetailsPdfMvp.View> implements OfferDetailsPdfMvp.Presenter {
</code>```

答:
To make what you want, you should change your OfferDetailsPresenter signature:

```<code>public interface OfferDetailsPresenter<T extends MvpView> extends MvpPresenter<T> {

    void downloadToAppDir(boolean isDownloadToAppCacheDir);

    void onClickScreen(boolean isVisibleTopContainer);
}
</code>```

Then, inside OfferDetailsPdfMvp you should change Presenter signature in the same manner:

```<code>public interface OfferDetailsPdfMvp {

    interface View extends OfferDetailsView  {

        public void openLocalPdfFile(File file, int pageNumber);

    }

    interface Presenter<T extends MvpView> extends OfferDetailsPresenter<T> {

        public void onPageScrolled(int page, int pageCount);

    }
}
</code>```

And then populate desired View as you do with the BaseOfferDetailsPresenter<T extends MvpView>:

```<code>OfferDetailsPdfPresenterImpl extends BaseOfferDetailsPresenter<OfferDetailsPdfMvp.View> implements OfferDetailsPdfMvp.Presenter<OfferDetailsPdfMvp.View>
</code>```

Title: How to avoid casting?

Body:
I add new global hight level interface:

    public interface MvpView {
    }

My hight level interface:

public interface OfferDetailsView extends MvpView {

   public void showProgress();
}

Another interface:

public interface OfferDetailsPdfMvp {

    interface View extends OfferDetailsView  {

        public void openLocalPdfFile(File file, int pageNumber);

    }

    interface Presenter extends OfferDetailsPresenter {

        public void onPageScrolled(int page, int pageCount);

    }
}

Another interface:

public interface OfferDetailsPresenter extends MvpPresenter {

    public void downloadToAppDir(boolean isDownloadToAppCacheDir);

    public void onClickScreen(boolean isVisibleTopContainer);
}

Another interface:

public interface MvpPresenter<V extends MvpView> {
    public void attachView(V mvpView);
}

Base abstract class:

public abstract class BaseOfferDetailsPresenter<T extends MvpView> implements MvpPresenter<T> {
    private T view;

     @Override
    public void attachView(T mvpView) {
        this.view = mvpView;
    }

   public T getView() {
         return view;
    }
}

And conrete class that extend from Base class:

public class OfferDetailsPdfPresenterImpl extends BaseOfferDetailsPresenter<OfferDetailsPdfMvp.View> implements OfferDetailsPdfMvp.Presenter {

    public void viewIsReady() {
      getView().showProgress(); //no cast
      getView().openLocalPdfFile(file, currentPageNumber); // no cast
    }

But I get compile error:

myproject\app\src\main\java\com\myproject\android\customer\presenter\OfferDetailsPdfPresenterImpl.java:35: error: MvpPresenter cannot be inherited with different arguments: <> and <com.myproject.android.customer.mvp.OfferDetailsPdfMvp.View>
    public class OfferDetailsPdfPresenterImpl extends BaseOfferDetailsPresenter<OfferDetailsPdfMvp.View> implements OfferDetailsPdfMvp.Presenter {

Body:
To make what you want, you should change your OfferDetailsPresenter signature:

public interface OfferDetailsPresenter<T extends MvpView> extends MvpPresenter<T> {

    void downloadToAppDir(boolean isDownloadToAppCacheDir);

    void onClickScreen(boolean isVisibleTopContainer);
}

Then, inside OfferDetailsPdfMvp you should change Presenter signature in the same manner:

public interface OfferDetailsPdfMvp {

    interface View extends OfferDetailsView  {

        public void openLocalPdfFile(File file, int pageNumber);

    }

    interface Presenter<T extends MvpView> extends OfferDetailsPresenter<T> {

        public void onPageScrolled(int page, int pageCount);

    }
}

And then populate desired View as you do with the BaseOfferDetailsPresenter<T extends MvpView>:

OfferDetailsPdfPresenterImpl extends BaseOfferDetailsPresenter<OfferDetailsPdfMvp.View> implements OfferDetailsPdfMvp.Presenter<OfferDetailsPdfMvp.View>


问:
Laravel 5.1 Migration and Seeding Cannot truncate a table referenced in a foreign key constraint
I'm trying to run the migration (see below) and seed the database, but when I run

```<code>php artisan migrate --seed
</code>```

I get this error:

```<code>Migration table created successfully.
Migrated: 2015_06_17_100000_create_users_table
Migrated: 2015_06_17_200000_create_password_resets_table
Migrated: 2015_06_17_300000_create_vehicles_table

[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table
referenced in a foreign key constraint (`app`.`vehicles`, CONSTRAINT `vehic
les_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `app`.`users` (`id`
)) (SQL: truncate `users`)

[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table
referenced in a foreign key constraint (`app`.`vehicles`, CONSTRAINT `vehic
les_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `app`.`users` (`id`
))
</code>```

I looked up what this error is supposed to mean, and also found examples of other people running into the same problem, even just related to using MySQL, and their solutions, but applying:

```<code>DB::statement('SET FOREIGN_KEY_CHECKS=0;'); and
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
</code>```

Within down() doesn't seem to work and when I run describe in MySQL the tables look right.

The migrations are named properly to make sure the users table is migrated first, and then vehicles so the foreign key can be applied, and the tables being setup up correctly suggests the migrations were run, but then the error occurs.  I dropped and recreated the DB and tried it again and it is the same result.  I also don't understand why it is trying to truncate on the first migration and seed of the database, I wouldn't have thought that would occur when you tried to run php artisan migrate:refresh --seed.

```<code>// 2015_06_17_100000_create_users_table.php

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('username', 60)->unique();
            $table->string('email', 200)->unique();
            $table->string('password', 255);
            $table->string('role')->default('user');
            $table->rememberToken();
            $table->timestamps();
        });
    }
}

public function down()
{
    Schema::drop('users');
}

// 2015_06_17_300000_create_vehicles_table.php

class CreateVehiclesTable extends Migration
{
    public function up()
    {
        Schema::create('vehicles', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('make');
            $table->string('model');
            $table->string('year');
            $table->string('color');
            $table->string('plate');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users');
        });
    }
}

public function down()
{
    Schema::drop('vehicles');
}
</code>```

答:
you can use

```<code>DB::table('your_table_name')->delete();
</code>```

to empty a table, this won't delete the table structure. But the auto increment id will not start from initial number.

Body:
I'm trying to run the migration (see below) and seed the database, but when I run

php artisan migrate --seed

I get this error:

Migration table created successfully.
Migrated: 2015_06_17_100000_create_users_table
Migrated: 2015_06_17_200000_create_password_resets_table
Migrated: 2015_06_17_300000_create_vehicles_table

[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table
referenced in a foreign key constraint (`app`.`vehicles`, CONSTRAINT `vehic
les_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `app`.`users` (`id`
)) (SQL: truncate `users`)

[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table
referenced in a foreign key constraint (`app`.`vehicles`, CONSTRAINT `vehic
les_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `app`.`users` (`id`
))

I looked up what this error is supposed to mean, and also found examples of other people running into the same problem, even just related to using MySQL, and their solutions, but applying:

DB::statement('SET FOREIGN_KEY_CHECKS=0;'); and
DB::statement('SET FOREIGN_KEY_CHECKS=1;');

Within down() doesn't seem to work and when I run describe in MySQL the tables look right.

The migrations are named properly to make sure the users table is migrated first, and then vehicles so the foreign key can be applied, and the tables being setup up correctly suggests the migrations were run, but then the error occurs.  I dropped and recreated the DB and tried it again and it is the same result.  I also don't understand why it is trying to truncate on the first migration and seed of the database, I wouldn't have thought that would occur when you tried to run php artisan migrate:refresh --seed.

// 2015_06_17_100000_create_users_table.php

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('username', 60)->unique();
            $table->string('email', 200)->unique();
            $table->string('password', 255);
            $table->string('role')->default('user');
            $table->rememberToken();
            $table->timestamps();
        });
    }
}

public function down()
{
    Schema::drop('users');
}

// 2015_06_17_300000_create_vehicles_table.php

class CreateVehiclesTable extends Migration
{
    public function up()
    {
        Schema::create('vehicles', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('make');
            $table->string('model');
            $table->string('year');
            $table->string('color');
            $table->string('plate');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users');
        });
    }
}

public function down()
{
    Schema::drop('vehicles');
}

Body:
you can use

DB::table('your_table_name')->delete();

to empty a table, this won't delete the table structure. But the auto increment id will not start from initial number.


问:
MySQL GROUP BY/ORDER BY problem
I have an MySQL query like this:

```<code>   SELECT
         MAX(messages.ID) as maxID,
         messages.from,
         messages.read,
               users.userName
      FROM
         messages
      LEFT OUTER JOIN
         users
              ON
              users.ID = messages.from
      WHERE
       messages.to = ?
      GROUP BY
       messages.from
      ORDER BY
       maxID DESC
</code>```

While this works fine and the messages are group by the user who sent them in DESCENDING order, I now have a problem when I want to ORDER BY the messages.read row. My code is as follows:

```<code>   SELECT
         MAX(messages.ID) as maxID,
         messages.from,
         messages.read,
               users.userName
      FROM
         messages
      LEFT OUTER JOIN
         users
              ON
              users.ID = messages.from
      WHERE
       messages.to = ?
      GROUP BY
       messages.from
      ORDER BY
             messages.read ASC,
       maxID DESC
</code>```

Now, messages.read returns the value of the row of the first message that the user send. But I need the value of the newest (highest ID) that the user send.
I know that GROUP BY groups by the first in the table, so how can I get around doing this?

Thank you very much in advance,
Fischer

答:
I know that GROUP BY groups by the
  first in the table, so how can I get
  around doing this?

That's not actually true.  It will return a random row.  In practice, this is often the first row in primary key order, but there is no guarantee.  Databases other than MySQL do not allow this practice and will raise an error.

Anyway, one way to retrieve the highest ID of unread messages is by joining the messages table twice.  The second join only looks for unread messages.  For example:

```<code>SELECT  max(msg.ID) as MaxID
,       messages.from
,       max(unread.ID) as MaxUnreadID
,       users.userName
FROM    users
join    messages msg
on      users.ID = msg.from
        and messages.to = ?
left join
        messages unread
on      users.ID = unread.from
        and messages.to = ?
        and unread.read = 0
GROUP BY
        users.ID
,       users.userName
</code>```

Title: MySQL GROUP BY/ORDER BY problem

Body:
I have an MySQL query like this:

   SELECT
         MAX(messages.ID) as maxID,
         messages.from,
         messages.read,
               users.userName
      FROM
         messages
      LEFT OUTER JOIN
         users
              ON
              users.ID = messages.from
      WHERE
       messages.to = ?
      GROUP BY
       messages.from
      ORDER BY
       maxID DESC

While this works fine and the messages are group by the user who sent them in DESCENDING order, I now have a problem when I want to ORDER BY the messages.read row. My code is as follows:

   SELECT
         MAX(messages.ID) as maxID,
         messages.from,
         messages.read,
               users.userName
      FROM
         messages
      LEFT OUTER JOIN
         users
              ON
              users.ID = messages.from
      WHERE
       messages.to = ?
      GROUP BY
       messages.from
      ORDER BY
             messages.read ASC,
       maxID DESC

Now, messages.read returns the value of the row of the first message that the user send. But I need the value of the newest (highest ID) that the user send.
I know that GROUP BY groups by the first in the table, so how can I get around doing this?

Thank you very much in advance,
Fischer

Body:
I know that GROUP BY groups by the
  first in the table, so how can I get
  around doing this?

That's not actually true.  It will return a random row.  In practice, this is often the first row in primary key order, but there is no guarantee.  Databases other than MySQL do not allow this practice and will raise an error.

Anyway, one way to retrieve the highest ID of unread messages is by joining the messages table twice.  The second join only looks for unread messages.  For example:

SELECT  max(msg.ID) as MaxID
,       messages.from
,       max(unread.ID) as MaxUnreadID
,       users.userName
FROM    users
join    messages msg
on      users.ID = msg.from
        and messages.to = ?
left join
        messages unread
on      users.ID = unread.from
        and messages.to = ?
        and unread.read = 0
GROUP BY
        users.ID
,       users.userName


问:
Change Camera Zoom based on Radius Google Maps iOS SDK
I am working on an app that displays certain markers based on a radius around your current location. The radius is between 100 - 5000 meters. I change the radius with an UISlider and redraw the GMSCircle.

My problem is that I want to update the camera zoom according to the slider value but I don't have an idea by which scale to divide.

This is how I create the camera in the viewDidLoad method where the initial zoom value is 15:

```<code>GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:locationManager.location.coordinate.latitude longitude:locationManager.location.coordinate.longitude  zoom:15];
</code>```

Here's a screenshot of what I am working on.

Does anyone know what scale should I use to move the zoom accordingly?

Thanks a lot!

Granit

答:
I just created extension for GMSCameraUpdate.

input parameters:

coordinate - your center coordinate

radius - radius of visible bounds

```<code>extension GMSCameraUpdate {

    static func fit(coordinate: CLLocationCoordinate2D, radius: Double) -> GMSCameraUpdate {
        var leftCoordinate = coordinate
        var rigthCoordinate = coordinate

        let region = MKCoordinateRegionMakeWithDistance(coordinate, radius, radius)
        let span = region.span

        leftCoordinate.latitude = coordinate.latitude - span.latitudeDelta
        leftCoordinate.longitude = coordinate.longitude - span.longitudeDelta
        rigthCoordinate.latitude = coordinate.latitude + span.latitudeDelta
        rigthCoordinate.longitude = coordinate.longitude + span.longitudeDelta

        let bounds = GMSCoordinateBounds(coordinate: leftCoordinate, coordinate: rigthCoordinate)
        let update = GMSCameraUpdate.fit(bounds, withPadding: -15.0)

        return update
    }

}
</code>```

Body:
I am working on an app that displays certain markers based on a radius around your current location. The radius is between 100 - 5000 meters. I change the radius with an UISlider and redraw the GMSCircle.

My problem is that I want to update the camera zoom according to the slider value but I don't have an idea by which scale to divide.

This is how I create the camera in the viewDidLoad method where the initial zoom value is 15:

GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:locationManager.location.coordinate.latitude longitude:locationManager.location.coordinate.longitude  zoom:15];

Here's a screenshot of what I am working on.

Does anyone know what scale should I use to move the zoom accordingly?

Thanks a lot!

Granit

Body:
I just created extension for GMSCameraUpdate.

input parameters:

coordinate - your center coordinate

radius - radius of visible bounds

extension GMSCameraUpdate {

    static func fit(coordinate: CLLocationCoordinate2D, radius: Double) -> GMSCameraUpdate {
        var leftCoordinate = coordinate
        var rigthCoordinate = coordinate

        let region = MKCoordinateRegionMakeWithDistance(coordinate, radius, radius)
        let span = region.span

        leftCoordinate.latitude = coordinate.latitude - span.latitudeDelta
        leftCoordinate.longitude = coordinate.longitude - span.longitudeDelta
        rigthCoordinate.latitude = coordinate.latitude + span.latitudeDelta
        rigthCoordinate.longitude = coordinate.longitude + span.longitudeDelta

        let bounds = GMSCoordinateBounds(coordinate: leftCoordinate, coordinate: rigthCoordinate)
        let update = GMSCameraUpdate.fit(bounds, withPadding: -15.0)

        return update
    }

}


问:
How to create 2d array with numpy random.choice for every rows?
I'm trying to create a 2d array (which is a six column and lots of rows) with numpy random choice with unique values between 1 and 50 for every row not all of the array

```<code>np.sort(np.random.choice(np.arange(1,50),size=(100,6),replace=False))
</code>```

But this raises an error.

```<code>ValueError: Cannot take a larger sample than population when 'replace=False'
</code>```

Is it possible to make this with an one liner without a loop

Edit

Okey i get the answer.

These are the results with jupyter %time cellmagic

```<code>#@James' solution
np.stack([np.random.choice(np.arange(1,50),size=6,replace=False) for i in range(1_000_000)])
Wall time: 25.1 s

#@Divakar's solution
np.random.rand(1_000_000, 50).argpartition(6,axis=1)[:,:6]+1
Wall time: 1.36 s

#@CoryKramer's solution
np.array([np.random.choice(np.arange(1, 50), size=6, replace=False) for _ in range(1_000_000)])
Wall time: 25.5 s
</code>```

I changed dtypes of np.empty and np.random.randint on @Paul Panzer's solution because it was not working on my pc.

```<code>3.6.0 |Anaconda custom (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC v.1900 64 bit (AMD64)]
</code>```

Fastest one is

```<code>def pp(n):
    draw = np.empty((n, 6), dtype=np.int64)
    # generating random numbers is expensive, so draw a large one and
    # make six out of one
    draw[:, 0] = np.random.randint(0, 50*49*48*47*46*45, (n,),dtype=np.uint64)
    draw[:, 1:] = np.arange(50, 45, -1)
    draw = np.floor_divide.accumulate(draw, axis=-1)
    draw[:, :-1] -= draw[:, 1:] * np.arange(50, 45, -1)
    # map the shorter ranges (:49, :48, :47) to the non-occupied
    # positions; this amounts to incrementing for each number on the
    # left that is not larger. the nasty bit: if due to incrementing
    # new numbers on the left are "overtaken" then for them we also
    # need to increment.
    for i in range(1, 6):
        coll = np.sum(draw[:, :i] <= draw[:, i, None], axis=-1)
        collidx = np.flatnonzero(coll)
        if collidx.size == 0:
            continue
        coll = coll[collidx]
        tot = coll
        while True:
            draw[collidx, i] += coll
            coll = np.sum(draw[collidx, :i] <= draw[collidx, i, None],  axis=-1)
            relidx = np.flatnonzero(coll > tot)
            if relidx.size == 0:
                break
            coll, tot = coll[relidx]-tot[relidx], coll[relidx]
            collidx = collidx[relidx]

    return draw + 1

#@Paul Panzer' solution
pp(1_000_000)
Wall time: 557 ms
</code>```

Thank you all.

答:
Here is a constructive approach, draw first (50 choices), second (49 choices) etc. For large sets it's quite competitive (pp in table):

```<code># n = 10
# pp                    0.18564210 ms
# Divakar               0.01960790 ms
# James                 0.20074140 ms
# CK                    0.17823420 ms
# n = 1000
# pp                    0.80046050 ms
# Divakar               1.31817130 ms
# James                18.93511460 ms
# CK                   20.83670820 ms
# n = 1000000
# pp                  655.32905590 ms
# Divakar            1352.44713990 ms
# James             18471.08987370 ms
# CK                18369.79808050 ms
# pp     checking plausibility...
#     var (exp obs) 208.333333333 208.363840259
#     mean (exp obs) 25.5 25.5064865
# Divakar     checking plausibility...
#     var (exp obs) 208.333333333 208.21113972
#     mean (exp obs) 25.5 25.499471
# James     checking plausibility...
#     var (exp obs) 208.333333333 208.313436938
#     mean (exp obs) 25.5 25.4979035
# CK     checking plausibility...
#     var (exp obs) 208.333333333 208.169585249
#     mean (exp obs) 25.5 25.49
</code>```

Code including benchmarking. Algo is a bit complicated because mapping to free spots is hairy:

```<code>import numpy as np
import types
from timeit import timeit

def f_pp(n):
    draw = np.empty((n, 6), dtype=int)
    # generating random numbers is expensive, so draw a large one and
    # make six out of one
    draw[:, 0] = np.random.randint(0, 50*49*48*47*46*45, (n,))
    draw[:, 1:] = np.arange(50, 45, -1)
    draw = np.floor_divide.accumulate(draw, axis=-1)
    draw[:, :-1] -= draw[:, 1:] * np.arange(50, 45, -1)
    # map the shorter ranges (:49, :48, :47) to the non-occupied
    # positions; this amounts to incrementing for each number on the
    # left that is not larger. the nasty bit: if due to incrementing
    # new numbers on the left are "overtaken" then for them we also
    # need to increment.
    for i in range(1, 6):
        coll = np.sum(draw[:, :i] <= draw[:, i, None], axis=-1)
        collidx = np.flatnonzero(coll)
        if collidx.size == 0:
            continue
        coll = coll[collidx]
        tot = coll
        while True:
            draw[collidx, i] += coll
            coll = np.sum(draw[collidx, :i] <= draw[collidx, i, None], axis=-1)
            relidx = np.flatnonzero(coll > tot)
            if relidx.size == 0:
                break
            coll, tot = coll[relidx]-tot[relidx], coll[relidx]
            collidx = collidx[relidx]

    return draw + 1

def check_result(draw, name):
    print(name[2:], '    checking plausibility...')
    import scipy.stats
    assert all(len(set(row)) == 6 for row in draw)
    assert len(set(draw.ravel())) == 50
    print('    var (exp obs)', scipy.stats.uniform(0.5, 50).var(), draw.var())
    print('    mean (exp obs)', scipy.stats.uniform(0.5, 50).mean(), draw.mean())

def f_Divakar(n):
    return np.random.rand(n, 50).argpartition(6,axis=1)[:,:6]+1

def f_James(n):
    return np.stack([np.random.choice(np.arange(1,51),size=6,replace=False) for i in range(n)])

def f_CK(n):
    return np.array([np.random.choice(np.arange(1, 51), size=6, replace=False) for _ in range(n)])

for n in (10, 1_000, 1_000_000):
    print(f'n = {n}')
    for name, func in list(globals().items()):
        if not name.startswith('f_') or not isinstance(func, types.FunctionType):
            continue
        try:
            print("{:16s}{:16.8f} ms".format(name[2:], timeit(
                'f(n)', globals={'f':func, 'n':n}, number=10)*100))
        except:
            print("{:16s} apparently failed".format(name[2:]))
    if(n >= 10000):
        for name, func in list(globals().items()):
            if name.startswith('f_') and isinstance(func, types.FunctionType):

                check_result(func(n), name)
</code>```

Body:
I'm trying to create a 2d array (which is a six column and lots of rows) with numpy random choice with unique values between 1 and 50 for every row not all of the array

np.sort(np.random.choice(np.arange(1,50),size=(100,6),replace=False))

But this raises an error.

ValueError: Cannot take a larger sample than population when 'replace=False'

Is it possible to make this with an one liner without a loop

Edit

Okey i get the answer.

These are the results with jupyter %time cellmagic

#@James' solution
np.stack([np.random.choice(np.arange(1,50),size=6,replace=False) for i in range(1_000_000)])
Wall time: 25.1 s

#@Divakar's solution
np.random.rand(1_000_000, 50).argpartition(6,axis=1)[:,:6]+1
Wall time: 1.36 s

#@CoryKramer's solution
np.array([np.random.choice(np.arange(1, 50), size=6, replace=False) for _ in range(1_000_000)])
Wall time: 25.5 s

I changed dtypes of np.empty and np.random.randint on @Paul Panzer's solution because it was not working on my pc.

3.6.0 |Anaconda custom (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC v.1900 64 bit (AMD64)]

Fastest one is

def pp(n):
    draw = np.empty((n, 6), dtype=np.int64)
    # generating random numbers is expensive, so draw a large one and
    # make six out of one
    draw[:, 0] = np.random.randint(0, 50*49*48*47*46*45, (n,),dtype=np.uint64)
    draw[:, 1:] = np.arange(50, 45, -1)
    draw = np.floor_divide.accumulate(draw, axis=-1)
    draw[:, :-1] -= draw[:, 1:] * np.arange(50, 45, -1)
    # map the shorter ranges (:49, :48, :47) to the non-occupied
    # positions; this amounts to incrementing for each number on the
    # left that is not larger. the nasty bit: if due to incrementing
    # new numbers on the left are "overtaken" then for them we also
    # need to increment.
    for i in range(1, 6):
        coll = np.sum(draw[:, :i] <= draw[:, i, None], axis=-1)
        collidx = np.flatnonzero(coll)
        if collidx.size == 0:
            continue
        coll = coll[collidx]
        tot = coll
        while True:
            draw[collidx, i] += coll
            coll = np.sum(draw[collidx, :i] <= draw[collidx, i, None],  axis=-1)
            relidx = np.flatnonzero(coll > tot)
            if relidx.size == 0:
                break
            coll, tot = coll[relidx]-tot[relidx], coll[relidx]
            collidx = collidx[relidx]

    return draw + 1

#@Paul Panzer' solution
pp(1_000_000)
Wall time: 557 ms

Thank you all.

Body:
Here is a constructive approach, draw first (50 choices), second (49 choices) etc. For large sets it's quite competitive (pp in table):

# n = 10
# pp                    0.18564210 ms
# Divakar               0.01960790 ms
# James                 0.20074140 ms
# CK                    0.17823420 ms
# n = 1000
# pp                    0.80046050 ms
# Divakar               1.31817130 ms
# James                18.93511460 ms
# CK                   20.83670820 ms
# n = 1000000
# pp                  655.32905590 ms
# Divakar            1352.44713990 ms
# James             18471.08987370 ms
# CK                18369.79808050 ms
# pp     checking plausibility...
#     var (exp obs) 208.333333333 208.363840259
#     mean (exp obs) 25.5 25.5064865
# Divakar     checking plausibility...
#     var (exp obs) 208.333333333 208.21113972
#     mean (exp obs) 25.5 25.499471
# James     checking plausibility...
#     var (exp obs) 208.333333333 208.313436938
#     mean (exp obs) 25.5 25.4979035
# CK     checking plausibility...
#     var (exp obs) 208.333333333 208.169585249
#     mean (exp obs) 25.5 25.49

Code including benchmarking. Algo is a bit complicated because mapping to free spots is hairy:

import numpy as np
import types
from timeit import timeit

def f_pp(n):
    draw = np.empty((n, 6), dtype=int)
    # generating random numbers is expensive, so draw a large one and
    # make six out of one
    draw[:, 0] = np.random.randint(0, 50*49*48*47*46*45, (n,))
    draw[:, 1:] = np.arange(50, 45, -1)
    draw = np.floor_divide.accumulate(draw, axis=-1)
    draw[:, :-1] -= draw[:, 1:] * np.arange(50, 45, -1)
    # map the shorter ranges (:49, :48, :47) to the non-occupied
    # positions; this amounts to incrementing for each number on the
    # left that is not larger. the nasty bit: if due to incrementing
    # new numbers on the left are "overtaken" then for them we also
    # need to increment.
    for i in range(1, 6):
        coll = np.sum(draw[:, :i] <= draw[:, i, None], axis=-1)
        collidx = np.flatnonzero(coll)
        if collidx.size == 0:
            continue
        coll = coll[collidx]
        tot = coll
        while True:
            draw[collidx, i] += coll
            coll = np.sum(draw[collidx, :i] <= draw[collidx, i, None], axis=-1)
            relidx = np.flatnonzero(coll > tot)
            if relidx.size == 0:
                break
            coll, tot = coll[relidx]-tot[relidx], coll[relidx]
            collidx = collidx[relidx]

    return draw + 1

def check_result(draw, name):
    print(name[2:], '    checking plausibility...')
    import scipy.stats
    assert all(len(set(row)) == 6 for row in draw)
    assert len(set(draw.ravel())) == 50
    print('    var (exp obs)', scipy.stats.uniform(0.5, 50).var(), draw.var())
    print('    mean (exp obs)', scipy.stats.uniform(0.5, 50).mean(), draw.mean())

def f_Divakar(n):
    return np.random.rand(n, 50).argpartition(6,axis=1)[:,:6]+1

def f_James(n):
    return np.stack([np.random.choice(np.arange(1,51),size=6,replace=False) for i in range(n)])

def f_CK(n):
    return np.array([np.random.choice(np.arange(1, 51), size=6, replace=False) for _ in range(n)])

for n in (10, 1_000, 1_000_000):
    print(f'n = {n}')
    for name, func in list(globals().items()):
        if not name.startswith('f_') or not isinstance(func, types.FunctionType):
            continue
        try:
            print("{:16s}{:16.8f} ms".format(name[2:], timeit(
                'f(n)', globals={'f':func, 'n':n}, number=10)*100))
        except:
            print("{:16s} apparently failed".format(name[2:]))
    if(n >= 10000):
        for name, func in list(globals().items()):
            if name.startswith('f_') and isinstance(func, types.FunctionType):

                check_result(func(n), name)


问:
Error: [ng:areq] Argument 'ControllerName' is not a function, got undefined
In app.js I have:

```<code>(function(){
    var app = angular.module("myApp", []);
})();
</code>```

in process.js  which is included after app.js I have:

```<code>(function(){
    app.controller('ProcessController', ['$http', function($http){
        this.something = "Test"
    }]);
});
</code>```

and in my HTML file I have a div

```<code><html class="no-js" lang="en" ng-app="myApp">
...
   <div class="row" ng-controller="ProcessController">
</code>```

This is throwing an error in my console:

```<code>Error: [ng:areq] Argument 'ProcessController' is not a function, got undefined
</code>```

I'm pretty new to angular and have never used multiple files like this before. What am I doing wrong?

答:
'use strict' ; Defines that JavaScript code should be executed in "strict mode".
so it needs declaration first then definition . So in case you have declared the module added in app.js & added js to the index.html but not injected in the mainApp module , you have chances for ngareq ControllerName is not a function or undefined.
Hope so it would help .</p>

Body:
In app.js I have:

(function(){
    var app = angular.module("myApp", []);
})();

in process.js  which is included after app.js I have:

(function(){
    app.controller('ProcessController', ['$http', function($http){
        this.something = "Test"
    }]);
});

and in my HTML file I have a div

...

This is throwing an error in my console:

Error: [ng:areq] Argument 'ProcessController' is not a function, got undefined

I'm pretty new to angular and have never used multiple files like this before. What am I doing wrong?


问:
How to check if a file exists in a shell script
I'd like to write a shell script which checks if a certain file, archived_sensor_data.json, exists, and if so, deletes it. Following http://www.cyberciti.biz/tips/find-out-if-file-exists-with-conditional-expressions.html, I've tried the following:

```<code>[-e archived_sensor_data.json] && rm archived_sensor_data.json
</code>```

However, this throws an error

```<code>[-e: command not found
</code>```

when I try to run the resulting test_controller script using the ./test_controller command. What is wrong with the code?

答:
Here is an alternative method using ls:

```<code>(ls x.txt && echo yes) || echo no
</code>```

If you want to hide any output from ls so you only see yes or no, redirect stdout and stderr to /dev/null:

```<code>(ls x.txt >> /dev/null 2>&1 && echo yes) || echo no
</code>```

Body:
I'd like to write a shell script which checks if a certain file, archived_sensor_data.json, exists, and if so, deletes it. Following http://www.cyberciti.biz/tips/find-out-if-file-exists-with-conditional-expressions.html, I've tried the following:

[-e archived_sensor_data.json] && rm archived_sensor_data.json

However, this throws an error

[-e: command not found

when I try to run the resulting test_controller script using the ./test_controller command. What is wrong with the code?

Body:
Here is an alternative method using ls:

(ls x.txt && echo yes) || echo no

If you want to hide any output from ls so you only see yes or no, redirect stdout and stderr to /dev/null:

(ls x.txt >> /dev/null 2>&1 && echo yes) || echo no


问:
Converting a real into an integer in lisp
How can I convert a real number to an integer in LISP?

Is there any primitive function?

Example:

3.0 => 3

答:
Other option is TRUNCATE. Examples</p>

```<code>> (truncate 2.2)
=> 2
   0.20000005

> (truncate 2.9)
=> 2
   0.9000001
</code>```

Body:
Other option is TRUNCATE. Examples

> (truncate 2.2)
=> 2
   0.20000005

> (truncate 2.9)
=> 2
   0.9000001


问:
Zoom function in d3js Scatter plot chart
I am trying to do zoom on axis in scatter plot chart,this is what I have tried

```<code>var zoom = d3.zoom()
    .scaleExtent([1, 5])
    .extent([100, 100], [width - 100, height - 100])
    .on("zoom", zoomed);

    var gX;
    var gY;
xScale = d3.scaleLinear().range([0, width])
yScale = d3.scaleLinear().range([height, 0])

    function zoomed() {
        svg.selectAll(".charts")
            .attr("transform", d3.event.transform);
        d3.selectAll('.dot').style("stroke-width", 2 / d3.event.transform.k);
        gX.call(xAxis.scale(d3.event.transform.rescaleX(xScale)));
        gY.call(yAxis.scale(d3.event.transform.rescaleY(yScale)));
    }
</code>```

and I appended gX and gY like below

```<code>gX = svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);
        gY = svg.append("g")
             .attr("class", "axis axis--y")
             .call(yAxis)
</code>```

When I do zoom on circle width is getting zoomed not axis, I am guessing something i am doing wrong on gX.call & gY.call which I couldn't figure. Any suggestions??

答:
I did something like this....

Call zoom on select like this

```<code>var svg = d3.select("div#ScatterPlot svg").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
    .call(d3.zoom().on("zoom", zoom));

var gX = svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis)
var gY = svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)

var circles = svg.selectAll(".dot")
          .data(data)
        .enter().append("circle")
        .attr("class", "dot")....

function zoom() {
            gX.call(xAxis.scale(d3.event.transform.rescaleX(xScale)));
            gY.call(yAxis.scale(d3.event.transform.rescaleY(yScale)));

            var new_XScale = d3.event.transform.rescaleX(xScale);
            var new_yScale = d3.event.transform.rescaleY(yScale);

            circles.attr("cx", function (d) { return new_XScale(d.xAxisValue) });
            circles.attr("cy", function (d) { return new_yScale(d.yAxisValue) });
        }
</code>```

Body:
I am trying to do zoom on axis in scatter plot chart,this is what I have tried

var zoom = d3.zoom()
    .scaleExtent([1, 5])
    .extent([100, 100], [width - 100, height - 100])
    .on("zoom", zoomed);

    var gX;
    var gY;
xScale = d3.scaleLinear().range([0, width])
yScale = d3.scaleLinear().range([height, 0])

    function zoomed() {
        svg.selectAll(".charts")
            .attr("transform", d3.event.transform);
        d3.selectAll('.dot').style("stroke-width", 2 / d3.event.transform.k);
        gX.call(xAxis.scale(d3.event.transform.rescaleX(xScale)));
        gY.call(yAxis.scale(d3.event.transform.rescaleY(yScale)));
    }

and I appended gX and gY like below

gX = svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);
        gY = svg.append("g")
             .attr("class", "axis axis--y")
             .call(yAxis)

When I do zoom on circle width is getting zoomed not axis, I am guessing something i am doing wrong on gX.call & gY.call which I couldn't figure. Any suggestions??

Body:
I did something like this....

Call zoom on select like this

var svg = d3.select("div#ScatterPlot svg").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
    .call(d3.zoom().on("zoom", zoom));

var gX = svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis)
var gY = svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)

var circles = svg.selectAll(".dot")
          .data(data)
        .enter().append("circle")
        .attr("class", "dot")....

function zoom() {
            gX.call(xAxis.scale(d3.event.transform.rescaleX(xScale)));
            gY.call(yAxis.scale(d3.event.transform.rescaleY(yScale)));

            var new_XScale = d3.event.transform.rescaleX(xScale);
            var new_yScale = d3.event.transform.rescaleY(yScale);

            circles.attr("cx", function (d) { return new_XScale(d.xAxisValue) });
            circles.attr("cy", function (d) { return new_yScale(d.yAxisValue) });
        }


问:
How to use goto across multiple functions
I am trying to exit a program without using exit(). I have come up with a very convoluted and dirty solution (I am a Beginner).
I would like to use if statements and if it is true, then I would like to use goto to go the main function and then return 3; and end the program.

Here is a bit of code:

```<code>    FILE *filepointer;

      char * line = NULL;
      size_t len = 0;
      size_t read;
      int linecount = 0;
      filepointer = fopen(filename, "r");
      if (filepointer == NULL)
        {
          printf("[ERR] Could not read file %s.\n",filename );
          goto FILE_ERROR;
        }
    ...
    int main(){
    ...
    FILE_ERROR: return 3;

}
</code>```

This however does not work as I cannot get jump between functions because I get undeclared Label as an error. Is there any way I can exclude exit() from my program and still end it returning a certain value. If there is a better solution, please let me know

答:
By design, a goto cannot jump from one function to another.  It can only be used to jump within a given function.

There are ways to jump between functions, but doing so is not only very poor design but also dangerous as it is very easy to put your program in an invalid state.

The proper way to handle this is to have your function return a specific value (or set of values) to indicate an error.  Then the calling function would check for one of those error values and act accordingly.

For example:

```<code>int readFile(char *filename)
{
  FILE *filepointer;

  char * line = NULL;
  size_t len = 0;
  size_t read;
  int linecount = 0;
  filepointer = fopen(filename, "r");
  if (filepointer == NULL)
    {
      // add strerror(error) to the error message to know why fopen failed
      printf("[ERR] Could not read file %s: %s.\n",filename, strerror(errno) );
      // error completion
      return 0;
    }
  ...
  // successful completion
  return 1;
}

int main(){
   ...
   if (readFile("myfile") == 0) {
       return 3;
   }
   ...
}
</code>```

Body:
I am trying to exit a program without using exit(). I have come up with a very convoluted and dirty solution (I am a Beginner).
I would like to use if statements and if it is true, then I would like to use goto to go the main function and then return 3; and end the program.

Here is a bit of code:

    FILE *filepointer;

      char * line = NULL;
      size_t len = 0;
      size_t read;
      int linecount = 0;
      filepointer = fopen(filename, "r");
      if (filepointer == NULL)
        {
          printf("[ERR] Could not read file %s.\n",filename );
          goto FILE_ERROR;
        }
    ...
    int main(){
    ...
    FILE_ERROR: return 3;

}

This however does not work as I cannot get jump between functions because I get undeclared Label as an error. Is there any way I can exclude exit() from my program and still end it returning a certain value. If there is a better solution, please let me know

Body:
By design, a goto cannot jump from one function to another.  It can only be used to jump within a given function.

There are ways to jump between functions, but doing so is not only very poor design but also dangerous as it is very easy to put your program in an invalid state.

The proper way to handle this is to have your function return a specific value (or set of values) to indicate an error.  Then the calling function would check for one of those error values and act accordingly.

For example:

int readFile(char *filename)
{
  FILE *filepointer;

  char * line = NULL;
  size_t len = 0;
  size_t read;
  int linecount = 0;
  filepointer = fopen(filename, "r");
  if (filepointer == NULL)
    {
      // add strerror(error) to the error message to know why fopen failed
      printf("[ERR] Could not read file %s: %s.\n",filename, strerror(errno) );
      // error completion
      return 0;
    }
  ...
  // successful completion
  return 1;
}

int main(){
   ...
   if (readFile("myfile") == 0) {
       return 3;
   }
   ...
}


问:
C++ - enum vs. const vs. #define
At the end of the article here: http://www.learncpp.com/cpp-tutorial/45-enumerated-types/, it mentions the following:

Finally, as with constant variables, enumerated types show up in the debugger, making them more useful than #defined values in this regard.

How is the bold sentence above achieved?

Thanks.

答:
The compiler stores enum information in the binary when the program is compiled with certain options.

When a variable is of a enum type, a debugger can show the enum name. This is best shown with an example:

```<code>enum E {
    ONE_E = 1,
};

int main(void)
{
    enum E e = 1;

    return 0;
}
</code>```

If you compile that with gcc -g you can try out the following in gdb:

```<code>Reading symbols from test...done.
(gdb) b main
Breakpoint 1 at 0x804839a: file test.c, line 8.
(gdb) run
Starting program: test

Breakpoint 1, main () at test.c:7
7               enum E e = 1;
(gdb) next
9               return 0;
(gdb) print e
$1 = ONE_E
(gdb)
</code>```

If you used a define, you would not have a proper type to give e, and would have to use an integer. In that case, the compiler would print 1 instead of ONE_E.

The -g flag asks gdb to add debugging information to the binary. You can even see that it is there by issuing:

```<code>xxd test | grep ONE_E
</code>```

I don't think that this will work in all architectures, though.

Title: C++ - enum vs. const vs. #define

Body:
The compiler stores enum information in the binary when the program is compiled with certain options.

When a variable is of a enum type, a debugger can show the enum name. This is best shown with an example:

enum E {
    ONE_E = 1,
};

int main(void)
{
    enum E e = 1;

    return 0;
}

If you compile that with gcc -g you can try out the following in gdb:

Reading symbols from test...done.
(gdb) b main
Breakpoint 1 at 0x804839a: file test.c, line 8.
(gdb) run
Starting program: test

Breakpoint 1, main () at test.c:7
7               enum E e = 1;
(gdb) next
9               return 0;
(gdb) print e
$1 = ONE_E
(gdb)

If you used a define, you would not have a proper type to give e, and would have to use an integer. In that case, the compiler would print 1 instead of ONE_E.

The -g flag asks gdb to add debugging information to the binary. You can even see that it is there by issuing:

xxd test | grep ONE_E

I don't think that this will work in all architectures, though.


问:
getCurrentPlace onResult Does Not Return Results
I have been trying to test the getCurrentPlace() method for the Google Places API. When I first tested it a few times, it was working no problem, but now all of a sudden it has stopped working. I've uninstalled the app, deleted the code and re-pasted from the documentation, closed Android Studio. I have no idea what is going wrong and the logs aren't erring, they just do not log what used to log.

```<code>View.OnClickListener getNearbyPlaces = new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        places = new FindNearbyPlaces();
        placesArray = new ArrayList<>();
        try {
            placesArray = places.findNearbyPlaces(mCurrentLocation);
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (PlacesAttributes place : placesArray) {
            Log.i("Name: ", place.getName());
            Log.i("Lat: ", String.valueOf(place.getLat()));
            Log.i("Lng: ", String.valueOf(place.getLng()));
        }

        if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
                .getCurrentPlace(mGoogleApiClient, null);
        result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
            @Override
            public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
                Log.i("help", "");
                for (PlaceLikelihood placeLikelihood : likelyPlaces) {
                    Log.i("Place", String.format("Place '%s' has likelihood: %g",
                            placeLikelihood.getPlace().getName(),
                            placeLikelihood.getLikelihood()));
                }
                likelyPlaces.release();
            }
        });

    }
};
</code>```

That is the code chunk that I have. The first three log statements in the beginning run their course, but the log statements in onResult do not, not even the Log.i("help", ""). I had the beginning log statements where they are when it did work, so they shouldn't be an issue.

答:
You should check your connection.</p>

```<code> GoogleApiClient mGoogleApiClient = new GoogleApiClient
            .Builder(getContext())
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .build();

    mGoogleApiClient.connect();
</code>```

Body:
I have been trying to test the getCurrentPlace() method for the Google Places API. When I first tested it a few times, it was working no problem, but now all of a sudden it has stopped working. I've uninstalled the app, deleted the code and re-pasted from the documentation, closed Android Studio. I have no idea what is going wrong and the logs aren't erring, they just do not log what used to log.

View.OnClickListener getNearbyPlaces = new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        places = new FindNearbyPlaces();
        placesArray = new ArrayList<>();
        try {
            placesArray = places.findNearbyPlaces(mCurrentLocation);
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (PlacesAttributes place : placesArray) {
            Log.i("Name: ", place.getName());
            Log.i("Lat: ", String.valueOf(place.getLat()));
            Log.i("Lng: ", String.valueOf(place.getLng()));
        }

        if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
                .getCurrentPlace(mGoogleApiClient, null);
        result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
            @Override
            public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
                Log.i("help", "");
                for (PlaceLikelihood placeLikelihood : likelyPlaces) {
                    Log.i("Place", String.format("Place '%s' has likelihood: %g",
                            placeLikelihood.getPlace().getName(),
                            placeLikelihood.getLikelihood()));
                }
                likelyPlaces.release();
            }
        });

    }
};

That is the code chunk that I have. The first three log statements in the beginning run their course, but the log statements in onResult do not, not even the Log.i("help", ""). I had the beginning log statements where they are when it did work, so they shouldn't be an issue.

Body:
You should check your connection.

 GoogleApiClient mGoogleApiClient = new GoogleApiClient
            .Builder(getContext())
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .build();

    mGoogleApiClient.connect();


问:
Docker two containers stops each others
[EDIT]: It seems to be a memory problem, I have increased the memory of the docker and now I can run the containers together. Thank you very much for all yours (very quickly) answers

I have created two containers(from 2 different images) with liferay instance on them, they are linked at the same postgres container but in a different DB.
The first container is published on port 8080 and the second on 8081.

Everything works fine except for one thing…if ContainerA is running and I start ContainerB, the ContainerA stops(and viceversa).

Searching on google I didn’t find nothing.
Someone has any idea? I am new about docker…port…etc.

As suggested I used the "docker logs ContainerName" after the Container stops, and this is the message:

WARN  [elasticsearch[Terminatrix][scheduler][T#1]][jvm:173]
  [Terminatrix] [gc][young][248][137] duration [5.9s], collections
  [1]/[6.3s], total [5.9s]/[12s], memory [688.1mb]->[479.4mb]/[910.5mb],
  all_pools {[young] [213.3mb]->[2.6mb]/[219.5mb]}{[survivor]
  [33.9mb]->[34.3mb]/[61mb]}{[old] [440.8mb]->[442.4mb]/[683mb]}

答:
Yes its possible to connect to multiple container to one db container but shared volume should be different.

It explained in this thread

Possible to run two instances of docker containers on one mysql database container?

Title: Docker two containers stops each others


问:
How do I replace a string value with a NULL in PySpark for all my columns in the dataframe?
As an example say I have a df

```<code>from pyspark.sql import Row

row = Row("v", "x", "y", "z")
df = sc.parallelize([
    row("p", 1, 2, 3.0), row("NULL", 3, "NULL", 5.0),
    row("NA", None, 6, 7.0), row(float("Nan"), 8, "NULL", float("NaN"))
]).toDF()
</code>```

Now I want to replace NULL, NA and NaN by pyspark null (None) value. How do I achieve it for multiple columns together.

```<code>from pyspark.sql.functions import when, lit, col
def replace(column, value):
    return when(column != value, column).otherwise(lit(None))

df = df.withColumn("v", replace(col("v"), "NULL"))
df = df.withColumn("v", replace(col("v"), "NaN"))
df = df.withColumn("v", replace(col("v"), "NaN"))
</code>```

Writing this for all columns is something I am trying to avoid as I can have any number of columns in my dataframe.

Appreciate your help. Thanks!

答:
Loop through the columns, construct the column expressions that replace specific strings with null, then select the columns:

df.show()
+----+----+----+---+
|   v|   x|   y|  z|
+----+----+----+---+
|   p|   1|   2|3.0|
|NULL|   3|null|5.0|
|  NA|null|   6|7.0|
| NaN|   8|null|NaN|
+----+----+----+---+

import pyspark.sql.functions as F
cols = [F.when(~F.col(x).isin("NULL", "NA", "NaN"), F.col(x)).alias(x)  for x in df.columns]
df.select(*cols).show()
+----+----+----+----+
|   v|   x|   y|   z|
+----+----+----+----+
|   p|   1|   2| 3.0|
|null|   3|null| 5.0|
|null|null|   6| 7.0|
|null|   8|null|null|
+----+----+----+----+
```

Body:
As an example say I have a df

from pyspark.sql import Row

row = Row("v", "x", "y", "z")
df = sc.parallelize([
    row("p", 1, 2, 3.0), row("NULL", 3, "NULL", 5.0),
    row("NA", None, 6, 7.0), row(float("Nan"), 8, "NULL", float("NaN"))
]).toDF()

Now I want to replace NULL, NA and NaN by pyspark null (None) value. How do I achieve it for multiple columns together.

from pyspark.sql.functions import when, lit, col
def replace(column, value):
    return when(column != value, column).otherwise(lit(None))

df = df.withColumn("v", replace(col("v"), "NULL"))
df = df.withColumn("v", replace(col("v"), "NaN"))
df = df.withColumn("v", replace(col("v"), "NaN"))

Writing this for all columns is something I am trying to avoid as I can have any number of columns in my dataframe.

Appreciate your help. Thanks!


问:
wp7-how to make a thread navigate pages
I want to check for changes in the aplication state every time interval, and if it has changed, to open a window, and  give the user 10 seconds to press on the window, if he does press on the window, then to allow him to navigate freely in the window, and if he doesn't press, to return back to the window before. I thought to implement it with a thread running in the background and waking up every time interval I want. Maybe there is a better way?</p>

答:
I agree with @matt-lacey, this could be dangerous and might result in a bad user experience.

With that said, this might work

```<code> Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        //navigation code here
                    });
</code>```

Title: wp7-how to make a thread navigate pages

Body:
I agree with @matt-lacey, this could be dangerous and might result in a bad user experience.

With that said, this might work

 Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        //navigation code here
                    });


问:
Filter list using dynamic query?
I am trying to filter a list of objects of type Proxy.  Here are it's properties.

```<code>Public Property IP As String
Public Property Port As Integer
Public Property Status As ProxyStatus
Public Property Country As String
Public Property Speed As Integer
</code>```

On the filter form, I have a CheckListBox with country names, and if a country is checked it should be included in the filtered results.

I know I can use hardcoded LINQ likeso:

```<code>Dim result = proxies.Where(Function(p) p.Country = "USA" OR p.Country =
     "Russia")
</code>```

But since my query is dynamic, depending on which countries are checked on the user form, how can I go about this when there are say, 50 countries that I want to include in my results?  I've read about PredicateBuilder but I haven't found an example that includes logical OR's, like if I am filtering by the Status property and I want to include proxies whose Status = Valid OR Status = Unknown?

答:
You can use a collection and Contains:

```<code>Dim countries As String() = SelectedCountries
Dim result = proxies.Where(Function(p) countries.Contains(p.Country))
</code>```

I have used SelectedCountries since i don't know how the user can select the countries. But i'm sure you know to create that array(or list).

Furthermore:

I need a dynamic OR statement, for example Status = Valid OR Status =
  Unknown. This being dependent on the users selection of various
  checkboxes

```<code>Dim allowedStatuses = SelectedStatuses
result = result.Where(Function(p) allowedStatuses.Contains(p.Status))
</code>```

You note that i use result = result.Where not proxies.Where. You can concat multiple Where, which is similar as using OrElse in the first Where. In my opinion this is more readable here.

Title: Filter list using dynamic query?

Body:
I am trying to filter a list of objects of type Proxy.  Here are it's properties.

Public Property IP As String
Public Property Port As Integer
Public Property Status As ProxyStatus
Public Property Country As String
Public Property Speed As Integer

On the filter form, I have a CheckListBox with country names, and if a country is checked it should be included in the filtered results.

I know I can use hardcoded LINQ likeso:

Dim result = proxies.Where(Function(p) p.Country = "USA" OR p.Country =
     "Russia")

But since my query is dynamic, depending on which countries are checked on the user form, how can I go about this when there are say, 50 countries that I want to include in my results?  I've read about PredicateBuilder but I haven't found an example that includes logical OR's, like if I am filtering by the Status property and I want to include proxies whose Status = Valid OR Status = Unknown?

Body:
You can use a collection and Contains:

Dim countries As String() = SelectedCountries
Dim result = proxies.Where(Function(p) countries.Contains(p.Country))

I have used SelectedCountries since i don't know how the user can select the countries. But i'm sure you know to create that array(or list).

Furthermore:

I need a dynamic OR statement, for example Status = Valid OR Status =
  Unknown. This being dependent on the users selection of various
  checkboxes

Dim allowedStatuses = SelectedStatuses
result = result.Where(Function(p) allowedStatuses.Contains(p.Status))

You note that i use result = result.Where not proxies.Where. You can concat multiple Where, which is similar as using OrElse in the first Where. In my opinion this is more readable here.


问:
How can I get my ItemsControl on a xaml form to stretch to fit the grid cell?
I'm trying to get my ItemsControl to expand to fit the grid column it is in.

This is what I'm trying to get:

This is what I'm actually getting:

I've tried StackPanel, ViewBox, WrapControl from Microsoft.ToolKit.Uwp.Controls and setting HorizontalAlignment to stretch.

I've tried converting it to a ListView.

Here's my xaml:

```<code><Page
    x:Class="PaymentScreen.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:PaymentScreen"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    mc:Ignorable="d">

    <Page.DataContext>
        <local:PaymentVM></local:PaymentVM>
    </Page.DataContext>

    <Grid x:Name="MainGrid">

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="0.10*"></ColumnDefinition>
            <ColumnDefinition Width="0.80*"></ColumnDefinition>
            <ColumnDefinition Width="0.10*"></ColumnDefinition>

        </Grid.ColumnDefinitions>

        <Grid.RowDefinitions>
            <RowDefinition Height="0.15*"></RowDefinition>
            <RowDefinition Height="0.30*"></RowDefinition>
            <RowDefinition Height="0.65*"></RowDefinition>

        </Grid.RowDefinitions>

        <Grid Grid.Column="1" Grid.Row="1" HorizontalAlignment="Stretch">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="0.66*"></ColumnDefinition>
                <ColumnDefinition Width="0.33*"></ColumnDefinition>
            </Grid.ColumnDefinitions>

            <Border Grid.Column="0" BorderBrush="Red" BorderThickness="1"></Border>
            <Border Grid.Column="1" BorderBrush="Red" BorderThickness="1"></Border>

                <ItemsControl Grid.Column="0"  Grid.Row="1" ItemsSource="{x:Bind ViewModel.PaymentEntryLines}" >

                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>

                            <StackPanel Orientation="Horizontal"></StackPanel>

                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>

                    <ItemsControl.ItemTemplate>
                        <DataTemplate x:DataType="local:PaymentLine" >
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition></RowDefinition>
                                    <RowDefinition></RowDefinition>
                                    <RowDefinition></RowDefinition>
                                    <RowDefinition></RowDefinition>
                                </Grid.RowDefinitions>

                                <TextBox Grid.Row="0"  Text="To Pay:"></TextBox>
                                <TextBox Grid.Row="1" Text="{x:Bind AmountToPay, Mode=TwoWay}"></TextBox>
                                <TextBox Grid.Row="2" Text="Paid:"></TextBox>
                                <TextBox Grid.Row="3" Text="{x:Bind AmountPaid, Mode=TwoWay}"></TextBox>
                            </Grid>

                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>

            <Border Grid.Column="1" Grid.Row="1">
            <StackPanel>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition></RowDefinition>
                        <RowDefinition></RowDefinition>
                        <RowDefinition></RowDefinition>
                        <RowDefinition></RowDefinition>
                    </Grid.RowDefinitions>

                    <TextBox Grid.Row="0"  Text="To Pay:"></TextBox>
                    <TextBox Grid.Row="1" Text="300.10"></TextBox>
                    <TextBox Grid.Row="2" Text="Paid:"></TextBox>
                    <TextBox Grid.Row="3" Text="500.40"></TextBox>
                </Grid>
            </StackPanel>

            </Border>
        </Grid>

    </Grid>
</Page>
</code>```

答:
What you want is an equivalent of the WPF UniformGrid, which divides its client area evenly among its children: Set Rows="1" and it arrange the children horizontally:

```<code><ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <somens:UniformGrid Rows="1" />
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</code>```

Here is a frequently-recommended UWP implementation of UniformGrid.

Body:
I'm trying to get my ItemsControl to expand to fit the grid column it is in.

This is what I'm trying to get:

This is what I'm actually getting:

I've tried StackPanel, ViewBox, WrapControl from Microsoft.ToolKit.Uwp.Controls and setting HorizontalAlignment to stretch.

I've tried converting it to a ListView.

Here's my xaml:

<Page
    x:Class="PaymentScreen.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:PaymentScreen"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    mc:Ignorable="d">

    <Page.DataContext>
        <local:PaymentVM></local:PaymentVM>
    </Page.DataContext>

    <Grid x:Name="MainGrid">

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="0.10*"></ColumnDefinition>
            <ColumnDefinition Width="0.80*"></ColumnDefinition>
            <ColumnDefinition Width="0.10*"></ColumnDefinition>

        </Grid.ColumnDefinitions>

        <Grid.RowDefinitions>
            <RowDefinition Height="0.15*"></RowDefinition>
            <RowDefinition Height="0.30*"></RowDefinition>
            <RowDefinition Height="0.65*"></RowDefinition>

        </Grid.RowDefinitions>

        <Grid Grid.Column="1" Grid.Row="1" HorizontalAlignment="Stretch">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="0.66*"></ColumnDefinition>
                <ColumnDefinition Width="0.33*"></ColumnDefinition>
            </Grid.ColumnDefinitions>

            <Border Grid.Column="0" BorderBrush="Red" BorderThickness="1"></Border>
            <Border Grid.Column="1" BorderBrush="Red" BorderThickness="1"></Border>

                <ItemsControl Grid.Column="0"  Grid.Row="1" ItemsSource="{x:Bind ViewModel.PaymentEntryLines}" >

                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>

                            <StackPanel Orientation="Horizontal"></StackPanel>

                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>

                    <ItemsControl.ItemTemplate>
                        <DataTemplate x:DataType="local:PaymentLine" >
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition></RowDefinition>
                                    <RowDefinition></RowDefinition>
                                    <RowDefinition></RowDefinition>
                                    <RowDefinition></RowDefinition>
                                </Grid.RowDefinitions>

                                <TextBox Grid.Row="0"  Text="To Pay:"></TextBox>
                                <TextBox Grid.Row="1" Text="{x:Bind AmountToPay, Mode=TwoWay}"></TextBox>
                                <TextBox Grid.Row="2" Text="Paid:"></TextBox>
                                <TextBox Grid.Row="3" Text="{x:Bind AmountPaid, Mode=TwoWay}"></TextBox>
                            </Grid>

                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>

            <Border Grid.Column="1" Grid.Row="1">
            <StackPanel>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition></RowDefinition>
                        <RowDefinition></RowDefinition>
                        <RowDefinition></RowDefinition>
                        <RowDefinition></RowDefinition>
                    </Grid.RowDefinitions>

                    <TextBox Grid.Row="0"  Text="To Pay:"></TextBox>
                    <TextBox Grid.Row="1" Text="300.10"></TextBox>
                    <TextBox Grid.Row="2" Text="Paid:"></TextBox>
                    <TextBox Grid.Row="3" Text="500.40"></TextBox>
                </Grid>
            </StackPanel>

            </Border>
        </Grid>

    </Grid>
</Page>

Body:
What you want is an equivalent of the WPF UniformGrid, which divides its client area evenly among its children: Set Rows="1" and it arrange the children horizontally:

<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <somens:UniformGrid Rows="1" />
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>

Here is a frequently-recommended UWP implementation of UniformGrid.


问:
iOS: TapGestureRecognizer in UIView not fired
I have create an date component and have problems with the GestureRecognizer.

First line is a StackView with labels. If I attach a TapGestureRecognizer it is fired on touch. The following Lines are subviews in a Stackview consisting of a label and an image view. I can add the Recognizer to the subview, to the label or the image view. It never gets fired and I made sure that userInteraction is enabled.

What could be the problem?

Here an example how I add the recognizer:

```<code>func addTap(){
        dayLabel.isUserInteractionEnabled = true
        imageView.isUserInteractionEnabled = true
        isUserInteractionEnabled = true

        tap1 = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))
    tap2 = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))
    tap3 = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))

    dayLabel.addGestureRecognizer(tap1!)
    imageView.addGestureRecognizer(tap2!)
    addGestureRecognizer(tap3!)
    }

    @objc func handleTap(recognizer: UITapGestureRecognizer){
        logger.debug("tap")
        changeSelection()
    }
</code>```

You can find a little demo project boiled down to the problem here: https://github.com/ogezue/datedemo

答:
Problem I can see is your view must be cover with Image and label
and you are adding same   UITapGestureRecognizer to all so   that  is added on last object  say view (which is covered with image and label) so it may not able to get tap event

You need three different objects of  UITapGestureRecognizer you can't add same tap gesture on different views

Hope it may solve your problem

Body:
I have create an date component and have problems with the GestureRecognizer.

First line is a StackView with labels. If I attach a TapGestureRecognizer it is fired on touch. The following Lines are subviews in a Stackview consisting of a label and an image view. I can add the Recognizer to the subview, to the label or the image view. It never gets fired and I made sure that userInteraction is enabled.

What could be the problem?

Here an example how I add the recognizer:

func addTap(){
        dayLabel.isUserInteractionEnabled = true
        imageView.isUserInteractionEnabled = true
        isUserInteractionEnabled = true

        tap1 = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))
    tap2 = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))
    tap3 = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:)))

    dayLabel.addGestureRecognizer(tap1!)
    imageView.addGestureRecognizer(tap2!)
    addGestureRecognizer(tap3!)
    }

    @objc func handleTap(recognizer: UITapGestureRecognizer){
        logger.debug("tap")
        changeSelection()
    }

You can find a little demo project boiled down to the problem here: https://github.com/ogezue/datedemo


问:
Adobe Media Encoder CC2014 SDK / API / WebService
I would like to know if it's currently possible to access AME SDK or API ?

I seen binaries named : - ame_webservice_console.exe - AMEWebService.exe (it's a windows service for media trans-coding)

But there isn't any documentation about that. It is implemented or in the roadmap for developers?

I explain the goal : I would like automatically schedule a transcode from a external project throught the AME Webservice without import manually the file by the menu. That's really interesting to mount an external and centralized render farm cluster.

答:
You can find AMEWinService.exe and AMEWebService.exe inside Adobe Media Encoder CC(inside program files)

The things you have to do

1.Start the AME windows service by AMEWinService -install command in your command line(run as administrator)

2.Start the AME Web service in the same way

3.Now you can enjoy the service at localhost:8080 , if you want change this configuration you can done it at ame_webservice_config.ini file

4.for client side application development you can refer the below document

https://github.com/sp00x/node-adobe-media-encoder-webservice/blob/master/dist/ame-webservice-client.d.ts


问:
Playing sound files one after another in flex AIR code
I have a set of sound clips to be played one after another in a sequence with couple of time interval inbetween.
In my case, its a question - followed by the set of four options.

When I write the below code, all the audop files start together at same time. How can I had time delay inbetween, so that the second clip plays only after the first one is over, and the third one starts playing, only when the second option is over.

I am with Flex AIR AS 3. See code below. Thanks in advance.

```<code>    private function playCoundClips(): void
    {
            //set audio clips

            var questionClipSource : String = "assets/quiz_voiceovers/" + questionCode + "Q.mp3";

            var optionAClipSource : String = "assets/quiz_voiceovers/" + questionCode + "a.mp3";
            var optionBClipSource : String = "assets/quiz_voiceovers/" + questionCode + "b.mp3";
            var optionCClipSource : String = "assets/quiz_voiceovers/" + questionCode + "c.mp3";
            var optionDClipSource : String = "assets/quiz_voiceovers/" + questionCode + "d.mp3";

            playThisClip(questionClipSource);

            playThisClip(optionAClipSource);
            playThisClip(optionBClipSource);

            playThisClip(optionCClipSource);
            playThisClip(optionDClipSource);

    }

    private function playThisClip(clipPath : String) : void
    {
        try
        {
            clipPlayingNow = true;
            var soundReq:URLRequest = new URLRequest(clipPath);
            var sound:Sound = new Sound();
            var soundControl:SoundChannel = new SoundChannel();

            sound.load(soundReq);
            soundControl = sound.play(0, 0);
        }
        catch(err: Error)
        {
            Alert.show(err.getStackTrace());
        }
    }
</code>```

Thanks
Sumit

答:
Time delay, is a very bad idea (in 99% of the case).
Have a look at the SOUND_COMPLETE event (see the doc)
This event is triggered when the sound stops playing.
So, it's now very easy to play sounds in sequence.
A simple example (not tested but idea is here) :

```<code>//declare somewhere a list of sounds to play
var sounds:Array=["sound_a.mp3","sound_a.mp3"];//sounds paths

//this function will play all sounds in the sounds parameter
function playSounds(sounds:Array):void{
  if(!sounds || sounds.length==0){
     //no more sound to play
     //you could dispatch an event here
     return;
  }
  var sound:Sound=new Sound();
  sound.load(new URLRequest(sounds.pop()));
  var soundChannel:SoundChannel = sound.play();
  soundChannel.addEVentListener(Event.SOUND_COMPLETE,function():void{
     soundChannel.removeEventListener(Event.SOUND_COMPLETE,arguments.callee);
     playSounds(sounds);
  });
}
</code>```

Body:
I have a set of sound clips to be played one after another in a sequence with couple of time interval inbetween.
In my case, its a question - followed by the set of four options.

When I write the below code, all the audop files start together at same time. How can I had time delay inbetween, so that the second clip plays only after the first one is over, and the third one starts playing, only when the second option is over.

I am with Flex AIR AS 3. See code below. Thanks in advance.

    private function playCoundClips(): void
    {
            //set audio clips

            var questionClipSource : String = "assets/quiz_voiceovers/" + questionCode + "Q.mp3";

            var optionAClipSource : String = "assets/quiz_voiceovers/" + questionCode + "a.mp3";
            var optionBClipSource : String = "assets/quiz_voiceovers/" + questionCode + "b.mp3";
            var optionCClipSource : String = "assets/quiz_voiceovers/" + questionCode + "c.mp3";
            var optionDClipSource : String = "assets/quiz_voiceovers/" + questionCode + "d.mp3";

            playThisClip(questionClipSource);

            playThisClip(optionAClipSource);
            playThisClip(optionBClipSource);

            playThisClip(optionCClipSource);
            playThisClip(optionDClipSource);

    }

    private function playThisClip(clipPath : String) : void
    {
        try
        {
            clipPlayingNow = true;
            var soundReq:URLRequest = new URLRequest(clipPath);
            var sound:Sound = new Sound();
            var soundControl:SoundChannel = new SoundChannel();

            sound.load(soundReq);
            soundControl = sound.play(0, 0);
        }
        catch(err: Error)
        {
            Alert.show(err.getStackTrace());
        }
    }

Thanks
Sumit

Body:
Time delay, is a very bad idea (in 99% of the case).
Have a look at the SOUND_COMPLETE event (see the doc)
This event is triggered when the sound stops playing.
So, it's now very easy to play sounds in sequence.
A simple example (not tested but idea is here) :

//declare somewhere a list of sounds to play
var sounds:Array=["sound_a.mp3","sound_a.mp3"];//sounds paths

//this function will play all sounds in the sounds parameter
function playSounds(sounds:Array):void{
  if(!sounds || sounds.length==0){
     //no more sound to play
     //you could dispatch an event here
     return;
  }
  var sound:Sound=new Sound();
  sound.load(new URLRequest(sounds.pop()));
  var soundChannel:SoundChannel = sound.play();
  soundChannel.addEVentListener(Event.SOUND_COMPLETE,function():void{
     soundChannel.removeEventListener(Event.SOUND_COMPLETE,arguments.callee);
     playSounds(sounds);
  });
}