问:
Jquery find element with data starting with some value
I'm looking for a sintax to search inside data of a element starting with a given value, with or without an underscore after it. For example if a give a number like 3:

```<code><span data-filter="3_1"></span>   // I NEED TRUE
<span data-filter="3"></span>   // I NEED TRUE
<span data-filter="33_1"></span>   // I NEED FALSE
<span data-filter="1_3"></span>   // I NEED FALSE
</code>```

$(span[filter^="3"]) doesn't work for 3° example.

Fiddle example: https://jsfiddle.net/fdphzogc/1/

Of course i've inserted an example like 3, but it can be another number with more digits like 465_12, where 465 is what i'm looking for

答:
My advice is after you defined your truth table, you have to translate it into a high-level language.

For example, if I read your post (without the code) I understood you are looking for everything starting with 3.

But if I read your snippet I understood you are looking for exactly "3" or starting "3_".
If this last sentence is true:

```<code>$('span[data-filter^="3_"], span[data-filter="3"]')
</code>```

Body:
I'm looking for a sintax to search inside data of a element starting with a given value, with or without an underscore after it. For example if a give a number like 3:

   // I NEED TRUE
   // I NEED TRUE
   // I NEED FALSE
   // I NEED FALSE

$(span[filter^="3"]) doesn't work for 3° example.

Fiddle example: https://jsfiddle.net/fdphzogc/1/

Of course i've inserted an example like 3, but it can be another number with more digits like 465_12, where 465 is what i'm looking for

Body:
My advice is after you defined your truth table, you have to translate it into a high-level language.

For example, if I read your post (without the code) I understood you are looking for everything starting with 3.

But if I read your snippet I understood you are looking for exactly "3" or starting "3_".
If this last sentence is true:

$('span[data-filter^="3_"], span[data-filter="3"]')


来源: stackexchange

问:
Not sure if it's my query or if I need to add another table
What query can i run to get my articles to pull up along with my pages, will i need to add an intermediate table between articles and pages for me to get all the articles to show up under the specific page.

I would like for query results to match the article with the below page:

TABLES ARE AS FOLLOWS:

```<code>PAGES-
pages.pageId(INT),
pages.pageTitle(VARCHAR),

ARTICLES-
articles.acrticleId(INT),
articles.articleTitle(VARCHAR),
articles.pageId(INT),

VIDEOS-
videos.videoId(INT),
videos.videoTitle(VARCHAR),
videos.videoLoc(VARCHAR),
videos.articlesId(INT),

IMAGES-
images.imageId(INT),
images.imageTitle(VARCHAR),
images.imageLoc(VARCHAR),
images.articlesId(INT),

TEXT-
text.textId(INT),
text.text(medium),
text.articlesId(INT),
</code>```

答:
You need something like this: </p>

```<code>SELECT pageTitle,GROUP_CONCAT(articleTitle)
FROM articles join pages using (pageId)
GROUP BY pageId;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What query can i run to get my articles to pull up along with my pages, will i need to add an intermediate table between articles and pages for me to get all the articles to show up under the specific page.

I would like for query results to match the article with the below page:

TABLES ARE AS FOLLOWS:

PAGES-
pages.pageId(INT),
pages.pageTitle(VARCHAR),

ARTICLES-
articles.acrticleId(INT),
articles.articleTitle(VARCHAR),
articles.pageId(INT),

VIDEOS-
videos.videoId(INT),
videos.videoTitle(VARCHAR),
videos.videoLoc(VARCHAR),
videos.articlesId(INT),

IMAGES-
images.imageId(INT),
images.imageTitle(VARCHAR),
images.imageLoc(VARCHAR),
images.articlesId(INT),

TEXT-
text.textId(INT),
text.text(medium),
text.articlesId(INT),

Body:
You need something like this:

SELECT pageTitle,GROUP_CONCAT(articleTitle)
FROM articles join pages using (pageId)
GROUP BY pageId;


问:
Trying to compile with make on Windows gives error 127
this is the very first time that I try to compile anything in Windows and it already gives me the creeps (not because of Windows that is).
I downloaded a dictionary from here:

https://www.j3e.de/ispell/igerman98/dict/igerman98-20161207.tar.bz2

When I extract the folder then there is a Makefile, so I think that I have to compile the progrmam first. I tried that with two methods: first Cygwin, second MinGW. Both programs are in my PATH.

I use the terminal of both programs to navigate to D:/igerman98 and there I enter

```<code>make
</code>```

The first message I get is:

```<code>$ make
A default make target doesn't exist. You might want to use one of those:
  make hunspell/de_DE.dic hunspell/de_DE.aff (or de_AT or de_CH)
  make myspell/de_DE.dic myspell/de_DE.aff (or de_AT or de_CH)
  make ispell/de_DE.aff ispell/de_DE.hash (or de_AT, de_CH ...)
  make aspell/de_DE.rws (or de_AT, de_CH ...)
  make ligature/rmligs
  make isowordlist-de_DE (or de_AT, de_CH ...)
Did I forget an important one ?-)
</code>```

So I enter again the following:

```<code>make hunspell/de_DE.dic hunspell/de_DE.aff
</code>```

But then I get the following error:

```<code>$ make hunspell/de_DE.dic hunspell/de_DE.aff
test -e all.words.placebo.tmp || echo a > all.words.placebo.tmp
buildhash all.words.placebo.tmp ispell/de_DE_null.aff ispell/de_DE_null.hash
make: buildhash: Command not found
make: *** [ispell/de_DE_null.hash] Error 127
</code>```

What am I doing wrong here? I just want de_DE.dic and de_DE.aff files to be created so I can use them with the spelling module in Textadept...

答: Under Linux, the program buildhash comes with the ispell-package. Under Windows, you can use: ISPELL for Windwos

Body:
this is the very first time that I try to compile anything in Windows and it already gives me the creeps (not because of Windows that is).
I downloaded a dictionary from here:

https://www.j3e.de/ispell/igerman98/dict/igerman98-20161207.tar.bz2

When I extract the folder then there is a Makefile, so I think that I have to compile the progrmam first. I tried that with two methods: first Cygwin, second MinGW. Both programs are in my PATH.

I use the terminal of both programs to navigate to D:/igerman98 and there I enter

make

The first message I get is:

$ make
A default make target doesn't exist. You might want to use one of those:
  make hunspell/de_DE.dic hunspell/de_DE.aff (or de_AT or de_CH)
  make myspell/de_DE.dic myspell/de_DE.aff (or de_AT or de_CH)
  make ispell/de_DE.aff ispell/de_DE.hash (or de_AT, de_CH ...)
  make aspell/de_DE.rws (or de_AT, de_CH ...)
  make ligature/rmligs
  make isowordlist-de_DE (or de_AT, de_CH ...)
Did I forget an important one ?-)

So I enter again the following:

make hunspell/de_DE.dic hunspell/de_DE.aff

But then I get the following error:

$ make hunspell/de_DE.dic hunspell/de_DE.aff
test -e all.words.placebo.tmp || echo a > all.words.placebo.tmp
buildhash all.words.placebo.tmp ispell/de_DE_null.aff ispell/de_DE_null.hash
make: buildhash: Command not found
make: *** [ispell/de_DE_null.hash] Error 127

What am I doing wrong here? I just want de_DE.dic and de_DE.aff files to be created so I can use them with the spelling module in Textadept...


问:
Apache Ignite: how to insert into table with IDENTITY key (SQL Server)
I have a table in SQL Server where the primary key is autogenerated (identity column), i.e.

```<code>CREATE TABLE TableName
(
     table_id INT NOT NULL IDENTITY (1,1),
     some_field VARCHAR(20),

     PRIMARY KEY (table_id)
);
</code>```

Since table_id is an autogenerated column, when I implemented the SqlFieldQuery INSERT clause I do not set any argument to table_id:

```<code>sql = new SqlFieldsQuery("INSERT INTO TableName (some_field) VALUES (?)");
cache.query(sql.setArgs("str");
</code>```

However at runtime I get the following error:

Exception in thread "main" javax.cache.CacheException: class org.apache.ignite.internal.processors.query.IgniteSQLException: Failed to execute DML statement [stmt=INSERT INTO TableName (some_field) VALUES (?), params=["str"]]

at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.query(IgniteCacheProxy.java:807)

  at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.query(IgniteCacheProxy.java:765)

  ...

  Caused by: class org.apache.ignite.internal.processors.query.IgniteSQLException: Failed to execute DML statement [stmt=INSERT INTO TableName (some_field) VALUES (?), params=["str"]]

at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.queryDistributedSqlFields(IgniteH2Indexing.java:1324)

  at org.apache.ignite.internal.processors.query.GridQueryProcessor$5.applyx(GridQueryProcessor.java:1815)
          at org.apache.ignite.internal.processors.query.GridQueryProcessor$5.applyx(GridQueryProcessor.java:1813)
          at org.apache.ignite.internal.util.lang.IgniteOutClosureX.apply(IgniteOutClosureX.java:36)
          at org.apache.ignite.internal.processors.query.GridQueryProcessor.executeQuery(GridQueryProcessor.java:2293)
          at org.apache.ignite.internal.processors.query.GridQueryProcessor.querySqlFields(GridQueryProcessor.java:1820)
          at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.query(IgniteCacheProxy.java:795)
          ... 5 more
      Caused by: class org.apache.ignite.IgniteCheckedException: Key is missing from query
          at org.apache.ignite.internal.processors.query.h2.dml.UpdatePlanBuilder.createSupplier(UpdatePlanBuilder.java:331)
          at org.apache.ignite.internal.processors.query.h2.dml.UpdatePlanBuilder.planForInsert(UpdatePlanBuilder.java:196)
          at org.apache.ignite.internal.processors.query.h2.dml.UpdatePlanBuilder.planForStatement(UpdatePlanBuilder.java:82)
          at org.apache.ignite.internal.processors.query.h2.DmlStatementsProcessor.getPlanForStatement(DmlStatementsProcessor.java:438)
          at org.apache.ignite.internal.processors.query.h2.DmlStatementsProcessor.updateSqlFields(DmlStatementsProcessor.java:164)
          at org.apache.ignite.internal.processors.query.h2.DmlStatementsProcessor.updateSqlFieldsDistributed(DmlStatementsProcessor.java:222)
          at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.queryDistributedSqlFields(IgniteH2Indexing.java:1321)
          ... 11 more

This is how I planned to implement the insertion because it seemed more tedious to get the max table_id from the cache, increment and insert. I thought I could omit the table_id from the insert and let SQL Server insert the pk, but it doesn't seem to work like this.

Can you please tell me how this should typically be implemented in Ignite? I checked the ignite-examples, unfortunately the examples are too simple (i.e. fixed keys only, like 1 or 2).

Moreover, how does Ignite support the use of sequences?

I am using ignite-core 2.2.0. Any help is appreciated! Thank you.

答:
That's true that as for now autoincrement fields are not supported.

As an option, you could generate IDs manually via for example Ignite's ID generator.

Body:
I have a table in SQL Server where the primary key is autogenerated (identity column), i.e.

CREATE TABLE TableName
(
     table_id INT NOT NULL IDENTITY (1,1),
     some_field VARCHAR(20),

     PRIMARY KEY (table_id)
);

Since table_id is an autogenerated column, when I implemented the SqlFieldQuery INSERT clause I do not set any argument to table_id:

sql = new SqlFieldsQuery("INSERT INTO TableName (some_field) VALUES (?)");
cache.query(sql.setArgs("str");

However at runtime I get the following error:

Exception in thread "main" javax.cache.CacheException: class org.apache.ignite.internal.processors.query.IgniteSQLException: Failed to execute DML statement [stmt=INSERT INTO TableName (some_field) VALUES (?), params=["str"]]

at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.query(IgniteCacheProxy.java:807)

  at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.query(IgniteCacheProxy.java:765)

  ...

  Caused by: class org.apache.ignite.internal.processors.query.IgniteSQLException: Failed to execute DML statement [stmt=INSERT INTO TableName (some_field) VALUES (?), params=["str"]]

at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.queryDistributedSqlFields(IgniteH2Indexing.java:1324)

  at org.apache.ignite.internal.processors.query.GridQueryProcessor$5.applyx(GridQueryProcessor.java:1815)
          at org.apache.ignite.internal.processors.query.GridQueryProcessor$5.applyx(GridQueryProcessor.java:1813)
          at org.apache.ignite.internal.util.lang.IgniteOutClosureX.apply(IgniteOutClosureX.java:36)
          at org.apache.ignite.internal.processors.query.GridQueryProcessor.executeQuery(GridQueryProcessor.java:2293)
          at org.apache.ignite.internal.processors.query.GridQueryProcessor.querySqlFields(GridQueryProcessor.java:1820)
          at org.apache.ignite.internal.processors.cache.IgniteCacheProxy.query(IgniteCacheProxy.java:795)
          ... 5 more
      Caused by: class org.apache.ignite.IgniteCheckedException: Key is missing from query
          at org.apache.ignite.internal.processors.query.h2.dml.UpdatePlanBuilder.createSupplier(UpdatePlanBuilder.java:331)
          at org.apache.ignite.internal.processors.query.h2.dml.UpdatePlanBuilder.planForInsert(UpdatePlanBuilder.java:196)
          at org.apache.ignite.internal.processors.query.h2.dml.UpdatePlanBuilder.planForStatement(UpdatePlanBuilder.java:82)
          at org.apache.ignite.internal.processors.query.h2.DmlStatementsProcessor.getPlanForStatement(DmlStatementsProcessor.java:438)
          at org.apache.ignite.internal.processors.query.h2.DmlStatementsProcessor.updateSqlFields(DmlStatementsProcessor.java:164)
          at org.apache.ignite.internal.processors.query.h2.DmlStatementsProcessor.updateSqlFieldsDistributed(DmlStatementsProcessor.java:222)
          at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.queryDistributedSqlFields(IgniteH2Indexing.java:1321)
          ... 11 more

This is how I planned to implement the insertion because it seemed more tedious to get the max table_id from the cache, increment and insert. I thought I could omit the table_id from the insert and let SQL Server insert the pk, but it doesn't seem to work like this.

Can you please tell me how this should typically be implemented in Ignite? I checked the ignite-examples, unfortunately the examples are too simple (i.e. fixed keys only, like 1 or 2).

Moreover, how does Ignite support the use of sequences?

I am using ignite-core 2.2.0. Any help is appreciated! Thank you.


问:
Can't get an entity property
There is a problem with my Db which I figured only now, when I started to work at the web api.

 My USER entity:

```<code>public class User { get; set; }
{
    public int UserId { get; set; }
    public string Name { get; set; }
}
</code>```

And this is ACTIVITY

```<code>public class Activity

{
    public int ActivityId { get; set; }
    public User User { get; set; }
}
</code>```

I added an activity and checked in SSMS. Everything seems to be good, there is a field named UserId which stores the id. My problem is when I try to get a User from an Activity because I keep getting null objects. I didn't set anything special in my DbContext for this.

This is where I'm trying to get an User from an Activity object:

```<code>public ActionResult ActivityAuthor(int activityId)
{
    Activity activityItem = unitOfWork.Activity.Get(activityId);
    return Json(unitOfWork.User.Get(activityItem.User.UserId));
}
</code>```

Relation between User and Activity

答:
my psychic debugging powers are telling me that you're querying the Activity table without Include-ing the User

```<code>using System.Data.Entity;

...

var activities = context.Activities
    .Include(x => x.User)
    .ToList();
</code>```

Alternatively, you don't need Include if you select properties of User as part of your query

```<code>var vms = context.Activities
    .Select(x => new ActivityVM() {UserName = x.User.Name})
    .ToList();
</code>```

Title: Can't get an entity property

Body:
There is a problem with my Db which I figured only now, when I started to work at the web api.

 My USER entity:

public class User { get; set; }
{
    public int UserId { get; set; }
    public string Name { get; set; }
}

And this is ACTIVITY

public class Activity

{
    public int ActivityId { get; set; }
    public User User { get; set; }
}

I added an activity and checked in SSMS. Everything seems to be good, there is a field named UserId which stores the id. My problem is when I try to get a User from an Activity because I keep getting null objects. I didn't set anything special in my DbContext for this.

This is where I'm trying to get an User from an Activity object:

public ActionResult ActivityAuthor(int activityId)
{
    Activity activityItem = unitOfWork.Activity.Get(activityId);
    return Json(unitOfWork.User.Get(activityItem.User.UserId));
}

Relation between User and Activity

Body:
my psychic debugging powers are telling me that you're querying the Activity table without Include-ing the User

using System.Data.Entity;

...

var activities = context.Activities
    .Include(x => x.User)
    .ToList();

Alternatively, you don't need Include if you select properties of User as part of your query

var vms = context.Activities
    .Select(x => new ActivityVM() {UserName = x.User.Name})
    .ToList();


问:
How to check if a button hasn't been clicked in a certain amount of time (Javascript)
I am making a story kind of html page where you anger the narrator by pressing "t". He says "I bet you can't go a full 5 seconds without pressing t."

Anyone know how I could check if a button isn't clicked within 5 seconds, and if it is clicked make something else happen as well.

I tried to use seconds to solve this problem, as I am very new to JavaScript, this is currently being worked on.

```<code>  function timenow() {
    var now = today.getSeconds();
  }
  function timelater() {
    var later = today.getSeconds();
  }

  function clicked() {
    if (!document.getElementById("form-search") && document.getElementById("fake-search").value == "t") {
      if (a==8) {
        alert("Alright Smart Guy, lets just delete everything on the page!");
        document.body.style.opacity = "0";
        document.getElementById("google_search").style.cursor= "wait";
        a+=1;
      }
      else if (a==9) {
        alert("You know what... I'm done, I'm Done! If you can not press t for 5 seconds, I'll give you everything back.");
        a+=1;
        timenow();
        setTimeout(timelater(), 5000);
        console.log(now);
        console.log(later);
      }
    else {
      null;
    }
</code>```

答:
First, you would use setTimeout() to start a timer as soon as the button is displayed (In this case, on page load).  Second, we will use onClick to call a function when the button is pressed.  If the button is pressed, we call clearTimeout() so that the timeout code doesn't run.  If the button is not pressed, the timeout will expire and the timeout code will run.

//first we define what happens when the button is not pressed in time.
function notPressed() {
  alert("You didn't press the button!!!");
}

//next we define what happens if the button IS pressed in time.
function pressed() {
  alert("You pressed the button!");
  //Here we must clear the timer or it will run even after the button is pressed!
  clearTimeout(btnTimer);
}

//finally we start the timer.  We specify the time using milliseconds in the second parameter.
var btnTimer = window.setTimeout(notPressed,5000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" onClick="pressed()" value="Click me" /></code>```

Body:
I am making a story kind of html page where you anger the narrator by pressing "t". He says "I bet you can't go a full 5 seconds without pressing t."

Anyone know how I could check if a button isn't clicked within 5 seconds, and if it is clicked make something else happen as well.

I tried to use seconds to solve this problem, as I am very new to JavaScript, this is currently being worked on.

  function timenow() {
    var now = today.getSeconds();
  }
  function timelater() {
    var later = today.getSeconds();
  }

  function clicked() {
    if (!document.getElementById("form-search") && document.getElementById("fake-search").value == "t") {
      if (a==8) {
        alert("Alright Smart Guy, lets just delete everything on the page!");
        document.body.style.opacity = "0";
        document.getElementById("google_search").style.cursor= "wait";
        a+=1;
      }
      else if (a==9) {
        alert("You know what... I'm done, I'm Done! If you can not press t for 5 seconds, I'll give you everything back.");
        a+=1;
        timenow();
        setTimeout(timelater(), 5000);
        console.log(now);
        console.log(later);
      }
    else {
      null;
    }

Body:
First, you would use setTimeout() to start a timer as soon as the button is displayed (In this case, on page load).  Second, we will use onClick to call a function when the button is pressed.  If the button is pressed, we call clearTimeout() so that the timeout code doesn't run.  If the button is not pressed, the timeout will expire and the timeout code will run.

//first we define what happens when the button is not pressed in time.
function notPressed() {
  alert("You didn't press the button!!!");
}

//next we define what happens if the button IS pressed in time.
function pressed() {
  alert("You pressed the button!");
  //Here we must clear the timer or it will run even after the button is pressed!
  clearTimeout(btnTimer);
}

//finally we start the timer.  We specify the time using milliseconds in the second parameter.
var btnTimer = window.setTimeout(notPressed,5000);

<input type="button" onClick="pressed()" value="Click me" />


问:
Java real time strategy game development
I'm coming to the end of my first year of CS and I thought a great way to consolidate all the things I've learnt this year would be a personal game project.

I would like to implement a 2D based rts, I'm thinking along the lines of starcraft I, warcraft II or even command and conquer. I will have about 3 months without interruptions to implement the game.

So to anyone experienced with java game programming, I have a few questions:

Is it realistic to design a 2D rts engine from scratch in 3 months?
If so what are some good books/resources to get started?

Would it be better to modify some existing project? I would think the experience of having to work with a lot of someone else's code would be good since our exposure to such topics in an undergrad cs degree seems very rare, if non-existent.

Are there any decent open source 2d rts projects that anyone could recommend? I've looked through a few but most seem to be written in c/c++

My humble thanks

Edit: Thanks for the quick responses, I think that perhaps it was a bad idea to post this in a rush since I think I misrepresented what I want to do.

When I say "along the lines of warcraft II etc" I mean more like that style of rts using sprites. I don't intend to implement a game nearly that complex, more like just a basic prototype.

My goal would be some thing more like a flat textured map with some basic obstacles like trees, a single unit producing structure like a barracks. I'd like to have the units to have health bars, be able to move and attack and die (and possible morph into another unit).

Far off goals would be to implement some basic pathing using a modified version of the dijkstra shortest path algorithm, ranged units with missle attack, etc.

I don't plan to implement any opponents or ai or networking or anything like that.

答: Well if it gives you any hope at all, my team and I are currently working on an RTS game called "The Genesis Project". We call ourselves MotherBoard Games, or MBG for short. If you would like, I am always looking for more coders. You can email me at mpmn5891@gmail.com, I can give you some advice and tips form my 6 year experience, 2 of which have been spent making this game (to give you a scope)</p>

ContentLicense: CC BY-SA 2.5


问:
SVN to Git migration : Premature end of file
I am using Subgit to migrate SVN repos to Git. It is a huge repo (Size of git repo is 86 GB after 75% progress). I am getting following error after 75% progress. I tried readTimeout = 600000 in subgit config but no success.

Can anyone please suggest me what this error is about and is there any configuration in SVN client/Subgit which I can tweak to fix this issue?

```<code>[2017-12-02 07:03:53.091][subgit-install][1] svn: E175002: Processing REPORT
request response failed: Premature end of file. (/svn/pcs/!svn/vcc/default)
svn: E175002: REPORT request failed on '/svn/pcs/!svn/vcc/default'
com.syntevo.svngitkit.core.a.i: svn: E175002: Processing REPORT request
response failed: Premature end of file. (/svn/pcs/!svn/vcc/default)
svn: E175002: REPORT request failed on '/svn/pcs/!svn/vcc/default'
at com.syntevo.svngitkit.core.a.i.a(SourceFile:29)
at com.syntevo.svngitkit.core.b.N.b(SourceFile:655)
at com.syntevo.svngitkit.core.b.N.a(SourceFile:357)
at com.syntevo.svngitkit.core.b.N.a(SourceFile:317)
at com.syntevo.svngitkit.core.b.N.a(SourceFile:263)
at com.syntevo.svngitkit.core.b.N.a(SourceFile:102)
at com.syntevo.svngitkit.core.b.ac.c(SourceFile:43)
at com.syntevo.svngitkit.core.b.ac.b(SourceFile:36)
at org.tmatesoft.translator.k.ap.a(SourceFile:1269)
at org.tmatesoft.translator.k.ap.c(SourceFile:885)
at org.tmatesoft.translator.k.ap.a(SourceFile:908)
at org.tmatesoft.translator.k.ap.b(SourceFile:965)
at org.tmatesoft.translator.k.ap.a(SourceFile:587)
at org.tmatesoft.translator.k.ap.a(SourceFile:558)
at org.tmatesoft.translator.k.d.i.a(SourceFile:203)
at org.tmatesoft.translator.k.d.i.c(SourceFile:90)
at org.tmatesoft.translator.a.Q.b(SourceFile:53)
at org.tmatesoft.translator.a.u.a(SourceFile:23)
at org.tmatesoft.translator.d.a(SourceFile:186)
at org.tmatesoft.translator.d.a(SourceFile:137)
at org.tmatesoft.translator.d.a(SourceFile:51)
at org.tmatesoft.translator.process.f.d(SourceFile:136)
at org.tmatesoft.translator.process.f.c(SourceFile:106)
at org.tmatesoft.translator.d.a(SourceFile:74)
at org.tmatesoft.translator.d.a(SourceFile:65)
at org.tmatesoft.translator.SubGit.main(SourceFile:10)
Caused by: org.tmatesoft.svn.core.SVNException: svn: E175002: Processing REPORT request response failed: Premature end of file.
(/svn/pcs/!svn/vcc/default)
</code>```

答:
from the description and the stacktrace it look like the SVN repository is being accessed over HTTP(S).
If that's the case, try to enable http spooling by enabling svn.httpSpooling:

[svn]

```<code># enable HTTP requests spooling to prevent server-side timeout when request processing takes long time.
httpSpooling = true
</code>```

Another possible acuse for this is incorrect mapping configuration,
but it's hard to tell having stacktrace only what exactly is set improperly, it requires additional analysis.
Try to restart the translation with enabled httpSpooling,
if it fails - please send SubGit's log (subgit-import-.zip or subgit-install-.zip)
along with SVN log ('svn log -v' command output) to support@subgit.com for analysis.
With these log it will be possible to find out the cause and resolve the issue.

Body:
I am using Subgit to migrate SVN repos to Git. It is a huge repo (Size of git repo is 86 GB after 75% progress). I am getting following error after 75% progress. I tried readTimeout = 600000 in subgit config but no success.

Can anyone please suggest me what this error is about and is there any configuration in SVN client/Subgit which I can tweak to fix this issue?

[2017-12-02 07:03:53.091][subgit-install][1] svn: E175002: Processing REPORT
request response failed: Premature end of file. (/svn/pcs/!svn/vcc/default)
svn: E175002: REPORT request failed on '/svn/pcs/!svn/vcc/default'
com.syntevo.svngitkit.core.a.i: svn: E175002: Processing REPORT request
response failed: Premature end of file. (/svn/pcs/!svn/vcc/default)
svn: E175002: REPORT request failed on '/svn/pcs/!svn/vcc/default'
at com.syntevo.svngitkit.core.a.i.a(SourceFile:29)
at com.syntevo.svngitkit.core.b.N.b(SourceFile:655)
at com.syntevo.svngitkit.core.b.N.a(SourceFile:357)
at com.syntevo.svngitkit.core.b.N.a(SourceFile:317)
at com.syntevo.svngitkit.core.b.N.a(SourceFile:263)
at com.syntevo.svngitkit.core.b.N.a(SourceFile:102)
at com.syntevo.svngitkit.core.b.ac.c(SourceFile:43)
at com.syntevo.svngitkit.core.b.ac.b(SourceFile:36)
at org.tmatesoft.translator.k.ap.a(SourceFile:1269)
at org.tmatesoft.translator.k.ap.c(SourceFile:885)
at org.tmatesoft.translator.k.ap.a(SourceFile:908)
at org.tmatesoft.translator.k.ap.b(SourceFile:965)
at org.tmatesoft.translator.k.ap.a(SourceFile:587)
at org.tmatesoft.translator.k.ap.a(SourceFile:558)
at org.tmatesoft.translator.k.d.i.a(SourceFile:203)
at org.tmatesoft.translator.k.d.i.c(SourceFile:90)
at org.tmatesoft.translator.a.Q.b(SourceFile:53)
at org.tmatesoft.translator.a.u.a(SourceFile:23)
at org.tmatesoft.translator.d.a(SourceFile:186)
at org.tmatesoft.translator.d.a(SourceFile:137)
at org.tmatesoft.translator.d.a(SourceFile:51)
at org.tmatesoft.translator.process.f.d(SourceFile:136)
at org.tmatesoft.translator.process.f.c(SourceFile:106)
at org.tmatesoft.translator.d.a(SourceFile:74)
at org.tmatesoft.translator.d.a(SourceFile:65)
at org.tmatesoft.translator.SubGit.main(SourceFile:10)
Caused by: org.tmatesoft.svn.core.SVNException: svn: E175002: Processing REPORT request response failed: Premature end of file.
(/svn/pcs/!svn/vcc/default)

Body:
from the description and the stacktrace it look like the SVN repository is being accessed over HTTP(S).
If that's the case, try to enable http spooling by enabling svn.httpSpooling:

[svn]

# enable HTTP requests spooling to prevent server-side timeout when request processing takes long time.
httpSpooling = true

Another possible acuse for this is incorrect mapping configuration,
but it's hard to tell having stacktrace only what exactly is set improperly, it requires additional analysis.
Try to restart the translation with enabled httpSpooling,
if it fails - please send SubGit's log (subgit-import-.zip or subgit-install-.zip)
along with SVN log ('svn log -v' command output) to support@subgit.com for analysis.
With these log it will be possible to find out the cause and resolve the issue.


问:
Using new \stdClass to get all values from a table
```<code>public static function getUpdates() {

        $stmt = self::db()->run('SELECT * FROM b_updates ORDER BY ID DESC LIMIT 1');
        $settings = new \StdClass;

        if($stmt->rowCount() > 0) {

            while($load = $stmt->fetch()) {

                $settings->{$load->title} = $load->brief;

              }
           return $settings;
        }
    }
</code>```

I have this Code above am using that on a small scale framework. but I want to get more rows. Example as you can see I can only get Title and Brief.. I want to be able to access more rows using the code but it seems hard to me.

This is what am looking for but it has error

```<code>public static function getUpdates() {

        $stmt = self::db()->run('SELECT * FROM b_updates ORDER BY ID DESC LIMIT 1');
        $settings = new \StdClass;

        if($stmt->rowCount() > 0) {

            while($load = $stmt->fetch()) {

                $settings->$load->title;
                $setting->$load->brief;
                $settings->$load->comments;
                $settings->$load->status;

              }
           return $settings;
        }
    }
</code>```

I would appreciate being helped or if any other solution would be given to me better :)

答:
you can use the fetchAll() method and you can specify the fetch_style to choose what kind of type should be fetched.

more info in the documentation:
http://php.net/manual/en/pdostatement.fetchall.php

Body:
public static function getUpdates() {

        $stmt = self::db()->run('SELECT * FROM b_updates ORDER BY ID DESC LIMIT 1');
        $settings = new \StdClass;

        if($stmt->rowCount() > 0) {

            while($load = $stmt->fetch()) {

                $settings->{$load->title} = $load->brief;

              }
           return $settings;
        }
    }

I have this Code above am using that on a small scale framework. but I want to get more rows. Example as you can see I can only get Title and Brief.. I want to be able to access more rows using the code but it seems hard to me.

This is what am looking for but it has error

public static function getUpdates() {

        $stmt = self::db()->run('SELECT * FROM b_updates ORDER BY ID DESC LIMIT 1');
        $settings = new \StdClass;

        if($stmt->rowCount() > 0) {

            while($load = $stmt->fetch()) {

                $settings->$load->title;
                $setting->$load->brief;
                $settings->$load->comments;
                $settings->$load->status;

              }
           return $settings;
        }
    }

I would appreciate being helped or if any other solution would be given to me better :)


问:
cx_freeze executable not working with playsound after build
A simple working code with playsound module is giving following errors when I run the exe generated by cx_freeze while actual Python code runs without any errors.

```<code>waqas@waqas-pc:~/sound$ ./build/exe.linux-x86_64-2.7/sound.py
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/cx_Freeze/initscripts/__startup__.py", line 14, in run
    module.run()
  File "/usr/local/lib/python2.7/dist-packages/cx_Freeze/initscripts/Console.py", line 26, in run
    exec(code, m.__dict__)
  File "sound.py", line 20, in <module>
    play_tune(tune)
  File "sound.py", line 14, in play_tune
    playsound.playsound(tune,True)
  File "/usr/local/lib/python2.7/dist-packages/playsound.py", line 91, in _playsoundNix
    import gi
  File "/usr/lib/python2.7/dist-packages/gi/__init__.py", line 42, in <module>
    from . import _gi
ImportError: No module named _error
</code>```

How can I get this issue fixed?

My setup.py file for cx_freeze looks like below:

```<code>import sys
from cx_Freeze import setup, Executable

packages  = ["playsound", "os", "time", "multiprocessing"]
Sound = Executable(
    script = "sound.py",
    targetName = "sound.py",
    )
setup(name = "sound" ,
      version = "0.1" ,
      options = {"build_exe": {"packages": packages}},
      description = "" ,
      executables = [Sound]
      )
</code>```

This is the code snippet I am trying to run:

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

import playsound
import os, time

def get_tune(tune_dir, tune_ext):
    for file in os.listdir(tune_dir):
        if file.endswith(tune_ext):
           return os.path.join(tune_dir, file)

def play_tune(tune):
    playsound.playsound(tune,True)

if __name__ == '__main__':
    tune = get_tune("./tunes", "mp3")
    play_tune(tune)
    x = raw_input("\n\n\t\tPress Any key to exit")
</code>```

python versoin 2.7.13

OS: Ubuntu 17:04 64 bit

cx_freeze version 5.1

playsound version 1.2.2

答: I finally solved it. I added "gi" to packages in my setup.py. Didn't understand why I had to add this additional package, but worked for me.

ContentLicense: CC BY-SA 4.0

Body:
A simple working code with playsound module is giving following errors when I run the exe generated by cx_freeze while actual Python code runs without any errors.

waqas@waqas-pc:~/sound$ ./build/exe.linux-x86_64-2.7/sound.py
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/cx_Freeze/initscripts/__startup__.py", line 14, in run
    module.run()
  File "/usr/local/lib/python2.7/dist-packages/cx_Freeze/initscripts/Console.py", line 26, in run
    exec(code, m.__dict__)
  File "sound.py", line 20, in <module>
    play_tune(tune)
  File "sound.py", line 14, in play_tune
    playsound.playsound(tune,True)
  File "/usr/local/lib/python2.7/dist-packages/playsound.py", line 91, in _playsoundNix
    import gi
  File "/usr/lib/python2.7/dist-packages/gi/__init__.py", line 42, in <module>
    from . import _gi
ImportError: No module named _error

How can I get this issue fixed?

My setup.py file for cx_freeze looks like below:

import sys
from cx_Freeze import setup, Executable

packages  = ["playsound", "os", "time", "multiprocessing"]
Sound = Executable(
    script = "sound.py",
    targetName = "sound.py",
    )
setup(name = "sound" ,
      version = "0.1" ,
      options = {"build_exe": {"packages": packages}},
      description = "" ,
      executables = [Sound]
      )

This is the code snippet I am trying to run:

#!/usr/bin/env python

import playsound
import os, time

def get_tune(tune_dir, tune_ext):
    for file in os.listdir(tune_dir):
        if file.endswith(tune_ext):
           return os.path.join(tune_dir, file)

def play_tune(tune):
    playsound.playsound(tune,True)

if __name__ == '__main__':
    tune = get_tune("./tunes", "mp3")
    play_tune(tune)
    x = raw_input("\n\n\t\tPress Any key to exit")

python versoin 2.7.13

OS: Ubuntu 17:04 64 bit

cx_freeze version 5.1

playsound version 1.2.2


问:
How to depend on a test Maven jar in Bazel?
Some Maven artifacts in addition to the main jar provide a separate test jar which contains classes to aid with writing tests that use the dependency. kafka-streams is one example. In Gradle it's possible to depend on such a jar using classifier: "test" (if the test jar has -test.jar suffix) and in Maven that would be <type>test-jar</type>. How to add a test jar to a Bazel workspace?

答:
I think this feature is missing from maven_jar.

I could write a rule for the main jar:

```<code>maven_jar(
    name = "org_apache_kafka",
    artifact = "org.apache.kafka:kafka-streams:1.0.0",
    sha1 = "a6c87c367176beb7650eb2df173fd9fe6e38656f",
)
</code>```

But I could not write one for the test jar, this didn't work:

```<code>maven_jar(
    name = "org_apache_kafka_test",
    artifact = "org.apache.kafka:kafka-streams:1.0.0-test",
    sha1 = "b275b72148aad7a59cc12f1005507d61fc0ae77b",
)
</code>```

I recommend filing a feature request at https://github.com/bazelbuild/bazel/issues/new .

Body:
I think this feature is missing from maven_jar.

I could write a rule for the main jar:

maven_jar(
    name = "org_apache_kafka",
    artifact = "org.apache.kafka:kafka-streams:1.0.0",
    sha1 = "a6c87c367176beb7650eb2df173fd9fe6e38656f",
)

But I could not write one for the test jar, this didn't work:

maven_jar(
    name = "org_apache_kafka_test",
    artifact = "org.apache.kafka:kafka-streams:1.0.0-test",
    sha1 = "b275b72148aad7a59cc12f1005507d61fc0ae77b",
)

I recommend filing a feature request at https://github.com/bazelbuild/bazel/issues/new .


问:
necessity of Dispose method mocking EF core with the in memory provider
Background

I'm working on a asp.net core application that uses Entity Framework Core as it's orm. For unit testing I'm using microsoft's in memory provider (Microsoft.EntityFrameworkCore.InMemory specifically version 1.1.0) to manually mock the database with a class that is derived from my DBContext.

MockDBContext.cs:

```<code>public class MockDBContext:DBContext{
    public MockDBContext:base(
        new DbContextOptionsBuilder<DBContext>().UseInMemoryDatabase(
            Guid.NewGuid().ToString()
        ).Options
    ){}
    public override void Dispose(){}
    public void clear(){
        base.Dispose();
    }
}
</code>```

where a new unique in memory database is created for each context.

I'm currently overriding Dispose to do nothing to allow me to check values written by the target methods, which have using(DBContext... inside them, otherwise checking would throw a ObjectDisposedException when I run the assert in my tests. I currently have another method called clear that I can manually call that calls base.Dispose in MockDBContext.

Question

My question is, since the mock database is in memory, do I actually need to dispose it? or will it get garbage collected if I don't bother with calling clear inside a try finally for each test

答: As long as your Memory db context no dependencies like a db connection or file resources that should be freed on dispose, you can leave the dispose empty. All references that are out of scope will be collected automatically when there is no reference to the object.</p>

Body:
Background

I'm working on a asp.net core application that uses Entity Framework Core as it's orm. For unit testing I'm using microsoft's in memory provider (Microsoft.EntityFrameworkCore.InMemory specifically version 1.1.0) to manually mock the database with a class that is derived from my DBContext.

MockDBContext.cs:

public class MockDBContext:DBContext{
    public MockDBContext:base(
        new DbContextOptionsBuilder<DBContext>().UseInMemoryDatabase(
            Guid.NewGuid().ToString()
        ).Options
    ){}
    public override void Dispose(){}
    public void clear(){
        base.Dispose();
    }
}

where a new unique in memory database is created for each context.

I'm currently overriding Dispose to do nothing to allow me to check values written by the target methods, which have using(DBContext... inside them, otherwise checking would throw a ObjectDisposedException when I run the assert in my tests. I currently have another method called clear that I can manually call that calls base.Dispose in MockDBContext.

Question

My question is, since the mock database is in memory, do I actually need to dispose it? or will it get garbage collected if I don't bother with calling clear inside a try finally for each test


问:
Tokbox archiving callback url always returns null on .Net
I have a .Net server with .Net SDK tokbox sdk.

I need to know when archiving has been uploaded to my AWS S3 bucket, and in order to do that I need to receive JSON callback url.

Being my url https://company.com/home/archivingvideo I am trying, on HomeController.cs

```<code>[HttpPost]
[AllowAnonymous]
public ActionResult ArchivingVideo(String param)
{

[HttpPost]
[AllowAnonymous]
public ActionResult ArchivingVideo(Object param)
{

[HttpPost]
[AllowAnonymous]
public ActionResult ArchivingVideo(Newtonsoft.Json.Linq.JObject param)
{
</code>```

String function receives null parameter.
Object function receives {} paramenter.
Newtonsoft.Json.Linq.JObject is not called

Do you know which type should I try to get callback information? I have tried sending me a JSON file with POSTMAN and I receive a String.

Thanks

答: In order to have the archive URL, you need to poll the server, because the time it takes to upload to S3 is variable. You can, for instance, do a GET every 5 seconds, and, eventually, you will get the download URL.</p>

Body:
I have a .Net server with .Net SDK tokbox sdk.

I need to know when archiving has been uploaded to my AWS S3 bucket, and in order to do that I need to receive JSON callback url.

Being my url https://company.com/home/archivingvideo I am trying, on HomeController.cs

[HttpPost]
[AllowAnonymous]
public ActionResult ArchivingVideo(String param)
{

[HttpPost]
[AllowAnonymous]
public ActionResult ArchivingVideo(Object param)
{

[HttpPost]
[AllowAnonymous]
public ActionResult ArchivingVideo(Newtonsoft.Json.Linq.JObject param)
{

String function receives null parameter.
Object function receives {} paramenter.
Newtonsoft.Json.Linq.JObject is not called

Do you know which type should I try to get callback information? I have tried sending me a JSON file with POSTMAN and I receive a String.

Thanks


问:
CocosSharp game on Android startup takes a long time to draw graphics
We have a somewhat simple game written using CocosSharp. The game is within another Xamarin.Forms app. When the player clicks to play the game, we bring them to a splash screen. On iOS this screen displays immediately but on Android, the screen is just black for about 15 seconds. The music plays pretty much immediately on both platforms.

The following is called from the ViewCreated event of the CocosSharpView.

```<code>InitializeAudio();
var scene = new Scenes.SplashScene(GameView);
GameView.RunWithScene(scene);
</code>```

The hang up seems to be when creating labels. The following take ~10 seconds to complete with 99% of it being in the constructor of the first label. We call our CreateText in the constructor.

```<code>    private void CreateText()
    {
        var label = new CCLabel("Text 1", "BD_CARTOON_SHOUT.TTF", 80)
        {
            PositionX = layer.ContentSize.Width / 2.0f,
            PositionY = layer.ContentSize.Height / 1.5f,
            Color = CCColor3B.DarkGray
        };
        layer.AddChild(label);

        label = new CCLabel("Text 2", "BD_CARTOON_SHOUT.TTF", 60)
        {
            PositionX = layer.ContentSize.Width / 2.0f,
            PositionY = 50f,
            Color = CCColor3B.DarkGray
        };

        layer.AddChild(label);
    }
</code>```

Keep in mind this only happens on Android.
Thanks in advance!

答:
I had the same issue several weeks ago. The problem was CCLabel constructor
where it didn't know which type of font are you using and therefore trying all other types before finally trying the last one which is correct. You need to specify font type in CCLabel constructor like this:

```<code>    var label = new CCLabel("Text 1", "BD_CARTOON_SHOUT.TTF", 80, CCLabelFormat.SystemFont);
</code>```

Hope it helps.

Body:
We have a somewhat simple game written using CocosSharp. The game is within another Xamarin.Forms app. When the player clicks to play the game, we bring them to a splash screen. On iOS this screen displays immediately but on Android, the screen is just black for about 15 seconds. The music plays pretty much immediately on both platforms.

The following is called from the ViewCreated event of the CocosSharpView.

InitializeAudio();
var scene = new Scenes.SplashScene(GameView);
GameView.RunWithScene(scene);

The hang up seems to be when creating labels. The following take ~10 seconds to complete with 99% of it being in the constructor of the first label. We call our CreateText in the constructor.

    private void CreateText()
    {
        var label = new CCLabel("Text 1", "BD_CARTOON_SHOUT.TTF", 80)
        {
            PositionX = layer.ContentSize.Width / 2.0f,
            PositionY = layer.ContentSize.Height / 1.5f,
            Color = CCColor3B.DarkGray
        };
        layer.AddChild(label);

        label = new CCLabel("Text 2", "BD_CARTOON_SHOUT.TTF", 60)
        {
            PositionX = layer.ContentSize.Width / 2.0f,
            PositionY = 50f,
            Color = CCColor3B.DarkGray
        };

        layer.AddChild(label);
    }

Keep in mind this only happens on Android.
Thanks in advance!

Body:
I had the same issue several weeks ago. The problem was CCLabel constructor
where it didn't know which type of font are you using and therefore trying all other types before finally trying the last one which is correct. You need to specify font type in CCLabel constructor like this:

    var label = new CCLabel("Text 1", "BD_CARTOON_SHOUT.TTF", 80, CCLabelFormat.SystemFont);

Hope it helps.


问:
How to make something happen ONLY when clicking in an exact coordinate
I just wanted to know how I could make something on a canvas change clicking ONLY on a specific area of the canvas.

Let's say my canvas is of width 400px and height 400px, and I am drawing a face.
If I click on an eye, I want it to change. Let's say the eye is in the coordinates (drawn with .arc()) (135,70,15,0,Math.PI*2,true).

How can I make it so that when I click anywhere inside said eye, and nowhere else, something happens?

Thanks a lot!!

答:
You need to manually compute if the mouse is in the eye. The best, simple and most precise solution would be to use ctx.isPointInPath. This API will tell you if a point is in the current shape you are drawing. Example :

```<code>ctx.arc(135,70,15,0,Math.PI*2,true)

if(ctx.isPointInPath(your_mouse.x, your_mouse.y)) {
    doSomething()
}
</code>```

Else you can do some hit-testing, but that's way more complicated depending on the shape of your object. Example for a rectangle :

```<code>if(
    mouse.x > rect.x && mouse.y > rect.y &&
    mouse.x < (rect.x + rect.width) && mouse.y < (rect.y + rect.height)
) {
    doSomething()
}
</code>```

Body:
You need to manually compute if the mouse is in the eye. The best, simple and most precise solution would be to use ctx.isPointInPath. This API will tell you if a point is in the current shape you are drawing. Example :

ctx.arc(135,70,15,0,Math.PI*2,true)

if(ctx.isPointInPath(your_mouse.x, your_mouse.y)) {
    doSomething()
}

Else you can do some hit-testing, but that's way more complicated depending on the shape of your object. Example for a rectangle :

if(
    mouse.x > rect.x && mouse.y > rect.y &&
    mouse.x < (rect.x + rect.width) && mouse.y < (rect.y + rect.height)
) {
    doSomething()
}


问:
ui-grid How to disable client side filter?
I do server side filter, user type in top of a column, I generate filter string and load filtered data from server side. But I don't want the typed in filter to be in effect on client side too, it will filter out unexpectedly.

For example, a column is for voucher id, user could type in comma separated string like '12,22,33' to search for three voucher records, but the client side filter with it will hide all the three records returned.

Any suggestion?

答:
After digging around I've seen that you can configure this on older versions:

```<code>        filterOptions: {  // no more in v3.0.+
            filterText: "",
            useExternalFilter: false
        },
</code>```

Taken from: https://github.com/angular-ui/ui-grid/wiki/Configuration-Options

However, this looks like the correct grid options to use on v3.0.+:

```<code>        options = {
            // ...
            useExternalFiltering: true,
            // ...
        };
</code>```

Body:
After digging around I've seen that you can configure this on older versions:

        filterOptions: {  // no more in v3.0.+
            filterText: "",
            useExternalFilter: false
        },

Taken from: https://github.com/angular-ui/ui-grid/wiki/Configuration-Options

However, this looks like the correct grid options to use on v3.0.+:

        options = {
            // ...
            useExternalFiltering: true,
            // ...
        };


问:
Could proc get executed without using call method?
I am bringing out a separate question from here. It really confused me. Here is the definition of add_mapping method:

```<code>def add_mapping(regexp, &proc)
  @test_mappings << [regexp, proc]
end
</code>```

How could proc here get executed and return result without using call method?

答: Yep, according to the documentation, [] is a synonym for Proc#call.

Body:
I am bringing out a separate question from here. It really confused me. Here is the definition of add_mapping method:

def add_mapping(regexp, &proc)
  @test_mappings << [regexp, proc]
end

How could proc here get executed and return result without using call method?

OwnerDisplayName: George IV


问:
Paging a UIScrollView with a large PDF
I try to create a simple UIScrollView with paging. And I want to be able to scroll through a large PDF document, but this gives me some problems...

I tried the following options:

Convert all the PDF pages to UIImages at startup, this works, but is very slow on start

Manually drawing the PDF page in the drawRect, but yet again this was slow...

And I prefer not to load everything at startup but to do it during the usage.

Did anyone did this recently? Can't seem to find a nice example project.

Thnx!

Jelle

答:
ZoomingPDFViewer won't really help here. It doesn't cover paging, and doesn't cover faster loading.
This may help you a bit: http://cocoawithlove.com/2009/01/multiple-virtual-pages-in-uiscrollview.html
Draw your PDFs into a custom view. That seems to be the most efficient technique.</p>

Title: Paging a UIScrollView with a large PDF


问:
Grab and Swipe Cards
I'm creating animated cards with Slick, a JS Carrousel plugin.

I'm wondering if it's possible to add a grab and swipe interaction, as well as a pause on hover function, like the one shown here https://www.hioscar.com/individuals/network/ny

Here's what I've got so far: http://jsfiddle.net/gavinfriel/kbsemva0/1/

```<code><section class="slider">
  <!--staff-card : The first card repeats unexpectedly-->
  <div class="staff-card">1</div>
  <!-- /staff-card -->

  <!--staff-card-->
  <div class="staff-card">2</div>
  <!-- /staff-card -->

  <!--staff-card-->
  <div class="staff-card">3</div>
  <!-- /staff-card -->
</section>
</code>```

JS

```<code>$(function() {
  $('.slider').slick({
    speed: 07000,
    autoplay: true,
    autoplaySpeed: 0,
    cssEase: 'linear',
    slidesToShow: 1,
    slidesToScroll: 1,
    variableWidth: true
  });
});
</code>```

If there's a better plugin to use for this other than Slick I'm all ears.

答:
Ok, I'm not sure if this satisfies you, if not, then sorry :) Still I was trying to help ;) Well that's the best I could do :)

```<code>$(function() {
  $('.slider').slick({
    speed: 1000,
    autoplay: true,
    autoplaySpeed: 0,
    pauseOnHover: true,
    cssEase: 'linear',
    slidesToShow: 1,
    slidesToScroll: 1,
    variableWidth: true,
    draggable: true,
    swipeToSlide: true,
  });
});
</code>```

Possible solution

Regards, KJ

Title: Grab and Swipe Cards

Body:
I'm creating animated cards with Slick, a JS Carrousel plugin.

I'm wondering if it's possible to add a grab and swipe interaction, as well as a pause on hover function, like the one shown here https://www.hioscar.com/individuals/network/ny

Here's what I've got so far: http://jsfiddle.net/gavinfriel/kbsemva0/1/

1

2

3

JS

$(function() {
  $('.slider').slick({
    speed: 07000,
    autoplay: true,
    autoplaySpeed: 0,
    cssEase: 'linear',
    slidesToShow: 1,
    slidesToScroll: 1,
    variableWidth: true
  });
});

If there's a better plugin to use for this other than Slick I'm all ears.

Body:
Ok, I'm not sure if this satisfies you, if not, then sorry :) Still I was trying to help ;) Well that's the best I could do :)

$(function() {
  $('.slider').slick({
    speed: 1000,
    autoplay: true,
    autoplaySpeed: 0,
    pauseOnHover: true,
    cssEase: 'linear',
    slidesToShow: 1,
    slidesToScroll: 1,
    variableWidth: true,
    draggable: true,
    swipeToSlide: true,
  });
});

Possible solution

Regards, KJ


问:
Getting syntax error in SQL Server - why?
Could anyone help me with this please?

```<code>CREATE TABLE CARRERA
(
     NOCARRERA CHAR(3) PRIMARY KEY,
     CARRERA VARCHAR(30),
     CHECK (NOCARRERA LIKE 'C[0-9][0-9]')
)
</code>```

Incorrect syntax near the keyword 'CHECK'

答:
The syntax of CHECK in SQL Server is as follows,

```<code>CREATE TABLE table_name
(
  column1 datatype [ NULL | NOT NULL ],
  column2 datatype [ NULL | NOT NULL ],

  ...

  CONSTRAINT constraint_name
    CHECK [ NOT FOR REPLICATION ] (column_name condition)

);
</code>```

So your query will look like,

```<code>CREATE TABLE CARRERA(
   NOCARRERA CHAR(3) PRIMARY KEY,
   CARRERA VARCHAR(30),
   CONSTRAINT CHK_NOCARRERA CHECK (NOCARRERA LIKE 'C[0-9][0-9]')
)
</code>```

Body:
Could anyone help me with this please?

CREATE TABLE CARRERA
(
     NOCARRERA CHAR(3) PRIMARY KEY,
     CARRERA VARCHAR(30),
     CHECK (NOCARRERA LIKE 'C[0-9][0-9]')
)

Incorrect syntax near the keyword 'CHECK'

Body:
The syntax of CHECK in SQL Server is as follows,

CREATE TABLE table_name
(
  column1 datatype [ NULL | NOT NULL ],
  column2 datatype [ NULL | NOT NULL ],

  ...

  CONSTRAINT constraint_name
    CHECK [ NOT FOR REPLICATION ] (column_name condition)

);

So your query will look like,

CREATE TABLE CARRERA(
   NOCARRERA CHAR(3) PRIMARY KEY,
   CARRERA VARCHAR(30),
   CONSTRAINT CHK_NOCARRERA CHECK (NOCARRERA LIKE 'C[0-9][0-9]')
)


问:
Pandas: combining header rows of a multiIndex DataFrame
Lets say I have a DataFrame as follows:

```<code>first   bar       baz       foo
second  one  two  one  two  one  two three
A       1    2    3    4    5    6   7
B       8    9    10   11   12   13  14
</code>```

and I want to create a new DataFrame like this:

```<code>        barone  bartwo  bazone baztwo  fooone footwo foothree
A       1       2       3      4       5      6      7
B       8       9       10     11      12     13     14
</code>```

What would be the possible code?

答:
1. Update using Python 3.6+ use f-string formatting with list comprehension:

```<code>df.columns = [f'{i}{j}' for i, j in df.columns]
</code>```

2. Use map and join:

```<code>df.columns = df.columns.map(''.join)
</code>```

3. If your columns has numeric datatypes, use map and format:

```<code>df.columns = df.columns.map('{0[0]}{0[1]}'.format)
</code>```

Output:

```<code>   barone  bartwo  bazone  baztwo  fooone  footwo  foothree
A       1       2       3       4       5       6         7
B       8       9      10      11      12      13        14
</code>```

Body:
Lets say I have a DataFrame as follows:

first   bar       baz       foo
second  one  two  one  two  one  two three
A       1    2    3    4    5    6   7
B       8    9    10   11   12   13  14

and I want to create a new DataFrame like this:

        barone  bartwo  bazone baztwo  fooone footwo foothree
A       1       2       3      4       5      6      7
B       8       9       10     11      12     13     14

What would be the possible code?

Body:
1. Update using Python 3.6+ use f-string formatting with list comprehension:

df.columns = [f'{i}{j}' for i, j in df.columns]

2. Use map and join:

df.columns = df.columns.map(''.join)

3. If your columns has numeric datatypes, use map and format:

df.columns = df.columns.map('{0[0]}{0[1]}'.format)

Output:

   barone  bartwo  bazone  baztwo  fooone  footwo  foothree
A       1       2       3       4       5       6         7
B       8       9      10      11      12      13        14


问:
OpenNLP classifier output
At the moment I'm using the following code to train a classifier model :

```<code>    final String iterations = "1000";
    final String cutoff = "0";
    InputStreamFactory dataIn = new MarkableFileInputStreamFactory(new File("src/main/resources/trainingSets/classifierA.txt"));
    ObjectStream<String> lineStream = new PlainTextByLineStream(dataIn, "UTF-8");
    ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);

    TrainingParameters params = new TrainingParameters();
    params.put(TrainingParameters.ITERATIONS_PARAM, iterations);
    params.put(TrainingParameters.CUTOFF_PARAM, cutoff);
    params.put(AbstractTrainer.ALGORITHM_PARAM, NaiveBayesTrainer.NAIVE_BAYES_VALUE);

    DoccatModel model = DocumentCategorizerME.train("NL", sampleStream, params, new DoccatFactory());

    OutputStream modelOut = new BufferedOutputStream(new FileOutputStream("src/main/resources/models/model.bin"));
    model.serialize(modelOut);

    return model;
</code>```

This goes well and after every run I get the following output :

```<code>    Indexing events with TwoPass using cutoff of 0

    Computing event counts...  done. 1474 events
    Indexing...  done.
Collecting events... Done indexing in 0,03 s.
Incorporating indexed data for training...
done.
    Number of Event Tokens: 1474
        Number of Outcomes: 2
      Number of Predicates: 4149
Computing model parameters...
Stats: (998/1474) 0.6770691994572592
...done.
</code>```

Could someone explain what this output means? And if it tells something about the accuracy?

答:
Looking at the source, we can tell this output is done by NaiveBayesTrainer::trainModel method:

```<code>public AbstractModel trainModel(DataIndexer di) {
    // ...
    display("done.\n");
    display("\tNumber of Event Tokens: " + numUniqueEvents + "\n");
    display("\t    Number of Outcomes: " + numOutcomes + "\n");
    display("\t  Number of Predicates: " + numPreds + "\n");
    display("Computing model parameters...\n");
    MutableContext[] finalParameters = findParameters();
    display("...done.\n");
    // ...
}
</code>```

If you take a look at findParameters() code, you'll notice that it calls the trainingStats() method, which contains the code snippet that calculates the accuracy:

```<code>private double trainingStats(EvalParameters evalParams) {
    // ...
    double trainingAccuracy = (double) numCorrect / numEvents;
    display("Stats: (" + numCorrect + "/" + numEvents + ") " + trainingAccuracy + "\n");
    return trainingAccuracy;
}
</code>```

TL;DR the Stats: (998/1474) 0.6770691994572592 part of the output is the accuracy you're looking for.

Title: OpenNLP classifier output

Body:
At the moment I'm using the following code to train a classifier model :

    final String iterations = "1000";
    final String cutoff = "0";
    InputStreamFactory dataIn = new MarkableFileInputStreamFactory(new File("src/main/resources/trainingSets/classifierA.txt"));
    ObjectStream<String> lineStream = new PlainTextByLineStream(dataIn, "UTF-8");
    ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);

    TrainingParameters params = new TrainingParameters();
    params.put(TrainingParameters.ITERATIONS_PARAM, iterations);
    params.put(TrainingParameters.CUTOFF_PARAM, cutoff);
    params.put(AbstractTrainer.ALGORITHM_PARAM, NaiveBayesTrainer.NAIVE_BAYES_VALUE);

    DoccatModel model = DocumentCategorizerME.train("NL", sampleStream, params, new DoccatFactory());

    OutputStream modelOut = new BufferedOutputStream(new FileOutputStream("src/main/resources/models/model.bin"));
    model.serialize(modelOut);

    return model;

This goes well and after every run I get the following output :

    Indexing events with TwoPass using cutoff of 0

    Computing event counts...  done. 1474 events
    Indexing...  done.
Collecting events... Done indexing in 0,03 s.
Incorporating indexed data for training...
done.
    Number of Event Tokens: 1474
        Number of Outcomes: 2
      Number of Predicates: 4149
Computing model parameters...
Stats: (998/1474) 0.6770691994572592
...done.

Could someone explain what this output means? And if it tells something about the accuracy?

Body:
Looking at the source, we can tell this output is done by NaiveBayesTrainer::trainModel method:

public AbstractModel trainModel(DataIndexer di) {
    // ...
    display("done.\n");
    display("\tNumber of Event Tokens: " + numUniqueEvents + "\n");
    display("\t    Number of Outcomes: " + numOutcomes + "\n");
    display("\t  Number of Predicates: " + numPreds + "\n");
    display("Computing model parameters...\n");
    MutableContext[] finalParameters = findParameters();
    display("...done.\n");
    // ...
}

If you take a look at findParameters() code, you'll notice that it calls the trainingStats() method, which contains the code snippet that calculates the accuracy:

private double trainingStats(EvalParameters evalParams) {
    // ...
    double trainingAccuracy = (double) numCorrect / numEvents;
    display("Stats: (" + numCorrect + "/" + numEvents + ") " + trainingAccuracy + "\n");
    return trainingAccuracy;
}

TL;DR the Stats: (998/1474) 0.6770691994572592 part of the output is the accuracy you're looking for.


问:
Need help finding an error in my C project
The project is to write a program that reads three integers and then prints them in order read and reversed. use four functions: main, one to read the data, one to print them in the order read, and one to print them reversed
I get the errors:

In fuction 'main':

[Error] expected declaration or statement at end of input

recipe for target 'main.o' failed

```<code>#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char *argv[]) {

int getData ( );
void printForward (int first, int second, int third);
void printReversed (int first, int second, int third);

int main (void)
{

int a;
int b;
int c;

a=getData();
b=getData();
c=getData();
printForward ( a, b, c);
printReversed ( a, b, c);

int getData();
{

int num;
printf ("Enter an integer: ");
scanf ("%d", &num);
return num;
}

void printForward (int a, int b, int c);

{
printf ("\nNumbers in order: %d, %d, and %d\n", a, b, c);
return;
}

void printReversed (int a, int b, int c);
{
printf ("\nNumbers reversed: %d, %d, and %d\n",
c, b, a);
return;
}
return 0;
}
</code>```

答:
Seems like you are missing a simple } closing your main function.
This would be more simple to observe if, and I cannot stress this enough, you used indentations in your code. This is something you should really think about doing more, it will help you, and others, with the readability of your code.

```<code>int main (void)
{

    int a;
    int b;
    int c;

    a=getData();
    b=getData();
    c=getData();
    printForward ( a, b, c);
    printReversed ( a, b, c);
} // THIS RIGHT HERE

int getData();
{
   // rest is the same
</code>```

Body:
The project is to write a program that reads three integers and then prints them in order read and reversed. use four functions: main, one to read the data, one to print them in the order read, and one to print them reversed
I get the errors:

In fuction 'main':

[Error] expected declaration or statement at end of input

recipe for target 'main.o' failed

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch,
system("pause") or input loop */

int main(int argc, char *argv[]) {

int getData ( );
void printForward (int first, int second, int third);
void printReversed (int first, int second, int third);

int main (void)
{

int a;
int b;
int c;

a=getData();
b=getData();
c=getData();
printForward ( a, b, c);
printReversed ( a, b, c);

int getData();
{

int num;
printf ("Enter an integer: ");
scanf ("%d", &num);
return num;
}

void printForward (int a, int b, int c);

{
printf ("\nNumbers in order: %d, %d, and %d\n", a, b, c);
return;
}

void printReversed (int a, int b, int c);
{
printf ("\nNumbers reversed: %d, %d, and %d\n",
c, b, a);
return;
}
return 0;
}

Body:
Seems like you are missing a simple } closing your main function.
This would be more simple to observe if, and I cannot stress this enough, you used indentations in your code. This is something you should really think about doing more, it will help you, and others, with the readability of your code.

int main (void)
{

    int a;
    int b;
    int c;

    a=getData();
    b=getData();
    c=getData();
    printForward ( a, b, c);
    printReversed ( a, b, c);
} // THIS RIGHT HERE

int getData();
{
   // rest is the same


问:
Wooccomerce Variable product issue
I am facing some issue woocommerce variable product. I have to describe in screenshot Please check attachment image

problem is "every time i click on the drop-down instead of selecting pack size i click anywhere outside of the drop-down getting Undefine word appearing

Website URL is:http://www.worldmatrix.co.in/empire/product/ram-bandhu-chilli-powder/

PLEASE HELP ME HOW CAN I SOLVE THE ISSUE

答:
On line 529 in the source code: this code where you want to write out availability, but only if it’s not empty:

if( '' != $('input.variation_id').val() ){

Do this instead:

if('' !== $('input.variation_id').val() || 0 !== $('input.variation_id').val()) {

Because the value is 0 when it’s nothing, not an empty string.

Title: Wooccomerce Variable product issue


问:
Use Results of CTE to Update Another Table
I have the following CTE that does what I want it to do.

```<code>;WITH numbering AS
(
    SELECT SrcID, AsOfDate, PID,
           dense_rank() OVER (PARTITION BY SrcID ORDER BY PID) AS rowno
    FROM   RAW_DATA
)
SELECT SrcID,
       MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
       MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
       MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
       MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
FROM   numbering
GROUP BY SrcID
</code>```

I need to use that, as well as the AsOfDate and PID, but I don’t want to display these in the CTE, as that throws off populating PID1, PID2, PID3, and PID4 . . . all of which is correct now.  I do need the SrcID and AsOfDate to do an update to another table, named ‘RAW_DATA’.  How can I run the CTE to generate the specific data set that I need, and then do an update to the RAW_DATA table, based on joins between SrcID and AsOfDate?

I think it should be something like this:

```<code>    ;WITH numbering AS
    (
        SELECT SrcID, AsOfDate, PID,
               dense_rank() OVER (PARTITION BY SrcID ORDER BY PID) AS rowno
        FROM   RAW_DATA
    )
    SELECT SrcID,
           MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
           MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
           MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
           MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
    FROM   numbering
    GROUP BY SrcID

INSERT INTO RAW_DATA(SrcID, AsOfDate, PID, PID1, PID2, PID3, PID4)
Select *
FROM         RAW_DATA INNER JOIN numbering
             ON RAW_DATA.SrcID = numbering.SrcID
             AND RAW_DATA.AsofDate = numbering.AsofDate
</code>```

However, that throws this error: Invalid object name 'numbering'.  I am on SQL Server 2008.

Update

Modifying my original post just a bit here.

Jeffrey, I'm testing your solution:

```<code>--drop table Count_Unique_PID
;WITH numbering AS
    (
        SELECT SrcID, AsOfDate, PID,PID1,PID2,PID3,PID4,
               dense_rank() OVER (PARTITION BY AsOfDate, SrcID ORDER BY PID) AS rowno
        FROM   RAW_DATA
    )

    SELECT SrcID,AsOfDate, PID,
           MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
           MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
           MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
           MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
    INTO Count_Unique_PID
    FROM   numbering
    GROUP BY SrcID,AsOfDate, PID

    SELECT SrcID,
           AsOfDate,
           PID,
           PID1,
           PID2,
           PID3,
           PID4
    FROM   Count_Unique_PID
    GROUP BY SrcID,AsOfDate, PID,PID1,PID2,PID3,PID4

UPDATE    RAW_DATA
SET              PID1 = B.PID1,
                 PID2 = B.PID2,
                 PID3 = B.PID3,
                 PID4 = B.PID4
FROM         RAW_DATA AS A INNER JOIN Count_Unique_PID  As B
             ON A.SrcID = B.SrcID
             AND A.AsofDate = B.AsofDate
</code>```

This runs, but it blows up my rows from 357,518 to 724,150.  The number of records should stay the same; it should remain 357,518 after the Update is done...something is still not quite right here.  Maybe I am missing a Group By somewhere, or something like that.  I don't see what the actual problem is.  Any additional thoughts on this?

答:
Your SELECT statement is doing nothing for the insert (maybe it's for validation). Simply remove the select statement and your insert should work.

```<code>;WITH numbering AS
(
    SELECT SrcID, AsOfDate, PID,
           dense_rank() OVER (PARTITION BY SrcID ORDER BY PID) AS rowno
    FROM   RAW_DATA
)

INSERT INTO RAW_DATA(SrcID, AsOfDate, PID, PID1, PID2, PID3, PID4)
Select *
FROM
         RAW_DATA INNER JOIN numbering
         ON RAW_DATA.SrcID = numbering.SrcID
         AND RAW_DATA.AsofDate = numbering.AsofDate
</code>```

If you need to run a select on the CTE as well, you should use a temp table to it will exist as long as the query is running.

Body:
I have the following CTE that does what I want it to do.

;WITH numbering AS
(
    SELECT SrcID, AsOfDate, PID,
           dense_rank() OVER (PARTITION BY SrcID ORDER BY PID) AS rowno
    FROM   RAW_DATA
)
SELECT SrcID,
       MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
       MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
       MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
       MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
FROM   numbering
GROUP BY SrcID

I need to use that, as well as the AsOfDate and PID, but I don’t want to display these in the CTE, as that throws off populating PID1, PID2, PID3, and PID4 . . . all of which is correct now.  I do need the SrcID and AsOfDate to do an update to another table, named ‘RAW_DATA’.  How can I run the CTE to generate the specific data set that I need, and then do an update to the RAW_DATA table, based on joins between SrcID and AsOfDate?

I think it should be something like this:

    ;WITH numbering AS
    (
        SELECT SrcID, AsOfDate, PID,
               dense_rank() OVER (PARTITION BY SrcID ORDER BY PID) AS rowno
        FROM   RAW_DATA
    )
    SELECT SrcID,
           MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
           MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
           MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
           MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
    FROM   numbering
    GROUP BY SrcID

INSERT INTO RAW_DATA(SrcID, AsOfDate, PID, PID1, PID2, PID3, PID4)
Select *
FROM         RAW_DATA INNER JOIN numbering
             ON RAW_DATA.SrcID = numbering.SrcID
             AND RAW_DATA.AsofDate = numbering.AsofDate

However, that throws this error: Invalid object name 'numbering'.  I am on SQL Server 2008.

Update

Modifying my original post just a bit here.

Jeffrey, I'm testing your solution:

--drop table Count_Unique_PID
;WITH numbering AS
    (
        SELECT SrcID, AsOfDate, PID,PID1,PID2,PID3,PID4,
               dense_rank() OVER (PARTITION BY AsOfDate, SrcID ORDER BY PID) AS rowno
        FROM   RAW_DATA
    )

    SELECT SrcID,AsOfDate, PID,
           MAX(CASE rowno WHEN 1 THEN PID END) AS PID1,
           MAX(CASE rowno WHEN 2 THEN PID END) AS PID2,
           MAX(CASE rowno WHEN 3 THEN PID END) AS PID3,
           MAX(CASE rowno WHEN 4 THEN PID END) AS PID4
    INTO Count_Unique_PID
    FROM   numbering
    GROUP BY SrcID,AsOfDate, PID

    SELECT SrcID,
           AsOfDate,
           PID,
           PID1,
           PID2,
           PID3,
           PID4
    FROM   Count_Unique_PID
    GROUP BY SrcID,AsOfDate, PID,PID1,PID2,PID3,PID4

UPDATE    RAW_DATA
SET              PID1 = B.PID1,
                 PID2 = B.PID2,
                 PID3 = B.PID3,
                 PID4 = B.PID4
FROM         RAW_DATA AS A INNER JOIN Count_Unique_PID  As B
             ON A.SrcID = B.SrcID
             AND A.AsofDate = B.AsofDate

This runs, but it blows up my rows from 357,518 to 724,150.  The number of records should stay the same; it should remain 357,518 after the Update is done...something is still not quite right here.  Maybe I am missing a Group By somewhere, or something like that.  I don't see what the actual problem is.  Any additional thoughts on this?

Body:
Your SELECT statement is doing nothing for the insert (maybe it's for validation). Simply remove the select statement and your insert should work.

;WITH numbering AS
(
    SELECT SrcID, AsOfDate, PID,
           dense_rank() OVER (PARTITION BY SrcID ORDER BY PID) AS rowno
    FROM   RAW_DATA
)

INSERT INTO RAW_DATA(SrcID, AsOfDate, PID, PID1, PID2, PID3, PID4)
Select *
FROM
         RAW_DATA INNER JOIN numbering
         ON RAW_DATA.SrcID = numbering.SrcID
         AND RAW_DATA.AsofDate = numbering.AsofDate

If you need to run a select on the CTE as well, you should use a temp table to it will exist as long as the query is running.


问:
Is MEF Production ready?
I have to create a pluggable web app at work and I was looking at MEF which is supposed to give all the infrastructure needed for plugin model application, however I see it's still in preview, but I was wondering if anyone has used it on a production application?</p>

答: MEF V1 shipped.</p>

Title: Is MEF Production ready?

Body: MEF V1 shipped.


问:
Attachment in PHP showing 0KB
I am trying to send files as attachment through php mail function. My code is sending the files but it is showing size 0KB. I already google it but didn't found a solution. Please help me.

HTML:

```<code><form method="post" action="code.php"  enctype="multipart/form-data">
    <input type="file" name="file[]" multiple="multiple" />
    <button type="submit">Submit</button>
</form>
</code>```

PHP:

```<code><?php

    foreach ($_FILES['file']['name'] as $filename){
        $files[] = $filename; // create array of terms
    }

    // email fields: to, from, subject, and so on
    $to = "receiver_email_here";
    $from = "sender_email_here";
    $subject ="My subject";
    $message = "My message";
    $headers = "From: $from";

    // boundary
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

    // headers for attachment
    $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

    // multipart boundary
    $message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
    $message .= "--{$mime_boundary}\n";

    // preparing attachments
    for($x=0;$x<count($files);$x++){
        $file = fopen($files[$x],"rb");
        $data = fread($file,filesize($files[$x]));
        fclose($file);
        $data = chunk_split(base64_encode($data));
        $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
        "Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
        "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
        $message .= "--{$mime_boundary}\n";
    }

    mail($to, $subject, $message, $headers);

?>
</code>```

I think I am doing something wrong in this part but I am not sure.

```<code>for($x=0;$x<count($files);$x++){
    $file = fopen($files[$x],"rb");
    $data = fread($file,filesize($files[$x]));
    fclose($file);
    $data = chunk_split(base64_encode($data));
    $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
    "Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
    "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
    $message .= "--{$mime_boundary}\n";
}
</code>```

Thanks

答:
You are trying to open $_FILES['file']['name'], but the name field contains the name of the original file, not the path to the file on the server. To access the file on the server, use

```<code>$_FILES['file']['tmp_name']
</code>```

Also to make sure that the file was uploaded correctly, use

```<code>$_FILES['file']['error'] == UPLOAD_ERR_OK
</code>```

Title: Attachment in PHP showing 0KB

Body:
I am trying to send files as attachment through php mail function. My code is sending the files but it is showing size 0KB. I already google it but didn't found a solution. Please help me.

HTML:

<form method="post" action="code.php"  enctype="multipart/form-data">
    <input type="file" name="file[]" multiple="multiple" />
    <button type="submit">Submit</button>
</form>

PHP:

<?php

    foreach ($_FILES['file']['name'] as $filename){
        $files[] = $filename; // create array of terms
    }

    // email fields: to, from, subject, and so on
    $to = "receiver_email_here";
    $from = "sender_email_here";
    $subject ="My subject";
    $message = "My message";
    $headers = "From: $from";

    // boundary
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

    // headers for attachment
    $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

    // multipart boundary
    $message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
    $message .= "--{$mime_boundary}\n";

    // preparing attachments
    for($x=0;$x<count($files);$x++){
        $file = fopen($files[$x],"rb");
        $data = fread($file,filesize($files[$x]));
        fclose($file);
        $data = chunk_split(base64_encode($data));
        $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
        "Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
        "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
        $message .= "--{$mime_boundary}\n";
    }

    mail($to, $subject, $message, $headers);

?>

I think I am doing something wrong in this part but I am not sure.

for($x=0;$x<count($files);$x++){
    $file = fopen($files[$x],"rb");
    $data = fread($file,filesize($files[$x]));
    fclose($file);
    $data = chunk_split(base64_encode($data));
    $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
    "Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
    "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
    $message .= "--{$mime_boundary}\n";
}

Thanks

Body:
You are trying to open $_FILES['file']['name'], but the name field contains the name of the original file, not the path to the file on the server. To access the file on the server, use

$_FILES['file']['tmp_name']

Also to make sure that the file was uploaded correctly, use

$_FILES['file']['error'] == UPLOAD_ERR_OK


问:
How I can space the number with PHP command?
I want to code the PHP for spacing the number, example:

$number = "55375911";

So this number should to space to 2-digit and 6-digit, it shows so: "55 3759 11". How I can code this?

Thank you for helping.

答:
I am assuming that the OP wants code for equally spaced numbers for a given number string and the specified digits. The number is give is $number in the code below and $digit is the number of digits each group should have. </p>

```<code>$number = "455375911";
$length = strlen($number);
$digit = 3;
$curlen = $length;
$cur = "";
echo $number . "<br />";
$last = $length%$digit;
echo "curlen $curlen<br />last " . $last . "<br />";

while($curlen >= $digit){
   $curlen = $curlen - $digit;
   $cur = substr($number, $curlen, $digit) . (empty($cur)?"":" ") . $cur;

   echo "curlen " . $curlen . "<br />";
}
if ($last){
   $cur = substr($number, 0, $last) . (empty($cur)?"":" ") . $cur;
}
else if ($curlen){
  $cur = substr($number, 0, $digit) . (empty($cur)?"":" ") . $cur;
}
echo $cur;
</code>```

Body:
I am assuming that the OP wants code for equally spaced numbers for a given number string and the specified digits. The number is give is $number in the code below and $digit is the number of digits each group should have.

$number = "455375911";
$length = strlen($number);
$digit = 3;
$curlen = $length;
$cur = "";
echo $number . "<br />";
$last = $length%$digit;
echo "curlen $curlen<br />last " . $last . "<br />";

while($curlen >= $digit){
   $curlen = $curlen - $digit;
   $cur = substr($number, $curlen, $digit) . (empty($cur)?"":" ") . $cur;

   echo "curlen " . $curlen . "<br />";
}
if ($last){
   $cur = substr($number, 0, $last) . (empty($cur)?"":" ") . $cur;
}
else if ($curlen){
  $cur = substr($number, 0, $digit) . (empty($cur)?"":" ") . $cur;
}
echo $cur;


问:
How can I show unused imports/locals in green (warning) in vscode, rather than red (error)?
When I'm writing TypeScript code in vscode, unused imports are shown as an error, with a red squiggly underline:

The same is true of unused local variables. I'm happy to have these marked as errors when I run tsc as part of my continuous integration tests, but I'd rather have them rendered as green warnings in vscode. It's more likely that I just haven't used the import/local yet, and the red error makes me think there's a more serious problem, e.g. that I'm importing a symbol that doesn't exist.

Back when unused imports/locals were implemented by tslint, this worked great. But now that they're part of the compiler, it's harder to distinguish them.

Is it possible to make just these two compiler errors get rendered as warnings?

My tsconfig.json includes:

```<code>{
  "compilerOptions": {
    "noUnusedLocals": true
  }
}
</code>```

答:
TL;DR: Upgrade to 1.19.0+ (currently only available as insiders build version) and it does report these errors as warning by default.

You are lucky! Recently they merged a pull reqests (https://github.com/Microsoft/vscode/pull/37616) which allows users to change the style of reported tsc errors. It is available for VSCode 1.19.0+. As of now it is only available in the VSCode insiders build (which is basically the beta version of the upcoming VSCode).

The setting is called typescript.reportStyleChecksAsWarnings. If the setting is set to true, then all errors of the below types will be reported as warning:

```<code>--noUnusedLocals
--noUnusedParameters
--noImplicitReturns
--noFallthroughCasesInSwitch
--allowUnusedLabels
--allowUnreachableCode
</code>```

In order to enable this setting go to File -> Preferences -> Settings and filter for typescript.reportStyleChecksAsWarnings. Here you can change this setting to true (which is the default in the current insiders build).

Body:
When I'm writing TypeScript code in vscode, unused imports are shown as an error, with a red squiggly underline:

The same is true of unused local variables. I'm happy to have these marked as errors when I run tsc as part of my continuous integration tests, but I'd rather have them rendered as green warnings in vscode. It's more likely that I just haven't used the import/local yet, and the red error makes me think there's a more serious problem, e.g. that I'm importing a symbol that doesn't exist.

Back when unused imports/locals were implemented by tslint, this worked great. But now that they're part of the compiler, it's harder to distinguish them.

Is it possible to make just these two compiler errors get rendered as warnings?

My tsconfig.json includes:

{
  "compilerOptions": {
    "noUnusedLocals": true
  }
}

Body:
TL;DR: Upgrade to 1.19.0+ (currently only available as insiders build version) and it does report these errors as warning by default.

You are lucky! Recently they merged a pull reqests (https://github.com/Microsoft/vscode/pull/37616) which allows users to change the style of reported tsc errors. It is available for VSCode 1.19.0+. As of now it is only available in the VSCode insiders build (which is basically the beta version of the upcoming VSCode).

The setting is called typescript.reportStyleChecksAsWarnings. If the setting is set to true, then all errors of the below types will be reported as warning:

--noUnusedLocals
--noUnusedParameters
--noImplicitReturns
--noFallthroughCasesInSwitch
--allowUnusedLabels
--allowUnreachableCode

In order to enable this setting go to File -> Preferences -> Settings and filter for typescript.reportStyleChecksAsWarnings. Here you can change this setting to true (which is the default in the current insiders build).


问:
Check if array is an ordered subset
I want to find out if an array is an ordered subset of another array:

[1,2] is an ordered subset of [1,2,3]

[1,3] is an ordered subset of [1,2,3]

[2,1] is not an ordered subset of [1,2,3]

I've found some solutions to this, but every solution ignores the order. Every method I've seen so far ignores the order of the arrays:

```<code>[1,2,3] - [2,1] #=> [3]
[1,2,3] & [2,1] #=> [1,2]
[1,2,3].to_set.superset?([2,1].to_set) #=> true
</code>```

Update:
Based on the discussion below, I've updated my question.

答:
```<code>b == a & b
</code>```

That checks whether b is contained in a in the same order.

In other words: In general you have B⊆A ⇔ B=A∩B. And Ruby's Array#& preserves the order (of the left operand).

Title: Check if array is an ordered subset

Body:
I want to find out if an array is an ordered subset of another array:

[1,2] is an ordered subset of [1,2,3]

[1,3] is an ordered subset of [1,2,3]

[2,1] is not an ordered subset of [1,2,3]

I've found some solutions to this, but every solution ignores the order. Every method I've seen so far ignores the order of the arrays:

[1,2,3] - [2,1] #=> [3]
[1,2,3] & [2,1] #=> [1,2]
[1,2,3].to_set.superset?([2,1].to_set) #=> true

Update:
Based on the discussion below, I've updated my question.

Body:
b == a & b

That checks whether b is contained in a in the same order.

In other words: In general you have B⊆A ⇔ B=A∩B. And Ruby's Array#& preserves the order (of the left operand).


问:
How to set base image for DockerPlugin of sbt native packager?
I want to dockerify a scala application.

I use the sbt-native-packager, and when building the image locally via

```<code>sbt docker:publishLocal
</code>```

I was surprised to realize that it would use:

```<code>openjdk:latest
</code>```

as its base image.

I like to point my docker image against certain version, and I know that my application currently require Java 8 and will crash on Java 9; and the latest tag might point to a new major version in the future.

I am a bit confused on how the Docker plugin works through sbt-native-packager. Why is it using openjdk:latest as its base? How can I set it to something different, e.g.: openjdk/8-jdk?

答:
You can set the baseImage and its tag in your build.sbt through:

```<code>dockerBaseImage := "openjdk:8-jdk"
</code>```

You can read about this in the docker documentation of the sbt native packager.

Body:
I want to dockerify a scala application.

I use the sbt-native-packager, and when building the image locally via

sbt docker:publishLocal

I was surprised to realize that it would use:

openjdk:latest

as its base image.

I like to point my docker image against certain version, and I know that my application currently require Java 8 and will crash on Java 9; and the latest tag might point to a new major version in the future.

I am a bit confused on how the Docker plugin works through sbt-native-packager. Why is it using openjdk:latest as its base? How can I set it to something different, e.g.: openjdk/8-jdk?

Body:
You can set the baseImage and its tag in your build.sbt through:

dockerBaseImage := "openjdk:8-jdk"

You can read about this in the docker documentation of the sbt native packager.


问:
Repeat scroll function while mouse hovering over element
is there a way how to repeat a function as long as the cursor is hovering over a specific dom element? I want to perform a scroll operation as long as long as the user is hovering over an arrow with an optional timeout. This task should be fullfillled without using jquery!

Here is my current code:

```<code>public overDown() {
    this.tabList.nativeElement.scrollBy(0, 10);
    const element = this.tabList.nativeElement;
    if(element.offsetHeight + element.scrollTop >= element.scrollHeight) {
      console.log('Bottom Limit');
    }
  }

  public overUp() {
    this.tabList.nativeElement.scrollBy(0, -10);
    const element = this.tabList.nativeElement;
    if(element.scrollTop === 0) {
      console.log('Top Limit');
    }
  }
</code>```

And the HTML

```<code><div class="list-arrow-up" (mouseover)="overUp()">▲</div>
  <ul #tabList>
    <li><!--several List items --></span></li>
  </ul>
  <div class="list-arrow-down" (mouseover)="overDown()">▼</div>
</code>```

答:
I hope this will help you. Change moveDown and moveUp function based on your requirement. This is javascript code, change this code to angular TypeScript.

HTML

```<code><a onmouseover="overDown()" onmouseleave="stopMoveDown = true">Down</a>
<a onmouseover="overUp()" onmouseleave="stopMoveUp = true">Up</a>
</code>```

JavaScript

```<code>  var stopMoveDown = false;
  var stopMoveUp = false;

  function moveDown() {
     console.log('Move Down');
     if(!stopMoveDown)
        setTimeout(moveDown, 100);
  }

  function moveUp() {
     console.log('Move Up');
     if(!stopMoveUp)
        setTimeout(moveUp, 100);
  }

  function overDown(){
    stopMoveDown = false;
    moveDown();
  }

  function overUp(){
    stopMoveUp = false;
    moveUp();
  }
</code>```

Click here to view demo, open console window and you can see the move up/down in the console window when mouse over Down/Up links.
https://liveweave.com/bFG3OP

Body:
is there a way how to repeat a function as long as the cursor is hovering over a specific dom element? I want to perform a scroll operation as long as long as the user is hovering over an arrow with an optional timeout. This task should be fullfillled without using jquery!

Here is my current code:

public overDown() {
    this.tabList.nativeElement.scrollBy(0, 10);
    const element = this.tabList.nativeElement;
    if(element.offsetHeight + element.scrollTop >= element.scrollHeight) {
      console.log('Bottom Limit');
    }
  }

  public overUp() {
    this.tabList.nativeElement.scrollBy(0, -10);
    const element = this.tabList.nativeElement;
    if(element.scrollTop === 0) {
      console.log('Top Limit');
    }
  }

And the HTML

▲

▼

Body:
I hope this will help you. Change moveDown and moveUp function based on your requirement. This is javascript code, change this code to angular TypeScript.

HTML

<a onmouseover="overDown()" onmouseleave="stopMoveDown = true">Down</a>
<a onmouseover="overUp()" onmouseleave="stopMoveUp = true">Up</a>

JavaScript

  var stopMoveDown = false;
  var stopMoveUp = false;

  function moveDown() {
     console.log('Move Down');
     if(!stopMoveDown)
        setTimeout(moveDown, 100);
  }

  function moveUp() {
     console.log('Move Up');
     if(!stopMoveUp)
        setTimeout(moveUp, 100);
  }

  function overDown(){
    stopMoveDown = false;
    moveDown();
  }

  function overUp(){
    stopMoveUp = false;
    moveUp();
  }

Click here to view demo, open console window and you can see the move up/down in the console window when mouse over Down/Up links.
https://liveweave.com/bFG3OP


问:
XMPP - What is different between muc (mod_muc) and mucLight (mod_muc_light)?
I have successfully implemented mucLight in my app with mongooseIM server.but I'm aware about muc protocol on ejabberd server.

Which client extension support muc/mucLight protocol ?

Is there a way to have a shared history for a group using muc/mucLight protocol ?

Which is improved for mobile devices ?

any others pros and cons ?

答:
Which client extension support muc/mucLight protocol ?

MUC is supported by almost every client library, MUC Light is supported by Smack and XMPPFramework. Also, MUC Light may be configured to use MUC protocol (with some MUC Light-exclusive features unavailable).

Is there a way to have a shared history for a group using muc/mucLight protocol ?

In MongooseIM both MUC and MUC Light use the same extension and table for archiving so theoretically their archives should be compatible but it is not a requirement so is not tested automatically in the project.

Which is improved for mobile devices ?

MUC Light exchanges data much less frequently than MUC and the packets attempt to carry information as efficiently as possible to reduce round-trips and unnecessary traffic.

any others pros and cons ?

http://mongooseim.readthedocs.io/en/latest/open-extensions/muc_light/#2-requirements

Here are the high-level principles behind MUC Light, that more or less directly indicate differences.


问:
How to add a Send feedback option on an app crashing?
How can I add a Send feedback option on an Android app crashing? This option is seen in Google's own apps and here is an example from Starbucks.

There are a number of very old answers to this question that involve programmatically creating something like this. They seem overly involved to make this show.

I'm surprised there isn't a simple way to implement this without putting a try catch around the entire app. Can this be enabled simply e.g. by enabling an option on the Google Play store console or by by adding something to the manifest?

I have not been able to find data on how to do this in the Android or Play Store documentation.

Update: We are using Crashlytics/Fabric as our crash reporting library

This image shows the default behaviour on Android 6.0.

And 8.0:

答:
I'm surprised there isn't a simple way to implement this without putting a try catch around the entire app

There is no means to put "a try catch around the entire app".

There are a wide range of crash reporting libraries for Android, some of which (e.g., ACRA) will support your sort of feedback option. Implementing a crash reporter is somewhat tricky, given that your app's process is in an unstable state when you crash, which is why we have tested and debugged libraries for this purpose.

Can this be enabled simply e.g. by enabling an option on the Google Play store console or by by adding something to the manifest?

The libraries will add something to the manifest as part of adding them to your app.


问:
In PHP's Laravel, how do I clear laravel.log?
I'm new to Laravel and PHP in general, and I'm trying to clear my errorLog. The current errorlog that I'm using is Laravel's laravel.log file that is in /app/storage/logs.

Is there an easy way to clear the laravel.log file? Is it safe to delete it and it'll rebuild when needed?

I'm using the latest version of Ubuntu. Thanks!

答:
This worked for me :</p>

```<code>echo "" > storage/logs/laravel.log
</code>```

Body:
This worked for me :

echo "" > storage/logs/laravel.log