问:
UIGestureRecognizer didn't respond swift 3.0
When I pan on the view it didn't react. The following code shows how I setup the gesture recognizer. What's wrong with my code?</p>

```<code>class MyViewController : UIViewController {
    override func loadView() {
        self.view.addGestureRecognizer(gestureRecognizerForSetCardFace)
    }

    var gestureRecognizerForSetCardFace: UIPanGestureRecognizer = {
        let recognizer = UIPanGestureRecognizer(target: self, action: #selector(handleSetGesture(gesture:)))
        recognizer.maximumNumberOfTouches = 1
        return recognizer
    }()

     @objc func handleSetGesture(gesture: UIPanGestureRecognizer){
        print("pan")
    }
}
</code>```

答:
You are overriding loadView. That should only be overridden if you actually create a view and assign it to self.view.

Change your code to override viewDidLoad instead.

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    self.view.addGestureRecognizer(gestureRecognizerForSetCardFace)
}
</code>```

Body:
When I pan on the view it didn't react. The following code shows how I setup the gesture recognizer. What's wrong with my code?

class MyViewController : UIViewController {
    override func loadView() {
        self.view.addGestureRecognizer(gestureRecognizerForSetCardFace)
    }

    var gestureRecognizerForSetCardFace: UIPanGestureRecognizer = {
        let recognizer = UIPanGestureRecognizer(target: self, action: #selector(handleSetGesture(gesture:)))
        recognizer.maximumNumberOfTouches = 1
        return recognizer
    }()

     @objc func handleSetGesture(gesture: UIPanGestureRecognizer){
        print("pan")
    }
}

Body:
You are overriding loadView. That should only be overridden if you actually create a view and assign it to self.view.

Change your code to override viewDidLoad instead.

override func viewDidLoad() {
    super.viewDidLoad()

    self.view.addGestureRecognizer(gestureRecognizerForSetCardFace)
}


来源: stackexchange

问:
PHP - include a php file and also send query parameters
I have to show a page from my php script based on certain conditions. I have an if condition and am doing an "include" if the condition is satisfied.

```<code>if(condition here){
  include "myFile.php?id='$someVar'";
}
</code>```

Now the problem is the server has a file "myFile.php" but I want to make a call to this file with an argument (id) and the value of "id" will change with each call.

Can someone please tell me how to achieve this?
Thanks.

答:
You can use $GLOBALS to solve this issue as well.

```<code>$myvar = "Hey";

include ("test.php");

echo $GLOBALS["myvar"];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have to show a page from my php script based on certain conditions. I have an if condition and am doing an "include" if the condition is satisfied.

if(condition here){
  include "myFile.php?id='$someVar'";
}

Now the problem is the server has a file "myFile.php" but I want to make a call to this file with an argument (id) and the value of "id" will change with each call.

Can someone please tell me how to achieve this?
Thanks.

Body:
You can use $GLOBALS to solve this issue as well.

$myvar = "Hey";

include ("test.php");

echo $GLOBALS["myvar"];


问:
How do I retrieve Composer via Ant?
I'm trying to get make my Ant script retrieve Composer for me. Composer is a dependancy manager for PHP.  According to the doc one needs to run this command: "curl -s https://getcomposer.org/installer | php" which will download Composer.phar into the directory I'm in. This works as intended when running from a terminal.

How do I setup the Ant build file for this? So far I've got this segment for the "composerget" target, but it's doesn't save the file, only output it in my command shell:

```<code>....
<target name="composerget" description="Composer update dependencies">
    <exec executable="curl">
        <arg line="-s" />
            <arg line="https://getcomposer.org/installer"/>
        <arg line="| php" />
    </exec>
  </target>
....
</code>```

Any help is greatly appeciated.

答:
This will download the Composer installer, verify its signature, and run the installer:

```<code>    <target name="composer" description="Install composer">
        <exec executable="wget">
            <arg value="-O" />
            <arg value="composer-setup.sig" />
            <arg value="https://composer.github.io/installer.sig" />
        </exec>
        <exec executable="wget">
            <arg value="-O" />
            <arg value="composer-setup.php" />
            <arg value="https://getcomposer.org/installer" />
        </exec>
        <exec executable="bash">
            <arg value="-c" />
            <arg value="awk '{print $$0 "  composer-setup.php"}' composer-setup.sig | sha384sum --check" />
        </exec>
        <exec executable="php">
            <arg value="composer-setup.php" />
        </exec>
        <exec executable="rm">
            <arg value="composer-setup.php" />
        </exec>
        <exec executable="rm">
            <arg value="composer-setup.sig" />
        </exec>
        <exec executable="mv">
            <arg value="composer.phar" />
            <arg value="composer" />
        </exec>
    </target>
</code>```

If you are using GNU Make, this is the equivalent:

```<code>all: vendor

vendor: composer composer.json composer.lock
        ./composer install

composer:
        wget -O composer-setup.sig https://composer.github.io/installer.sig
        wget -O composer-setup.php https://getcomposer.org/installer
        awk '{print $$0 "  composer-setup.php"}' composer-setup.sig | sha384sum --check
        php composer-setup.php --quiet
        rm composer-setup.*
        mv composer.phar composer
</code>```

Title: How do I retrieve Composer via Ant?

Body:
I'm trying to get make my Ant script retrieve Composer for me. Composer is a dependancy manager for PHP.  According to the doc one needs to run this command: "curl -s https://getcomposer.org/installer | php" which will download Composer.phar into the directory I'm in. This works as intended when running from a terminal.

How do I setup the Ant build file for this? So far I've got this segment for the "composerget" target, but it's doesn't save the file, only output it in my command shell:

....
<target name="composerget" description="Composer update dependencies">
    <exec executable="curl">
        <arg line="-s" />
            <arg line="https://getcomposer.org/installer"/>
        <arg line="| php" />
    </exec>
  </target>
....

Any help is greatly appeciated.

Body:
This will download the Composer installer, verify its signature, and run the installer:

    <target name="composer" description="Install composer">
        <exec executable="wget">
            <arg value="-O" />
            <arg value="composer-setup.sig" />
            <arg value="https://composer.github.io/installer.sig" />
        </exec>
        <exec executable="wget">
            <arg value="-O" />
            <arg value="composer-setup.php" />
            <arg value="https://getcomposer.org/installer" />
        </exec>
        <exec executable="bash">
            <arg value="-c" />
            <arg value="awk '{print $$0 &quot;  composer-setup.php&quot;}' composer-setup.sig | sha384sum --check" />
        </exec>
        <exec executable="php">
            <arg value="composer-setup.php" />
        </exec>
        <exec executable="rm">
            <arg value="composer-setup.php" />
        </exec>
        <exec executable="rm">
            <arg value="composer-setup.sig" />
        </exec>
        <exec executable="mv">
            <arg value="composer.phar" />
            <arg value="composer" />
        </exec>
    </target>

If you are using GNU Make, this is the equivalent:

all: vendor

vendor: composer composer.json composer.lock
        ./composer install

composer:
        wget -O composer-setup.sig https://composer.github.io/installer.sig
        wget -O composer-setup.php https://getcomposer.org/installer
        awk '{print $$0 "  composer-setup.php"}' composer-setup.sig | sha384sum --check
        php composer-setup.php --quiet
        rm composer-setup.*
        mv composer.phar composer


问:
AddOrUpdate works not as expected and produces duplicates
I'm using Code-First DBContext-based EF5 setup.

In DbMigrationsConfiguration.Seed I'm trying to fill DB with default dummy data. To accomplish this task, I use DbSet.AddOrUpdate method.

The simplest code to illustrate my aim:

```<code>j = 0;

var cities = new[]
    {
        "Berlin",
        "Vienna",
        "London",
        "Bristol",
        "Rome",
        "Stockholm",
        "Oslo",
        "Helsinki",
        "Amsterdam",
        "Dublin"
    };
var cityObjects = new City[cities.Length];

foreach (string c in cities)
{
    int id = r.NextDouble() > 0.5 ? 0 : 1;
    var city = new City
        {
            Id = j,
            Name = c,
            Slug = c.ToLowerInvariant(),
            Region = regions[id],
            RegionId = regions[id].Id,
            Reviewed = true
        };
    context.CitySet.AddOrUpdate(cc => cc.Id, city);
    cityObjects[j] = city;
    j++;
}
</code>```

I've tried to use/omit Id field as well as to use Id/Slug property as update selector.

when Update-Database is run, Id field is ignored and the value is generated automatically by SQL Server and DB is filled with duplicates; Slug selector allows duplicates and on subsequent runs produces exceptions (Sequence contains more than one element).

Is AddOrUpdate method intended to work this way? Should I perform upsert by hand?

答:
```<code>var paidOutType = new List<PaidOutType>
                {
                    new PaidOutType { PaidOutTypeID = 1, Code = "001", Description = "PAID OUT 1", PType = "1", Amount = 0, IsSalesSummery = true,DayFrom=1,DayTo=31 },
                    new PaidOutType { PaidOutTypeID = 2, Code = "002", Description = "PAID OUT 2", PType = "1", Amount = 0, IsSalesSummery = true,DayFrom=1,DayTo=31 },
                    new PaidOutType { PaidOutTypeID = 3, Code = "002", Description = "PAID OUT 3", PType = "1", Amount = 0, IsSalesSummery = true,DayFrom=1,DayTo=31 },
                };
                paidOutType.ForEach(u => smartPOSContext.PaidOutType.AddOrUpdate(u));
                smartPOSContext.SaveChanges();
</code>```

Body:
I'm using Code-First DBContext-based EF5 setup.

In DbMigrationsConfiguration.Seed I'm trying to fill DB with default dummy data. To accomplish this task, I use DbSet.AddOrUpdate method.

The simplest code to illustrate my aim:

j = 0;

var cities = new[]
    {
        "Berlin",
        "Vienna",
        "London",
        "Bristol",
        "Rome",
        "Stockholm",
        "Oslo",
        "Helsinki",
        "Amsterdam",
        "Dublin"
    };
var cityObjects = new City[cities.Length];

foreach (string c in cities)
{
    int id = r.NextDouble() > 0.5 ? 0 : 1;
    var city = new City
        {
            Id = j,
            Name = c,
            Slug = c.ToLowerInvariant(),
            Region = regions[id],
            RegionId = regions[id].Id,
            Reviewed = true
        };
    context.CitySet.AddOrUpdate(cc => cc.Id, city);
    cityObjects[j] = city;
    j++;
}

I've tried to use/omit Id field as well as to use Id/Slug property as update selector.

when Update-Database is run, Id field is ignored and the value is generated automatically by SQL Server and DB is filled with duplicates; Slug selector allows duplicates and on subsequent runs produces exceptions (Sequence contains more than one element).

Is AddOrUpdate method intended to work this way? Should I perform upsert by hand?


问:
Using Sinon to test after promise resolution
I have some code that executes after a promise is resolved. I'm trying to spy on a method that should be invoked post-promise resolution but I'm having problems with my tests finishing execution before the call to the spied on method is invoked.

How can I test the call to storage.add is actually being made?

Here's the test:

```<code>"it marks true in storage": function() {
    sinonSandbox.stub(tested, "updateServiceApi", function() {
        return MPromise.resolve();
    });

    var storageStub = sinonSandbox.stub(storage, "add");

    tested._execute();

    expect(
        storageStub.calledWith("name", true)
    ).to.be.true
}
</code>```

And here's the implementation:

```<code>_execute: function() {
    this.updateServiceApi().then(function(){
        // tests finish before this code is executed :(
        storage.add("name", true);
    });
},
</code>```

答:
The problem here is that you've written your test as if _execute is synchronous.

Because of the promises, the expect call will be executed before the storage.add() call is made.

Exactly how you deal with this will be test runner dependent, but the general fix is to add a .then() to the called function in the test which will contain your expect code.

```<code>"it marks true in storage": function() {
    sinonSandbox.stub(tested, "updateServiceApi", function() {
        return MPromise.resolve();
    });

    var storageStub = sinonSandbox.stub(storage, "add");

    return tested._execute()
        .then(() => {
             expect(storageStub.calledWith("name", true)).to.be.true;
        });
}
</code>```

Body:
I have some code that executes after a promise is resolved. I'm trying to spy on a method that should be invoked post-promise resolution but I'm having problems with my tests finishing execution before the call to the spied on method is invoked.

How can I test the call to storage.add is actually being made?

Here's the test:

"it marks true in storage": function() {
    sinonSandbox.stub(tested, "updateServiceApi", function() {
        return MPromise.resolve();
    });

    var storageStub = sinonSandbox.stub(storage, "add");

    tested._execute();

    expect(
        storageStub.calledWith("name", true)
    ).to.be.true
}

And here's the implementation:

_execute: function() {
    this.updateServiceApi().then(function(){
        // tests finish before this code is executed :(
        storage.add("name", true);
    });
},

Body:
The problem here is that you've written your test as if _execute is synchronous.

Because of the promises, the expect call will be executed before the storage.add() call is made.

Exactly how you deal with this will be test runner dependent, but the general fix is to add a .then() to the called function in the test which will contain your expect code.

"it marks true in storage": function() {
    sinonSandbox.stub(tested, "updateServiceApi", function() {
        return MPromise.resolve();
    });

    var storageStub = sinonSandbox.stub(storage, "add");

    return tested._execute()
        .then(() => {
             expect(storageStub.calledWith("name", true)).to.be.true;
        });
}


问:
GitLab: lost gitlab-secrets.json - CipherError (bad decrypt)
I have reinstalled GitLab and forgot to back up the gitlab-secrets.json file.

Now I cannot enable 2FA (was disabled) and I'm seeing this error in the production.log file:

```<code>Completed 500 Internal Server Error in 15ms (ActiveRecord: 1.3ms)

OpenSSL::Cipher::CipherError (bad decrypt):
  app/controllers/profiles/two_factor_auths_controller.rb:5:in `show'
  lib/gitlab/i18n.rb:47:in `with_locale'
  lib/gitlab/i18n.rb:53:in `with_user_locale'
  app/controllers/application_controller.rb:337:in `set_locale'
  lib/gitlab/middleware/multipart.rb:93:in `call'
  lib/gitlab/request_profiler/middleware.rb:14:in `call'
  lib/gitlab/middleware/go.rb:17:in `call'
  lib/gitlab/etag_caching/middleware.rb:11:in `call'
  lib/gitlab/middleware/read_only.rb:30:in `call'
  lib/gitlab/request_context.rb:18:in `call'
  lib/gitlab/metrics/requests_rack_middleware.rb:27:in `call'
</code>```

Is there anything I could do to fix it without losing any data?

GitLab CE ver. 10.1.0

答:
if you used omnibus to install gitlab, maybe my ways could help.
For a reason, I had to reinstall gitlab, and I encountered almost the same 500 bad decrypt error after I'd done it. I didn't know to backup that secret file at all at that time.
I assume that you can access your gitlab website, can see the project list, but cannot directly open them because bad decrypt error (can open it by adding /tree/master).
Here are my ways:

/var/opt/gitlab  ------ Gitlab data files here. Backup them.

Download a minor upgrade version, which may help migrate your database encrypt info into to a new one.

Find a new machine, install gitlab(the previous version), restore data file and then upgrade it to that new downloaded version.

See if it is solved

For me, my previous gitlab version was 8.9.3, and after I reinstalled the exectly same version without backup the gitlab-secrets.json, I encountered 500 bad decrypt error. Then I upgraded it to 8.17.7, which is just a minor version upgrade. I notice a database migration and after that all the database encrypt info updated. Then I can open all my projects without 500.

```<code>    Checking PostgreSQL executables: OK
Shutting down all GitLab services except those needed for migrations
ok: down: gitlab-workhorse: 0s, normally up
ok: down: logrotate: 0s, normally up
ok: down: postgresql: 1s, normally up
ok: down: sidekiq: 0s, normally up
ok: down: unicorn: 1s, normally up
ok: run: postgresql: (pid 14987) 0s
run: postgresql: (pid 14987) 0s; run: log: (pid 15964) 159018s
Reconfiguring GitLab to apply migrations
init (upstart 0.6.5)

  * Moving existing certificates found in /opt/gitlab/embedded/ssl/certs

  * Symlinking existing certificates found in /etc/gitlab/trusted-certs
gitlab Reconfigured!
</code>```

Body:
I have reinstalled GitLab and forgot to back up the gitlab-secrets.json file.

Now I cannot enable 2FA (was disabled) and I'm seeing this error in the production.log file:

Completed 500 Internal Server Error in 15ms (ActiveRecord: 1.3ms)

OpenSSL::Cipher::CipherError (bad decrypt):
  app/controllers/profiles/two_factor_auths_controller.rb:5:in `show'
  lib/gitlab/i18n.rb:47:in `with_locale'
  lib/gitlab/i18n.rb:53:in `with_user_locale'
  app/controllers/application_controller.rb:337:in `set_locale'
  lib/gitlab/middleware/multipart.rb:93:in `call'
  lib/gitlab/request_profiler/middleware.rb:14:in `call'
  lib/gitlab/middleware/go.rb:17:in `call'
  lib/gitlab/etag_caching/middleware.rb:11:in `call'
  lib/gitlab/middleware/read_only.rb:30:in `call'
  lib/gitlab/request_context.rb:18:in `call'
  lib/gitlab/metrics/requests_rack_middleware.rb:27:in `call'

Is there anything I could do to fix it without losing any data?

GitLab CE ver. 10.1.0

Body:
if you used omnibus to install gitlab, maybe my ways could help.
For a reason, I had to reinstall gitlab, and I encountered almost the same 500 bad decrypt error after I'd done it. I didn't know to backup that secret file at all at that time.
I assume that you can access your gitlab website, can see the project list, but cannot directly open them because bad decrypt error (can open it by adding /tree/master).
Here are my ways:

/var/opt/gitlab  ------ Gitlab data files here. Backup them.

Download a minor upgrade version, which may help migrate your database encrypt info into to a new one.

Find a new machine, install gitlab(the previous version), restore data file and then upgrade it to that new downloaded version.

See if it is solved

For me, my previous gitlab version was 8.9.3, and after I reinstalled the exectly same version without backup the gitlab-secrets.json, I encountered 500 bad decrypt error. Then I upgraded it to 8.17.7, which is just a minor version upgrade. I notice a database migration and after that all the database encrypt info updated. Then I can open all my projects without 500.

    Checking PostgreSQL executables: OK
Shutting down all GitLab services except those needed for migrations
ok: down: gitlab-workhorse: 0s, normally up
ok: down: logrotate: 0s, normally up
ok: down: postgresql: 1s, normally up
ok: down: sidekiq: 0s, normally up
ok: down: unicorn: 1s, normally up
ok: run: postgresql: (pid 14987) 0s
run: postgresql: (pid 14987) 0s; run: log: (pid 15964) 159018s
Reconfiguring GitLab to apply migrations
init (upstart 0.6.5)

  * Moving existing certificates found in /opt/gitlab/embedded/ssl/certs

  * Symlinking existing certificates found in /etc/gitlab/trusted-certs
gitlab Reconfigured!


问:
Optimizing searching techniques for large data sets
I'm currently working on a project where I need to work with a .csv file that is around 3 million lines long and different .xlsx files that range in size between 10 lines long and over 1000 lines long. I'm trying to find commonalities between different cells in my .xlsx file and my .csv file.
To do this. I've read in my .csv file and .xslx file and stored both in ArrayLists.
I have what I want to work, working however the method I'm using is O(n^3) using a 3 nested for loop do search between each.

```<code>//This is our .xlsx file stored in an ArrayList
for(int i = 1; i<finalKnowledgeGraph.size(); i+=3) {
            //loop through our knowledgeGraph again
            for(int j = 1; j<finalKnowledgeGraph.size(); j+=3) {
                //loop through .csv file which is stored in an ArrayList
                for(int k=1; k<storeAsserions.size(); k++) {
                   if(finalKnowledgeGraph.get(i).equals(storeAsserions.get(k)) && finalKnowledgeGraph.get(j+1).equals(storeAsserions.get(k+1))){
                      System.out.println("Do Something");
                   } else if(finalKnowledgeGraph.get(i+1).equals(storeAsserions.get(k)) && finalKnowledgeGraph.get(j).equals(storeAsserions.get(k+1))) {
                       System.out.println("Do something else");
                   }
                }
            }
        }
</code>```

At the moment in my actual code, my System.out.println("Do something") is just writing specific parts of each file to a new .csv file.

Now, with what I'm doing out of the way my problem is optimization. Obviously if im running a 3 nested for loop over millions of inputs, it won't be finished running in my life time so I'm wondering what ways I can optimize the code.

One of my friends suggested storing the files in memory and so read/writes will be several times quicker. Another friend suggested storing the files in hashtables instead of ArrayLists to help speed up the process but since I'm essentially searching EVERY element in said hashtable I don't see how that's going to speed up the process. It just seems like it's going to transfer the searching from one data structure to another. However I said i'd also post the question here and see if people had any tips/suggestions on how I'd go about optimizing this code. Thanks

Note: I have literally no knowledge of optimization etc. myself and I found other questions on S/O too specific for my knowledge on the field so if the question seems like a duplicate, I've probably seen the question you're talking about already and couldn't understand the content

Edit: Everything stored in both ArrayLists is verb:noun:noun pairs where I'm trying to compare nouns between each ArrayList. Since I'm not concerned with verbs, I start searching at index 1. (Just for some context)

答:
One possible solution would be using a database, which -- given a proper index -- could do the search pretty fast. Assuming the data fit in memory, you can be even faster.

The principle

For problems like

```<code>for (X x : xList) {
    for (Y y : yList) {
        if (x.someAttr() == y.someAttr()) doSomething(x, y);
    }
}
</code>```

you simply partition one list into buckets according to the attribute like

```<code>Map<A, List<Y>> yBuckets = new HashMap<>();
yList.forEach(y -> yBuckets.compute(y.someAttr(), (k, v) ->
    (v==null ? new ArrayList<>() : v).add(y));
</code>```

Now, you iterate the other list and only look at the elements in the proper bucket like

```<code>for (X x : xList) {
    List<Y> smallList = yBucket.get(x.someAttr());
    if (smallList != null) {
        for (Y y : smallList) {
            if (x.someAttr() == y.someAttr()) doSomething(x, y);
        }
    }
}
</code>```

The comparison can be actually left out, as it's always true, but that's not the point. The speed comes from eliminating to looking at cases when equals would return false.

The complexity gets reduced from quadratic to linear plus the number of calls to doSomething.

Your case

Your data structure obviously does not fit. You're flattening your triplets into one list and this is wrong. You surely can work around it somehow, but creating a class Triplet {String verb, noun1, noun2} makes everything simpler. For storeAsserions, it looks like you're working with pairs. They seem to overlap, but that may be a typo, anyway it doesn't matter. Let's use Triplets and Pairs.

Let me also rename your lists, so that the code fits better in this tiny window:

```<code>for (Triplet x : fList) {
    for (Triplet y : fList) {
        for (Pair z : sList) {
            if (x.noun1.equals(z.noun1) && y.noun2.equals(z.noun2)) {
                doSomething();
            } else if (x.noun2.equals(z.noun1) && y.noun1.equals(z.noun2)) {
                doSomethingElse();
            }
        }
    }
}
</code>```

Now, we need some loops over buckets, so that at least one of the equals tests is always true, so that we save us dealing with non-matching data. Let's concentrate on the first condition

```<code>x.noun1.equals(z.noun1) && y.noun2.equals(z.noun2)
</code>```

I suggest a loop like

```<code>for (Pair z : sList) {
    for (Triplet x : smallListOfTripletsHavingNoun1SameAsZ) {
        for (Triplet y : smallListOfTripletsHavingNoun2SameAsZ) {
            doSomething();
        }
    }
}
</code>```

where the small lists get computes like in the first section.

No non-matching entries get ever compared, so the complexity gets reduced from cubic to the number of matches (= to the number if lines you code would print).

Addendum -yBuckets

Let's assume xList looks like

```<code>[
  {id: 1, someAttr: "a"},
  {id: 2, someAttr: "a"},
  {id: 3, someAttr: "b"},
]
</code>```

Then yBuckets should be

```<code>{
  "a": [
    {id: 1, someAttr: "a"},
    {id: 2, someAttr: "a"},
  ],
  :b": [
    {id: 3, someAttr: "b"},
  ],
}
</code>```

One simple way, how to create such a Map is

```<code>yList.forEach(y -> yBuckets.compute(y.someAttr(), (k, v) ->
   (v==null ? new ArrayList<>() : v).add(y));
</code>```

In plaintext:

For each y from yList,

get a corresponding map entry in the form of (k, v),

when v is null, then create a new List

otherwise work with the List v

In any case, add y to it

and store it back to the Map (which is a no-op unless when a new List was created in the third step).

Body:
I'm currently working on a project where I need to work with a .csv file that is around 3 million lines long and different .xlsx files that range in size between 10 lines long and over 1000 lines long. I'm trying to find commonalities between different cells in my .xlsx file and my .csv file.
To do this. I've read in my .csv file and .xslx file and stored both in ArrayLists.
I have what I want to work, working however the method I'm using is O(n^3) using a 3 nested for loop do search between each.

//This is our .xlsx file stored in an ArrayList
for(int i = 1; i<finalKnowledgeGraph.size(); i+=3) {
            //loop through our knowledgeGraph again
            for(int j = 1; j<finalKnowledgeGraph.size(); j+=3) {
                //loop through .csv file which is stored in an ArrayList
                for(int k=1; k<storeAsserions.size(); k++) {
                   if(finalKnowledgeGraph.get(i).equals(storeAsserions.get(k)) && finalKnowledgeGraph.get(j+1).equals(storeAsserions.get(k+1))){
                      System.out.println("Do Something");
                   } else if(finalKnowledgeGraph.get(i+1).equals(storeAsserions.get(k)) && finalKnowledgeGraph.get(j).equals(storeAsserions.get(k+1))) {
                       System.out.println("Do something else");
                   }
                }
            }
        }

At the moment in my actual code, my System.out.println("Do something") is just writing specific parts of each file to a new .csv file.

Now, with what I'm doing out of the way my problem is optimization. Obviously if im running a 3 nested for loop over millions of inputs, it won't be finished running in my life time so I'm wondering what ways I can optimize the code.

One of my friends suggested storing the files in memory and so read/writes will be several times quicker. Another friend suggested storing the files in hashtables instead of ArrayLists to help speed up the process but since I'm essentially searching EVERY element in said hashtable I don't see how that's going to speed up the process. It just seems like it's going to transfer the searching from one data structure to another. However I said i'd also post the question here and see if people had any tips/suggestions on how I'd go about optimizing this code. Thanks

Note: I have literally no knowledge of optimization etc. myself and I found other questions on S/O too specific for my knowledge on the field so if the question seems like a duplicate, I've probably seen the question you're talking about already and couldn't understand the content

Edit: Everything stored in both ArrayLists is verb:noun:noun pairs where I'm trying to compare nouns between each ArrayList. Since I'm not concerned with verbs, I start searching at index 1. (Just for some context)

Body:
One possible solution would be using a database, which -- given a proper index -- could do the search pretty fast. Assuming the data fit in memory, you can be even faster.

The principle

For problems like

for (X x : xList) {
    for (Y y : yList) {
        if (x.someAttr() == y.someAttr()) doSomething(x, y);
    }
}

you simply partition one list into buckets according to the attribute like

Map<A, List<Y>> yBuckets = new HashMap<>();
yList.forEach(y -> yBuckets.compute(y.someAttr(), (k, v) ->
    (v==null ? new ArrayList<>() : v).add(y));

Now, you iterate the other list and only look at the elements in the proper bucket like

for (X x : xList) {
    List<Y> smallList = yBucket.get(x.someAttr());
    if (smallList != null) {
        for (Y y : smallList) {
            if (x.someAttr() == y.someAttr()) doSomething(x, y);
        }
    }
}

The comparison can be actually left out, as it's always true, but that's not the point. The speed comes from eliminating to looking at cases when equals would return false.

The complexity gets reduced from quadratic to linear plus the number of calls to doSomething.

Your case

Your data structure obviously does not fit. You're flattening your triplets into one list and this is wrong. You surely can work around it somehow, but creating a class Triplet {String verb, noun1, noun2} makes everything simpler. For storeAsserions, it looks like you're working with pairs. They seem to overlap, but that may be a typo, anyway it doesn't matter. Let's use Triplets and Pairs.

Let me also rename your lists, so that the code fits better in this tiny window:

for (Triplet x : fList) {
    for (Triplet y : fList) {
        for (Pair z : sList) {
            if (x.noun1.equals(z.noun1) && y.noun2.equals(z.noun2)) {
                doSomething();
            } else if (x.noun2.equals(z.noun1) && y.noun1.equals(z.noun2)) {
                doSomethingElse();
            }
        }
    }
}

Now, we need some loops over buckets, so that at least one of the equals tests is always true, so that we save us dealing with non-matching data. Let's concentrate on the first condition

x.noun1.equals(z.noun1) && y.noun2.equals(z.noun2)

I suggest a loop like

for (Pair z : sList) {
    for (Triplet x : smallListOfTripletsHavingNoun1SameAsZ) {
        for (Triplet y : smallListOfTripletsHavingNoun2SameAsZ) {
            doSomething();
        }
    }
}

where the small lists get computes like in the first section.

No non-matching entries get ever compared, so the complexity gets reduced from cubic to the number of matches (= to the number if lines you code would print).

Addendum -yBuckets

Let's assume xList looks like

[
  {id: 1, someAttr: "a"},
  {id: 2, someAttr: "a"},
  {id: 3, someAttr: "b"},
]

Then yBuckets should be

{
  "a": [
    {id: 1, someAttr: "a"},
    {id: 2, someAttr: "a"},
  ],
  :b": [
    {id: 3, someAttr: "b"},
  ],
}

One simple way, how to create such a Map is

yList.forEach(y -> yBuckets.compute(y.someAttr(), (k, v) ->
   (v==null ? new ArrayList<>() : v).add(y));

In plaintext:

For each y from yList,

get a corresponding map entry in the form of (k, v),

when v is null, then create a new List

otherwise work with the List v

In any case, add y to it

and store it back to the Map (which is a no-op unless when a new List was created in the third step).


问:
Three.js | Vertex's distance from center doesn't change after applying displacement map on sphereGeometry
I'm trying to calculate the distance (from origin) of displaced vertices after applying displacement map on a sphere geometry(positioned at origin only).

As the displacement map changes the position of the vertex, the distance should differ in both the cases ( before and after applying displacement map ), but somehow the distance from center of the sphere ( here origin ) doesn't change.

Any views on this?
Thanks in advance :)

答: This isn't possible given where displacement mapping fits into the graphics pipeline. You essentially "send off" all your data into shaders, and that's where the displacement mapping occurs. That's why it's efficient but also not accessible. If you need something more accessible, you'll need to write some JS that operates on your vertices beforehand, but it will not be nearly as performant. You could also blend the two methods by creating a dynamic displacement map. It all depends on context, which isn't clear in your question. Why do you need to calculate the vertex distance after you've applied the map? In making the displacement map, you are directly setting the position of vertices, and could calculate the distance from origin just based on the original vertices and reading the displacement map.</p>


问:
Cannot register my .ocx with error code 0x80040200
When i try to register my .ocx file I get error code 0x80040200.

I know that this error usually occurs when I got no administrator privileges, but for me that's not the case.

I found some code snippet with which I could test my .ocx wether regsvr32 can find the entry point and it looks like it could.

Is there any other known reason why this error could occur?

Thanks

答: In my case, I tried to register dll and got the same error. The reason was absence of a tlb file near the dll.</p>


问:
Crash on button click when I try to add items in ListView dynamically
I have an activity named EfortActivity which contains 3 EditText, a Spinner, a RadioGroup and a Button - saveButton. My goal is to add data dynamically in a ListView (the listView is implemented in another activity called HistoryActivity).

The problem is that when I click on the saveButton my app crash.

Here is the code in EfortActivity:

```<code>public class EfortMonitorizareActivity extends AppCompatActivity {

RadioGroup radioGroupDaNu;
Spinner spinnerTip;
EditText editTextDurata;
EditText editTextInainte;
EditText editTextDupa;
Intent intent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_efort_monitorizare);
    intent = getIntent();
    initializareComponente();
}

private void initializareComponente() {
    radioGroupDaNu = (RadioGroup) findViewById(R.id.rg_activitateDANU);
    spinnerTip = (Spinner) findViewById(R.id.spin_tip_efort);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getApplicationContext(),
            R.array.TipEfort, R.layout.support_simple_spinner_dropdown_item);
    spinnerTip.setAdapter(adapter);
    editTextDurata = (EditText) findViewById(R.id.edt_durataAnt_efort);
    editTextInainte = (EditText) findViewById(R.id.edt_greuteInainteAnt_efort);
    editTextDupa = (EditText) findViewById(R.id.edt_greutateDupaAnt_efort);

    Button btn_inregistrareDate = (Button) findViewById(R.id.btn_adaugaDate_efort);
    btn_inregistrareDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (validare()) {
                Efort efort = createPlayerFromComponents();
                if (efort != null) {
                    intent.putExtra(Constants.ADD_EFORT_KEY,efort);
                    setResult(RESULT_OK,intent);
                    finish();
                }
            }
        }
    });
}

private Efort createPlayerFromComponents() {

    RadioButton checkDaNu = (RadioButton) findViewById(radioGroupDaNu.getCheckedRadioButtonId());
    String radioDaNu = checkDaNu.getText().toString();
    String tip = spinnerTip.getSelectedItem().toString();
    Integer durata = Integer.parseInt(editTextDurata.getText().toString());
    Integer inainte = Integer.parseInt(editTextInainte.getText().toString());
    Integer dupa = Integer.parseInt(editTextDupa.getText().toString());

    return new Efort(radioDaNu, tip, durata, inainte, dupa);
}

private boolean validare() {

    RadioButton nu = (RadioButton) findViewById(R.id.button_nu_efort);

    if (editTextDurata.getText() == null || editTextDurata.getText().toString().trim().isEmpty()) {
        Toast.makeText(getApplicationContext(), R.string.addplayer_number_error, Toast.LENGTH_SHORT).show();
        return false;
    }
    if (editTextInainte.getText() == null || editTextDurata.getText().toString().trim().isEmpty()) {
        Toast.makeText(getApplicationContext(), R.string.addplayer_number_error, Toast.LENGTH_SHORT).show();
        return false;
    }
    if (editTextDupa.getText() == null || editTextDurata.getText().toString().trim().isEmpty()) {
        Toast.makeText(getApplicationContext(), R.string.addplayer_number_error, Toast.LENGTH_SHORT).show();
        return false;
    }         }
</code>```

Here is the code for HistoryActivity:

```<code>public class IstoricActivity extends AppCompatActivity {

ListView lvEfort;
List<String> listaEfort = new ArrayList<>();
Button deconectare;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_istoric);

    deconectare=(Button)findViewById(R.id.btn_deconectareIstoric);
    deconectare.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });
    //initializare componente
    lvEfort = (ListView) findViewById(R.id.lw_listaEfort);
    Efort efortDefault = new Efort("Da", "Tennis", 40, 55, 53);
    listaEfort.add(efortDefault.toString());

    //declarare + initializare adapter
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, listaEfort);
    lvEfort.setAdapter(adapter);
    adapter.notifyDataSetChanged();
    }
}
</code>```

And the class Efort:

```<code>public class Efort implements Parcelable {

private String radioDaNu;
private String tip;
private Integer durata;
private Integer inainte;
private Integer dupa;

public Efort(String radioDaNu, String tip, Integer durata, Integer inainte, Integer dupa) {
    this.radioDaNu = radioDaNu;
    this.tip = tip;
    this.durata = durata;
    this.inainte = inainte;
    this.dupa = dupa;
}

public String getRadioDaNu() {
    return radioDaNu;
}

public void setRadioDaNu(String radioDaNu) {
    this.radioDaNu = radioDaNu;
}

public String getTip() {
    return tip;
}

public void setTip(String tip) {
    this.tip = tip;
}

public Integer getDurata() {
    return durata;
}

public void setDurata(Integer durata) {
    this.durata = durata;
}

public Integer getInainte() {
    return inainte;
}

public void setInainte(Integer inainte) {
    this.inainte = inainte;
}

public Integer getDupa() {
    return dupa;
}

public void setDupa(Integer dupa) {
    this.dupa = dupa;
}

@Override
public String toString() {
    return "Efort{" +
            // ", datePicker=" + datePicker +
            ", Activitate efort  :" + radioDaNu +
            ", tip : '" + tip + '\'' +
            ", tipm de : " + durata +
            ", inainte de antrenamnet aveam : " + inainte +
            ", dupa antrenamnet am : " + dupa +
            '}';
}

public Efort(Parcel in) {
    this.radioDaNu = in.readString();
    this.tip = in.readString();
    this.durata = in.readInt();
    this.inainte = in.readInt();
    this.dupa = in.readInt();
}

public static Parcelable.Creator<Efort> CREATOR = new Creator<Efort>() {
    @Override
    public Efort createFromParcel(Parcel parcel) {
        return new Efort(parcel);
    }

    @Override
    public Efort[] newArray(int i) {
        return new Efort[i];
    }
};

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(radioDaNu);
    parcel.writeString(tip);
    parcel.writeInt(durata);
    parcel.writeInt(inainte);
    parcel.writeInt(dupa);
}
}
</code>```

答:
When you called,

```<code>  finish()
</code>```

it will stop your activity and finish it. Please remove that finish()

Body:
I have an activity named EfortActivity which contains 3 EditText, a Spinner, a RadioGroup and a Button - saveButton. My goal is to add data dynamically in a ListView (the listView is implemented in another activity called HistoryActivity).

The problem is that when I click on the saveButton my app crash.

Here is the code in EfortActivity:

public class EfortMonitorizareActivity extends AppCompatActivity {

RadioGroup radioGroupDaNu;
Spinner spinnerTip;
EditText editTextDurata;
EditText editTextInainte;
EditText editTextDupa;
Intent intent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_efort_monitorizare);
    intent = getIntent();
    initializareComponente();
}

private void initializareComponente() {
    radioGroupDaNu = (RadioGroup) findViewById(R.id.rg_activitateDANU);
    spinnerTip = (Spinner) findViewById(R.id.spin_tip_efort);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getApplicationContext(),
            R.array.TipEfort, R.layout.support_simple_spinner_dropdown_item);
    spinnerTip.setAdapter(adapter);
    editTextDurata = (EditText) findViewById(R.id.edt_durataAnt_efort);
    editTextInainte = (EditText) findViewById(R.id.edt_greuteInainteAnt_efort);
    editTextDupa = (EditText) findViewById(R.id.edt_greutateDupaAnt_efort);

    Button btn_inregistrareDate = (Button) findViewById(R.id.btn_adaugaDate_efort);
    btn_inregistrareDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (validare()) {
                Efort efort = createPlayerFromComponents();
                if (efort != null) {
                    intent.putExtra(Constants.ADD_EFORT_KEY,efort);
                    setResult(RESULT_OK,intent);
                    finish();
                }
            }
        }
    });
}

private Efort createPlayerFromComponents() {

    RadioButton checkDaNu = (RadioButton) findViewById(radioGroupDaNu.getCheckedRadioButtonId());
    String radioDaNu = checkDaNu.getText().toString();
    String tip = spinnerTip.getSelectedItem().toString();
    Integer durata = Integer.parseInt(editTextDurata.getText().toString());
    Integer inainte = Integer.parseInt(editTextInainte.getText().toString());
    Integer dupa = Integer.parseInt(editTextDupa.getText().toString());

    return new Efort(radioDaNu, tip, durata, inainte, dupa);
}

private boolean validare() {

    RadioButton nu = (RadioButton) findViewById(R.id.button_nu_efort);

    if (editTextDurata.getText() == null || editTextDurata.getText().toString().trim().isEmpty()) {
        Toast.makeText(getApplicationContext(), R.string.addplayer_number_error, Toast.LENGTH_SHORT).show();
        return false;
    }
    if (editTextInainte.getText() == null || editTextDurata.getText().toString().trim().isEmpty()) {
        Toast.makeText(getApplicationContext(), R.string.addplayer_number_error, Toast.LENGTH_SHORT).show();
        return false;
    }
    if (editTextDupa.getText() == null || editTextDurata.getText().toString().trim().isEmpty()) {
        Toast.makeText(getApplicationContext(), R.string.addplayer_number_error, Toast.LENGTH_SHORT).show();
        return false;
    }         }

Here is the code for HistoryActivity:

public class IstoricActivity extends AppCompatActivity {

ListView lvEfort;
List<String> listaEfort = new ArrayList<>();
Button deconectare;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_istoric);

    deconectare=(Button)findViewById(R.id.btn_deconectareIstoric);
    deconectare.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });
    //initializare componente
    lvEfort = (ListView) findViewById(R.id.lw_listaEfort);
    Efort efortDefault = new Efort("Da", "Tennis", 40, 55, 53);
    listaEfort.add(efortDefault.toString());

    //declarare + initializare adapter
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, listaEfort);
    lvEfort.setAdapter(adapter);
    adapter.notifyDataSetChanged();
    }
}

And the class Efort:

public class Efort implements Parcelable {

private String radioDaNu;
private String tip;
private Integer durata;
private Integer inainte;
private Integer dupa;

public Efort(String radioDaNu, String tip, Integer durata, Integer inainte, Integer dupa) {
    this.radioDaNu = radioDaNu;
    this.tip = tip;
    this.durata = durata;
    this.inainte = inainte;
    this.dupa = dupa;
}

public String getRadioDaNu() {
    return radioDaNu;
}

public void setRadioDaNu(String radioDaNu) {
    this.radioDaNu = radioDaNu;
}

public String getTip() {
    return tip;
}

public void setTip(String tip) {
    this.tip = tip;
}

public Integer getDurata() {
    return durata;
}

public void setDurata(Integer durata) {
    this.durata = durata;
}

public Integer getInainte() {
    return inainte;
}

public void setInainte(Integer inainte) {
    this.inainte = inainte;
}

public Integer getDupa() {
    return dupa;
}

public void setDupa(Integer dupa) {
    this.dupa = dupa;
}

@Override
public String toString() {
    return "Efort{" +
            // ", datePicker=" + datePicker +
            ", Activitate efort  :" + radioDaNu +
            ", tip : '" + tip + '\'' +
            ", tipm de : " + durata +
            ", inainte de antrenamnet aveam : " + inainte +
            ", dupa antrenamnet am : " + dupa +
            '}';
}

public Efort(Parcel in) {
    this.radioDaNu = in.readString();
    this.tip = in.readString();
    this.durata = in.readInt();
    this.inainte = in.readInt();
    this.dupa = in.readInt();
}

public static Parcelable.Creator<Efort> CREATOR = new Creator<Efort>() {
    @Override
    public Efort createFromParcel(Parcel parcel) {
        return new Efort(parcel);
    }

    @Override
    public Efort[] newArray(int i) {
        return new Efort[i];
    }
};

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(radioDaNu);
    parcel.writeString(tip);
    parcel.writeInt(durata);
    parcel.writeInt(inainte);
    parcel.writeInt(dupa);
}
}

Body:
When you called,

  finish()

it will stop your activity and finish it. Please remove that finish()


问:
Flutter: Padding on a scaled Image
I'm new to flutter, but I thought I was on the right track here.

I've tried using the padding attribute on a Container, as well as wrapping the element (or parent elements) inside of a new Padding(). The below is only a portion of the layout, but the offending part.

```<code>new Column(
      mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          new Container(
            padding: new EdgeInsets.all(8.0),
              child: new Image.network(_choiceOne,
                height: 200.0,
                  fit: BoxFit.cover
          )
        )
      ],
    )
</code>```

I've also tried using a Decoration on parent elements to produce the desired "padding", but I still end up with the renderer flipping out. I think it has something to do with the scaling of the random image's I'm retrieving, but am not sure.

The start of the error is: A horizontal RenderFlex overflowed by 11 pixels.

With the error tree being listed as Row ← Column ← Container ← Chooser ← ConstrainedBox ← Container ← Center ← MediaQuery ←

答: Try using margin instead of padding.</p>

Title: Flutter: Padding on a scaled Image

Body:
I'm new to flutter, but I thought I was on the right track here.

I've tried using the padding attribute on a Container, as well as wrapping the element (or parent elements) inside of a new Padding(). The below is only a portion of the layout, but the offending part.

new Column(
      mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          new Container(
            padding: new EdgeInsets.all(8.0),
              child: new Image.network(_choiceOne,
                height: 200.0,
                  fit: BoxFit.cover
          )
        )
      ],
    )

I've also tried using a Decoration on parent elements to produce the desired "padding", but I still end up with the renderer flipping out. I think it has something to do with the scaling of the random image's I'm retrieving, but am not sure.

The start of the error is: A horizontal RenderFlex overflowed by 11 pixels.

With the error tree being listed as Row ← Column ← Container ← Chooser ← ConstrainedBox ← Container ← Center ← MediaQuery ←

Body: Try using margin instead of padding.


问:
Java: variable from parent class in child one isn't initialized and holds null
```<code>Parent class(*ch.qos.logback.core.FileAppender*):

     ...

   protected String fileName = null;

   public FileAppender() {
      }

          public void setFile(String file) {
            if (file == null) {
              fileName = file;
            } else {
              // Trim spaces from both ends. The users probably does not want
              // trailing spaces in file names.
              String val = file.trim();
              fileName = val;
            }
          }
    ...
</code>```

Child class:

```<code>    ...
   public class FileAppender<E> extends ch.qos.logback.core.FileAppender<E> {

     private FileResourceManager frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);

     public void writeOut(E event) throws IOException {
      Object txId = null;
      try {
       frm.start();
       txId = frm.generatedUniqueTxId();
       frm.startTransaction(txId);
       outputStream = frm.writeResource(txId, fileName, true);
       outputStream.write(event.toString().getBytes());
       frm.commitTransaction(txId);

      }

      catch (Exception e) {
    ...
      }
     }
</code>```

The problem is that fileName is passed as null to frm in this line:

```<code>private FileResourceManager frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);
</code>```

How can i create frm instance,with not-null fileName,e.g. already initialized in parent?

答:
If I understand your question correctly, you can do one of the following:

call setFile(file) in constructor of child class

implement logics placed in setFile() method in child's constructor (BTW, that'll be code duplication)

if parent class provides constructor, which accepts file parameter, call parent's constructor with super(file) in constructor of child class

UPDATE

AFAIU, the problem is in fields initialization order. The moving "frm" field initialization into child class constructor should solve the problem:

```<code>public FileAppender(String fileName) {
    setFile(fileName);
    frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);
    ...
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Parent class(*ch.qos.logback.core.FileAppender*):

     ...

   protected String fileName = null;

   public FileAppender() {
      }

          public void setFile(String file) {
            if (file == null) {
              fileName = file;
            } else {
              // Trim spaces from both ends. The users probably does not want
              // trailing spaces in file names.
              String val = file.trim();
              fileName = val;
            }
          }
    ...

Child class:

    ...
   public class FileAppender<E> extends ch.qos.logback.core.FileAppender<E> {

     private FileResourceManager frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);

     public void writeOut(E event) throws IOException {
      Object txId = null;
      try {
       frm.start();
       txId = frm.generatedUniqueTxId();
       frm.startTransaction(txId);
       outputStream = frm.writeResource(txId, fileName, true);
       outputStream.write(event.toString().getBytes());
       frm.commitTransaction(txId);

      }

      catch (Exception e) {
    ...
      }
     }

The problem is that fileName is passed as null to frm in this line:

private FileResourceManager frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);

How can i create frm instance,with not-null fileName,e.g. already initialized in parent?

Body:
If I understand your question correctly, you can do one of the following:

call setFile(file) in constructor of child class

implement logics placed in setFile() method in child's constructor (BTW, that'll be code duplication)

if parent class provides constructor, which accepts file parameter, call parent's constructor with super(file) in constructor of child class

UPDATE

AFAIU, the problem is in fields initialization order. The moving "frm" field initialization into child class constructor should solve the problem:

public FileAppender(String fileName) {
    setFile(fileName);
    frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);
    ...
}


问:
Tokenize words stored in a string in Python
So in my program, I have an input text file. I iterate through the list, add all the words in the list into a string called "text". Then, I use tokenizer on the string, which fails.

```<code>x = open("Tokens.txt")
text = ""
for line in iter(x):

   text += line[0:-1] + " "

x.close()

for i in tokenizer(text):
    print(i)
</code>```

The input stored in the text file-

```<code>abx
*
22;
print "example"
time = 26
</code>```

When I hard code the input into the tokenizer, it works- the program outputs the correct tokens. Like this-

```<code>#for i in tokenizer("abx * 22; print \"example\"  time = 26"):
  #print(i)
</code>```

However, I'm required to open the text file, grab the input from the file, then analyze it, but that won't work. This is the error I'm getting.

```<code>Traceback (most recent call last):

File "C:/Users/XX/PycharmProjects/check/lexical.py", line 35, in <module>
    for i in tokenizer(text):

File "C:/Users/XX/PycharmProjects/check/lexical.py", line 26, in tokenizer
    raise Exception('Cannot output tokens')
Exception: Cannot output tokens
</code>```

答:
I do not have the reputation to comment, so I am posting as an answer.
Iterating over your file (for line in iter(x)) is better done as for line in x.readlines()

Body:
So in my program, I have an input text file. I iterate through the list, add all the words in the list into a string called "text". Then, I use tokenizer on the string, which fails.

x = open("Tokens.txt")
text = ""
for line in iter(x):

   text += line[0:-1] + " "

x.close()

for i in tokenizer(text):
    print(i)

The input stored in the text file-

abx
*
22;
print "example"
time = 26

When I hard code the input into the tokenizer, it works- the program outputs the correct tokens. Like this-

#for i in tokenizer("abx * 22; print \"example\"  time = 26"):
  #print(i)

However, I'm required to open the text file, grab the input from the file, then analyze it, but that won't work. This is the error I'm getting.

Traceback (most recent call last):

File "C:/Users/XX/PycharmProjects/check/lexical.py", line 35, in <module>
    for i in tokenizer(text):

File "C:/Users/XX/PycharmProjects/check/lexical.py", line 26, in tokenizer
    raise Exception('Cannot output tokens')
Exception: Cannot output tokens


问:
Updating angular from one 4.2.x to 4.3
Angular 4.3 is just out and they got this new HttpClient replacing the HttpModule. But I happened to start with 4.2 and I'd like to tap into this new implementation.

What's the recommended way for me to update the app to 4.3?

Current dependencies are as follows:

```<code>"dependencies": {
    "@angular/animations": "^4.4.4",
    "@angular/cdk": "^2.0.0-beta.11",
    "@angular/common": "^4.2.4",
    "@angular/compiler": "^4.2.4",
    "@angular/core": "^4.2.4",
    "@angular/forms": "^4.2.4",
    "@angular/http": "^4.2.4",
    "@angular/material": "^2.0.0-beta.11",
    "@angular/platform-browser": "^4.2.4",
    "@angular/platform-browser-dynamic": "^4.2.4",
    "@angular/router": "^4.2.4",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "rxjs": "^5.4.2",
    "zone.js": "^0.8.14"
  },
</code>```

Not, all but some clearly needed to be upped.
So what do I do?

rm -rf node_modules?

That sounds like an overkill.

Modifying the package.json ( by replacing all 4.2.4's with 4.3 ) and then running the npm install makes me cautious and urges me to ask before actually to do it.

I do not want to run npm install and then learn what happens after that the hard way. :)

Your advice is appreciated.

答:
simply write the command
npm update --save

it will upgrade to latest stable version
i was also having the same requirement as yours to use HttpClient
it has updated all my project configuration files to the latest version, i dont have to do any manual work as i have read on some other post
old package.json file ||
new package.json file after updating

i got reference from Mick Lawitzke answer on github, below is the link

reference : https://github.com/angular/angular-cli/issues/7162

Title: Updating angular from one 4.2.x to 4.3

Body:
Angular 4.3 is just out and they got this new HttpClient replacing the HttpModule. But I happened to start with 4.2 and I'd like to tap into this new implementation.

What's the recommended way for me to update the app to 4.3?

Current dependencies are as follows:

"dependencies": {
    "@angular/animations": "^4.4.4",
    "@angular/cdk": "^2.0.0-beta.11",
    "@angular/common": "^4.2.4",
    "@angular/compiler": "^4.2.4",
    "@angular/core": "^4.2.4",
    "@angular/forms": "^4.2.4",
    "@angular/http": "^4.2.4",
    "@angular/material": "^2.0.0-beta.11",
    "@angular/platform-browser": "^4.2.4",
    "@angular/platform-browser-dynamic": "^4.2.4",
    "@angular/router": "^4.2.4",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "rxjs": "^5.4.2",
    "zone.js": "^0.8.14"
  },

Not, all but some clearly needed to be upped.
So what do I do?

rm -rf node_modules?

That sounds like an overkill.

Modifying the package.json ( by replacing all 4.2.4's with 4.3 ) and then running the npm install makes me cautious and urges me to ask before actually to do it.

I do not want to run npm install and then learn what happens after that the hard way. :)

Your advice is appreciated.


问:
How to use TortoiseSVN via command line?
I use TortoiseSVN and want to use command line SVN options.

I used the command:

```<code>svn checkout [-N] [--ignore-externals] [-r rev] URL PATH
</code>```

and get the following error:

'svn' is not recognized as an internal or external command

Is it because I need to add some environment variable? Or can't TortoiseSVN be used from the command line?

答:
You can have both TortoiseSVN and the Apache Subversion command line tools installed.  I usually install the Apache SVN tools from the VisualSVN download site: https://www.visualsvn.com/downloads/ </p>

<p>Once installed, place the Subversion\bin in your set PATH.  Then you will be able to use TortoiseSVN when you want to use the GUI, and you have the proper SVN command line tools to use from the command line.  </p>

ContentLicense: CC BY-SA 4.0

Body:
I use TortoiseSVN and want to use command line SVN options.

I used the command:

svn checkout [-N] [--ignore-externals] [-r rev] URL PATH

and get the following error:

'svn' is not recognized as an internal or external command

Is it because I need to add some environment variable? Or can't TortoiseSVN be used from the command line?

Body:
You can have both TortoiseSVN and the Apache Subversion command line tools installed.  I usually install the Apache SVN tools from the VisualSVN download site: https://www.visualsvn.com/downloads/

Once installed, place the Subversion\bin in your set PATH.  Then you will be able to use TortoiseSVN when you want to use the GUI, and you have the proper SVN command line tools to use from the command line.


问:
Android MediaCodec seems to be ignoring specified KEY_BIT_RATE value
I need to implement H264 encoding and configure MediaCodec as follows

```<code>    MediaCodec codec = MediaCodec.createEncoderByType("video/avc");
    MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc", resolution.getWidth(), resolution.getHeight());

    mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
    mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, 1000000);
    mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE,30);
    codec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
</code>```

Bitrate is set to 1000000 and this is a requirement defined by network limitations. When I test on Samsung Galaxy J7 I see 1000 kbps in output as expected. But when I test the same code on some particular devices like Samsung Galaxy Grand 2 Duos (android 4.4) or Huawei Nexus 6P (android 7.1.2), I see that the encoder produces up to 5 megabytes per second in output, that means that specified value 1000000 bits per second is totally ignored by codec. What's wrong with it? Is there a way to force encoder to use this specified value?

答:
True reason of this behavior was in timestamps that I transferred to the encoder when pushed frames in. On a developing stage for simplicity I used System.nanoTime() value as a timestamp. This timestamp expressed time in nanoseconds while encoder requires microseconds as a timestamp.

Most of codec implementations probably use their own timer to measure real incoming fps and thus they do not depend on a actual timestamp values and just ignore them. But Nexus 6P has probably a smart one, this encoder uses timestamps to measure fps value. Timestamps were given in nanoseconds and from the point of view of the codec time flow was 1000 times slower and measured fps was 1000/30 ~ 1 frame per 33 seconds and thus the codec tried to push all requested megabit into a single output frame.

Body:
I need to implement H264 encoding and configure MediaCodec as follows

    MediaCodec codec = MediaCodec.createEncoderByType("video/avc");
    MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc", resolution.getWidth(), resolution.getHeight());

    mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
    mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, 1000000);
    mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE,30);
    codec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);

Bitrate is set to 1000000 and this is a requirement defined by network limitations. When I test on Samsung Galaxy J7 I see 1000 kbps in output as expected. But when I test the same code on some particular devices like Samsung Galaxy Grand 2 Duos (android 4.4) or Huawei Nexus 6P (android 7.1.2), I see that the encoder produces up to 5 megabytes per second in output, that means that specified value 1000000 bits per second is totally ignored by codec. What's wrong with it? Is there a way to force encoder to use this specified value?


问:
Using $_POST values in CodeIgniter
Application makes an AJAX request to a method in a controller.

The controller then calls a method in the model to run a query on the DB and then return the results.

AJAX "type" specified as POST.

Even though $_POST superglobal values are available for use in model, should one still list the $_POST values in the model method signature?

I'm thinking this is best practice so people dissecting a system can quickly see inputs going into model methods

```<code>$this->Students_table_model->attendance_history_get($_POST['students_id'],$_POST['start_date'],$_POST['end_date']);

public function attendance_history_get($students_id,$start,$end)
</code>```

VS

```<code>$this->Students_table_model->attendance_history_get();
</code>```

and then just using the available $_POST values in model method attendance_history_get()

答:
Use

```<code>$this->Students_table_model->attendance_history_get($_POST);
</code>```

and use it in the model.

Title: Using $_POST values in CodeIgniter

Body:
Application makes an AJAX request to a method in a controller.

The controller then calls a method in the model to run a query on the DB and then return the results.

AJAX "type" specified as POST.

Even though $_POST superglobal values are available for use in model, should one still list the $_POST values in the model method signature?

I'm thinking this is best practice so people dissecting a system can quickly see inputs going into model methods

$this->Students_table_model->attendance_history_get($_POST['students_id'],$_POST['start_date'],$_POST['end_date']);

public function attendance_history_get($students_id,$start,$end)

VS

$this->Students_table_model->attendance_history_get();

and then just using the available $_POST values in model method attendance_history_get()

Body:
Use

$this->Students_table_model->attendance_history_get($_POST);

and use it in the model.


问:
Why do different operating systems install packages from CRAN differently?
When I install.package() in R on a Windows machine, the package downloads from CRAN and installs. When I do the same on a Linux box, the package usually has to compile (at least, I assume that's what going with all those g++ lines that scroll past).

Why is the package installation method different on Windows?

Other questions and their answers make it clear that using different methods and repositories for Linux particularly, enables users to get more/different packages (particularly using the cran2deb repository). My question is more theoretical in nature: why is the default choice in Windows to download precompiled (binary?) packages whereas the default in Linux seems to be to compile packages from source?

Or to put it another way (based on Dirk's assertion in the second link above), why doesn't CRAN offer binary packages for Unix-type operating systems?

答:
In general, Windows binaries will work on all versions of Windows.

Ditto for the key / current versions of MacOS: the provided binaries work.

Linux, sadly, is more complicated because the different distros lay things out differently. Something I build on Ubuntu or Debian (or, more specifically, a particular release version thereof) may not even work on other releases of the same distro, let alone other distro.  In some cases you can get binaries.  At some point I (co-)owned a build service for all of CRAN, but it died/broke. All doable with effort, but ... some effort.

So from source it is. That use to be the standard anyway which "Unix" was a catch-all phrase covering SunOS/Solaris, AIX, *BSD, SGI and on and on. Often even with different processors.  So source.

There have been attempts to provide 'universal binaries': flatpack and snap are two more recent examples.  And then there is of course Docker.


问:
get input from keyboard while displaying an avi with matlab
Hi all

I wrote a short program that displays an avi file. I need the program to get input from the keyboard while the movie is running (and not after it ends):
this is my code:

figure('MenuBar','none')

    set(gcf,'Color', 'white')

    set(gca,'Color','white');

    set(gca,'XColor','white');

    set(gca,'YColor','white');

    m=aviread('c:/t1.avi')

    a=30:1:100;

    b=100:-1:30;

    c=[a b a b a b a b a b] %to run the movie back and forth

    movie(m,c) %runs the movie

Thank you for any help

Ariel

答:
As far as I know multi-threading or parallel processing capabilities in MATLAB are limited; however it appears as there are remedies. This article describes combining MATLAB and C++ code, with use of MEX files. </p>

<p>Now I have to admit that I have never tried this so I can't really claim that it would work in your case, but it would be a good place to start. </p>

Body:
As far as I know multi-threading or parallel processing capabilities in MATLAB are limited; however it appears as there are remedies. This article describes combining MATLAB and C++ code, with use of MEX files.

Now I have to admit that I have never tried this so I can't really claim that it would work in your case, but it would be a good place to start.


问:
kubernetes list all running pods name
I looking for the option to list all pods name

How to do without awk (or cut). Now i'm using this command

```<code>kubectl get --no-headers=true pods -o name | awk -F "/" '{print $2}'
</code>```

答:
You can use custom-columns in output option to get the name and --no-headers option</p>

```<code>kubectl get --no-headers=true pods -l app=external-dns -o custom-columns=:metadata.name
</code>```

Title: kubernetes list all running pods name

Body:
I looking for the option to list all pods name

How to do without awk (or cut). Now i'm using this command

kubectl get --no-headers=true pods -o name | awk -F "/" '{print $2}'

Body:
You can use custom-columns in output option to get the name and --no-headers option

kubectl get --no-headers=true pods -l app=external-dns -o custom-columns=:metadata.name


问:
Closing a pull request through github API
As per the design requirements of our application, we used to delete the merge requests in Gitlab using gitlab API. Now we are migrating to Github and I am looking for a similar API call which closes the pull requests on Github.

I read through the documentation here, but it doesn't answer my question.

I would be glad if someone could help me with it.

答:
If you read the API documentation whose link you pasted above, it seems that there is an update endpoint which can be used to assign the state of a pull request:

```<code>PATCH /repos/:owner/:repo/pulls/:number

{
    "title": "new title",
    "body": "updated body",
    "state": "closed",
    "base": "master"
}
</code>```

The state key inside the JSON can be either open or closed.

Body:
If you read the API documentation whose link you pasted above, it seems that there is an update endpoint which can be used to assign the state of a pull request:

PATCH /repos/:owner/:repo/pulls/:number

{
    "title": "new title",
    "body": "updated body",
    "state": "closed",
    "base": "master"
}

The state key inside the JSON can be either open or closed.


问:
Handles SQL Exception from Entity Framework
In my sql stored procedure, i do some insertion and updating which in some scenarios throws Primary Key or unique key violation.

When I try to execute this procedure from ADO.net, .net application also throws that exception and let me know that something wrong had happen.

But when I try to execute this procedure from EF, it just executes. Neither it show anything nor update anything.

How should I handle or notify user that something wrong had happen?

Ado.Net code is

```<code> SqlConnection sqlConnection = new SqlConnection(@"data source=database01; database=test; user id=test; password=test;");
        SqlCommand cmd = new SqlCommand("[uspUpdateTest]", sqlConnection);
        cmd.CommandType = System.Data.CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("RunID", RunID);
        cmd.Parameters.AddWithValue("RunCode", RunCode);
        sqlConnection.Open();
        var str = cmd.ExecuteNonQuery();
</code>```

Entity Framework Code is

```<code> TestEntities context = new TestEntities();
        var str=context.UpdateRun(RunID, RunCode);
</code>```

答:
We can use the following way for sql raised error exception from entity framework:
Let's say, we have DBContext. So that</p>

```<code>var connection= (SqlConnection)db.Database.Connection;
if (connection != null && connection.State == ConnectionState.Closed)
        {
            connection.Open();
        }
        SqlCommand com = new SqlCommand("spname", connection);
        com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add(new SqlParameter("@parameter", parameter));
                        try
                        {
                            com.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            throw ex.message;
                        } `
</code>```

Body:
In my sql stored procedure, i do some insertion and updating which in some scenarios throws Primary Key or unique key violation.

When I try to execute this procedure from ADO.net, .net application also throws that exception and let me know that something wrong had happen.

But when I try to execute this procedure from EF, it just executes. Neither it show anything nor update anything.

How should I handle or notify user that something wrong had happen?

Ado.Net code is

 SqlConnection sqlConnection = new SqlConnection(@"data source=database01; database=test; user id=test; password=test;");
        SqlCommand cmd = new SqlCommand("[uspUpdateTest]", sqlConnection);
        cmd.CommandType = System.Data.CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("RunID", RunID);
        cmd.Parameters.AddWithValue("RunCode", RunCode);
        sqlConnection.Open();
        var str = cmd.ExecuteNonQuery();

Entity Framework Code is

 TestEntities context = new TestEntities();
        var str=context.UpdateRun(RunID, RunCode);

Body:
We can use the following way for sql raised error exception from entity framework:
Let's say, we have DBContext. So that

var connection= (SqlConnection)db.Database.Connection;
if (connection != null && connection.State == ConnectionState.Closed)
        {
            connection.Open();
        }
        SqlCommand com = new SqlCommand("spname", connection);
        com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add(new SqlParameter("@parameter", parameter));
                        try
                        {
                            com.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            throw ex.message;
                        } `


问:
create video from array of UIImages and save the video to iPhone library. AVAssetLibrary +AVFoundation
Problem in saving video to iPhone Library.
 i have an array of UIImages,and two buttons ,"convertToVideo"&"saveToiPhoneLib"

```

-(IBAction) convertToVideo
{
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

 NSString *documentsDirectory = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;

NSString *savedVideoPath = [documentsDirectory stringByAppendingPathComponent:@"videoOutput"];

printf(" \n\n\n-Video file == %s--\n\n\n",[savedVideoPath UTF8String]);

[self writeImageAsMovie:imageArray toPath:savedVideoPath size:self.view.frame.size duration:3];
}

here i'm passing the imageArray and savedVideoPath to the function below

-(void)writeImageAsMovie:(NSArray *)array toPath:(NSString*)path size:(CGSize)size duration:(int)duration
{

 NSError *error = nil;

 AVAssetWriter *videoWriter = [[AVAssetWriter alloc] initWithURL:
          [NSURL fileURLWithPath:path] fileType:AVFileTypeQuickTimeMovie
                 error:&error];

 NSParameterAssert(videoWriter);

 NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
           AVVideoCodecH264, AVVideoCodecKey,
           [NSNumber numberWithInt:size.width], AVVideoWidthKey,
           [NSNumber numberWithInt:size.height], AVVideoHeightKey,
           nil];
 AVAssetWriterInput* writerInput = [[AVAssetWriterInput
          assetWriterInputWithMediaType:AVMediaTypeVideo
          outputSettings:videoSettings] retain];

// NSDictionary *bufferAttributes = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:kCVPixelFormatType_32ARGB], kCVPixelBufferPixelFormatTypeKey, nil];

 AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor
              assetWriterInputPixelBufferAdaptorWithAssetWriterInput:writerInput
              sourcePixelBufferAttributes:nil];

 NSParameterAssert(writerInput);
 NSParameterAssert([videoWriter canAddInput:writerInput]);
 [videoWriter addInput:writerInput];

 //Start a session:
 [videoWriter startWriting];
 [videoWriter startSessionAtSourceTime:kCMTimeZero];

 CVPixelBufferRef buffer = NULL;

 //convert uiimage to CGImage.

 buffer = [self pixelBufferFromCGImage:[[array objectAtIndex:0] CGImage]];
 [adaptor appendPixelBuffer:buffer withPresentationTime:kCMTimeZero];

 //Write samples:
......

 //Finish the session:
 [writerInput markAsFinished];
 [videoWriter finishWriting];
}

generate a CVPixelBufferRef here

- (CVPixelBufferRef) pixelBufferFromCGImage: (CGImageRef) image
{
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
        [NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey,
        [NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey,
        nil];
    CVPixelBufferRef pxbuffer = NULL;

    CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, self.view.frame.size.width,
            self.view.frame.size.height, kCVPixelFormatType_32ARGB, (CFDictionaryRef) options,
            &pxbuffer);
    NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL);

    CVPixelBufferLockBaseAddress(pxbuffer, 0);
    void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
    NSParameterAssert(pxdata != NULL);

    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pxdata, self.view.frame.size.width,
             self.view.frame.size.height, 8, 4*self.view.frame.size.width, rgbColorSpace,
             kCGImageAlphaNoneSkipFirst);
    NSParameterAssert(context);
    CGContextConcatCTM(context, CGAffineTransformMakeRotation(0));
    CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image),
             CGImageGetHeight(image)), image);
    CGColorSpaceRelease(rgbColorSpace);
    CGContextRelease(context);

    CVPixelBufferUnlockBaseAddress(pxbuffer, 0);

    return pxbuffer;
}
```

saving to the iPhone library

```

-(IBAction) saveToiPhoneLib
{

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

 NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;

 NSString *getImagePath = [basePath stringByAppendingPathComponent:@"videoOutput"];

 printf(" \n\n\n-Video file == %s--\n\n\n",[getImagePath UTF8String]);

 UISaveVideoAtPathToSavedPhotosAlbum ( getImagePath,self, @selector(video:didFinishSavingWithError: contextInfo:), nil);
}

- (void) video: (NSString *) videoPath didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo {
 NSLog(@"Finished saving video with error: %@", error);
}

```

but while saving i m getting error message:-

Finished saving video with error: Error Domain=ALAssetsLibraryErrorDomain Code=-3302 "Invalid data" UserInfo=0x1d59f0 {NSLocalizedFailureReason=There was a problem writing this asset because the data is invalid and cannot be viewed or played., NSLocalizedRecoverySuggestion=Try with different data, NSLocalizedDescription=Invalid data}

please let me know my mistake. thanks in advance

答: That’s simply too much code to check for errors. Make sure you can start the export session, that you really get pixel buffers for your images, that the writer is ready for receiving more data, that the buffer gets appended without errors, that the export session finishes with success and that the output movie file exists and actually contains some data. Only then you can try and save it to the system photo album. Check all the available error information along the way so that you know where the thing breaks for the first time. (Another thing is that you are simply taking code from the web and pasting it together, which is simply not going to work for AV programming.)

Body:
Problem in saving video to iPhone Library.
 i have an array of UIImages,and two buttons ,"convertToVideo"&"saveToiPhoneLib"

-(IBAction) convertToVideo
{
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

 NSString *documentsDirectory = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;

NSString *savedVideoPath = [documentsDirectory stringByAppendingPathComponent:@"videoOutput"];

printf(" \n\n\n-Video file == %s--\n\n\n",[savedVideoPath UTF8String]);

[self writeImageAsMovie:imageArray toPath:savedVideoPath size:self.view.frame.size duration:3];
}

here i'm passing the imageArray and savedVideoPath to the function below

-(void)writeImageAsMovie:(NSArray *)array toPath:(NSString*)path size:(CGSize)size duration:(int)duration
{

 NSError *error = nil;

 AVAssetWriter *videoWriter = [[AVAssetWriter alloc] initWithURL:
          [NSURL fileURLWithPath:path] fileType:AVFileTypeQuickTimeMovie
                 error:&error];

 NSParameterAssert(videoWriter);

 NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
           AVVideoCodecH264, AVVideoCodecKey,
           [NSNumber numberWithInt:size.width], AVVideoWidthKey,
           [NSNumber numberWithInt:size.height], AVVideoHeightKey,
           nil];
 AVAssetWriterInput* writerInput = [[AVAssetWriterInput
          assetWriterInputWithMediaType:AVMediaTypeVideo
          outputSettings:videoSettings] retain];

// NSDictionary *bufferAttributes = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:kCVPixelFormatType_32ARGB], kCVPixelBufferPixelFormatTypeKey, nil];

 AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor
              assetWriterInputPixelBufferAdaptorWithAssetWriterInput:writerInput
              sourcePixelBufferAttributes:nil];

 NSParameterAssert(writerInput);
 NSParameterAssert([videoWriter canAddInput:writerInput]);
 [videoWriter addInput:writerInput];

 //Start a session:
 [videoWriter startWriting];
 [videoWriter startSessionAtSourceTime:kCMTimeZero];

 CVPixelBufferRef buffer = NULL;

 //convert uiimage to CGImage.

 buffer = [self pixelBufferFromCGImage:[[array objectAtIndex:0] CGImage]];
 [adaptor appendPixelBuffer:buffer withPresentationTime:kCMTimeZero];

 //Write samples:
......

 //Finish the session:
 [writerInput markAsFinished];
 [videoWriter finishWriting];
}

generate a CVPixelBufferRef here

- (CVPixelBufferRef) pixelBufferFromCGImage: (CGImageRef) image
{
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
        [NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey,
        [NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey,
        nil];
    CVPixelBufferRef pxbuffer = NULL;

    CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, self.view.frame.size.width,
            self.view.frame.size.height, kCVPixelFormatType_32ARGB, (CFDictionaryRef) options,
            &pxbuffer);
    NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL);

    CVPixelBufferLockBaseAddress(pxbuffer, 0);
    void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
    NSParameterAssert(pxdata != NULL);

    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pxdata, self.view.frame.size.width,
             self.view.frame.size.height, 8, 4*self.view.frame.size.width, rgbColorSpace,
             kCGImageAlphaNoneSkipFirst);
    NSParameterAssert(context);
    CGContextConcatCTM(context, CGAffineTransformMakeRotation(0));
    CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image),
             CGImageGetHeight(image)), image);
    CGColorSpaceRelease(rgbColorSpace);
    CGContextRelease(context);

    CVPixelBufferUnlockBaseAddress(pxbuffer, 0);

    return pxbuffer;
}

saving to the iPhone library

-(IBAction) saveToiPhoneLib
{

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

 NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;

 NSString *getImagePath = [basePath stringByAppendingPathComponent:@"videoOutput"];

 printf(" \n\n\n-Video file == %s--\n\n\n",[getImagePath UTF8String]);

 UISaveVideoAtPathToSavedPhotosAlbum ( getImagePath,self, @selector(video:didFinishSavingWithError: contextInfo:), nil);
}

- (void) video: (NSString *) videoPath didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo {
 NSLog(@"Finished saving video with error: %@", error);
}

but while saving i m getting error message:-

Finished saving video with error: Error Domain=ALAssetsLibraryErrorDomain Code=-3302 "Invalid data" UserInfo=0x1d59f0 {NSLocalizedFailureReason=There was a problem writing this asset because the data is invalid and cannot be viewed or played., NSLocalizedRecoverySuggestion=Try with different data, NSLocalizedDescription=Invalid data}

please let me know my mistake. thanks in advance


问:
regex to allow only once "&" and "-"
I was trying this regex ^[A-Za-z &-]+[A-Za-z]$

This is allowing these strings:

abc && abc

abc -- abc

abc &&-- abc

I want to restrict it to allow only one & or - at a time, i.e., abc & abc.
It should allow both the & and -, but not together, i.e., fruits- apple & orange.

答:
Simple Answer to Allow Only One of & and -

Just move the & and - out of the character class that has the + after it:

```<code>^[A-Za-z ]+[&-][A-Za-z ]+$
</code>```

(I added a + at the end and added a space to the final group, because your examples allow spaces after the punctuation and for multiple letters at the end.)

A cleaner version is this, using the case-insensitive flag:

```<code>/^[a-z ]+[&-][a-z ]+$/i
</code>```

Answer to Allow Both, but Only One Time Each

You edited your question pretty significantly after I posted this, which changed the meaning entirely. To allow both & and - in the same string, but only one time each and not adjacent to each other, you have to get more creative, as in:

```<code>/^[a-z ]+([&-])[a-z ]+(?!\1)[&-][a-z ]+$/i
</code>```

This allows a & or - (the ([&-])) the first time, but only allows the one that hasn't been used the second time. We do this with a negative lookahead group: (?!\1)[&-]. Here's a demo.

Title: regex to allow only once "&" and "-"

Body:
Simple Answer to Allow Only One of & and -

Just move the & and - out of the character class that has the + after it:

^[A-Za-z ]+[&-][A-Za-z ]+$

(I added a + at the end and added a space to the final group, because your examples allow spaces after the punctuation and for multiple letters at the end.)

A cleaner version is this, using the case-insensitive flag:

/^[a-z ]+[&-][a-z ]+$/i

Answer to Allow Both, but Only One Time Each

You edited your question pretty significantly after I posted this, which changed the meaning entirely. To allow both & and - in the same string, but only one time each and not adjacent to each other, you have to get more creative, as in:

/^[a-z ]+([&-])[a-z ]+(?!\1)[&-][a-z ]+$/i

This allows a & or - (the ([&-])) the first time, but only allows the one that hasn't been used the second time. We do this with a negative lookahead group: (?!\1)[&-]. Here's a demo.


问:
React—Change a components state on window.history.popstate
I have a React component that pushes song IDs to the url when the state changes. My problem is that when a user clicks 'back' on their browser, I need to change the state of my SongApp component. How do I do this?</p>

```<code>class SongApp extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      song: props.songId
    }

    this.setSong = this.setSong.bind(this);
  }

  setSong(e) {
    var songId = e.target.id;
    this.setState({song: songId})
    window.history.pushState({song: songId}, '', '?s='+songId)
  }

  render() {
    var id = this.state.song;

    var content = id ? <SongDisplay lyrics={ this.props.songData[id].lyrics } /> : <SongIndex songData={this.props.songData} setSong={this.setSong}/>
    return(
      <div className="song-app">
        {content}
      </div>
    )
  }
}

window.addEventListener('popstate', function(event) {
  console.log('popstate fired!');
  debugger;
  if(event.state.song) {
    // change SongApp state
  }
});
</code>```

答:
I found out you can attach the component's method to a listener:</p>

```<code>  componentDidMount() {
    window.addEventListener("popstate", this.setSongFromHistory);
  }

  setSongFromHistory(e) {
    if(e.state.song){
      e.preventDefault(); // stop request to server for new html
      e.stopPropagation();
      this.setState({song: e.state.song});
      $('html,body').scrollTop(0);
    }
  }
</code>```

Body:
I have a React component that pushes song IDs to the url when the state changes. My problem is that when a user clicks 'back' on their browser, I need to change the state of my SongApp component. How do I do this?

class SongApp extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      song: props.songId
    }

    this.setSong = this.setSong.bind(this);
  }

  setSong(e) {
    var songId = e.target.id;
    this.setState({song: songId})
    window.history.pushState({song: songId}, '', '?s='+songId)
  }

  render() {
    var id = this.state.song;

    var content = id ? <SongDisplay lyrics={ this.props.songData[id].lyrics } /> : <SongIndex songData={this.props.songData} setSong={this.setSong}/>
    return(

        {content}

    )
  }
}

window.addEventListener('popstate', function(event) {
  console.log('popstate fired!');
  debugger;
  if(event.state.song) {
    // change SongApp state
  }
});

Body:
I found out you can attach the component's method to a listener:

  componentDidMount() {
    window.addEventListener("popstate", this.setSongFromHistory);
  }

  setSongFromHistory(e) {
    if(e.state.song){
      e.preventDefault(); // stop request to server for new html
      e.stopPropagation();
      this.setState({song: e.state.song});
      $('html,body').scrollTop(0);
    }
  }