问:
scala returns doesn't conform to required S_
I got the error

```<code>found   : scala.concurrent.Future[Option[models.ProcessTemplatesModel]]
required: Option[models.ProcessTemplatesModel]
</code>```

My function is below

```<code>def createCopyOfProcessTemplate(processTemplateId: Int): Future[Option[ProcessTemplatesModel]] = {
    val action = processTemplates.filter(_.id === processTemplateId).result.map(_.headOption)
    val result: Future[Option[ProcessTemplatesModel]] = db.run(action)

    result.map { case (result) =>
      result match {
        case Some(r) => {
          var copy = (processTemplates returning processTemplates.map(_.id)) += ProcessTemplatesModel(None, "[Copy of] " + r.title, r.version, r.createdat, r.updatedat, r.deadline, r.status, r.comment, Some(false), r.checkedat, Some(false), r.approvedat, false, r.approveprocess, r.trainingsprocess)
          val composedAction = copy.flatMap { id =>
            processTemplates.filter(_.id === id).result.headOption
          }
          db.run(composedAction)

        }
      }
    }
  }
</code>```

what is my problem in this case?

edit:

my controller function looks like this:

```<code> def createCopyOfProcessTemplate(processTemplateId: Int) = Action.async {
    processTemplateDTO.createCopyOfProcessTemplate(processTemplateId).map { process =>
      Ok(Json.toJson(process))
    }
  }
</code>```

Is there my failure?

答:
According to the your code - there are the following issues:

You use two db.run which return futures, but inner future will
not complete. For resolving it you should compose futures with
flatMap or for-comprehension.

You use only one partial-function case Some(_) => for pattern matching
and don't handle another value None.

You can use only one db.run and actions composition.

Your code can be like as:

```<code>def createCopyOfProcessTemplate(processTemplateId: Int): Future[Option[ProcessTemplatesModel]] = {
    val action = processTemplates.filter(...).result.map(_.headOption)

    val composedAction = action.flatMap {
       case Some(r) =>
           val copyAction = (processTemplates returning processTemplates...)
           copyAction.flatMap { id =>
               processTemplates.filter(_.id === id).result.headOption
           }
       case _ =>
           DBIO.successful(None) // issue #2 has been resolved here
    }

    db.run(composedAction)       // issue #3 has been resolved here
  }
</code>```

We get rid of issue #1 (because we use actions composition).

Body:
I got the error

found   : scala.concurrent.Future[Option[models.ProcessTemplatesModel]]
required: Option[models.ProcessTemplatesModel]

My function is below

def createCopyOfProcessTemplate(processTemplateId: Int): Future[Option[ProcessTemplatesModel]] = {
    val action = processTemplates.filter(_.id === processTemplateId).result.map(_.headOption)
    val result: Future[Option[ProcessTemplatesModel]] = db.run(action)

    result.map { case (result) =>
      result match {
        case Some(r) => {
          var copy = (processTemplates returning processTemplates.map(_.id)) += ProcessTemplatesModel(None, "[Copy of] " + r.title, r.version, r.createdat, r.updatedat, r.deadline, r.status, r.comment, Some(false), r.checkedat, Some(false), r.approvedat, false, r.approveprocess, r.trainingsprocess)
          val composedAction = copy.flatMap { id =>
            processTemplates.filter(_.id === id).result.headOption
          }
          db.run(composedAction)

        }
      }
    }
  }

what is my problem in this case?

edit:

my controller function looks like this:

 def createCopyOfProcessTemplate(processTemplateId: Int) = Action.async {
    processTemplateDTO.createCopyOfProcessTemplate(processTemplateId).map { process =>
      Ok(Json.toJson(process))
    }
  }

Is there my failure?

Body:
According to the your code - there are the following issues:

You use two db.run which return futures, but inner future will
not complete. For resolving it you should compose futures with
flatMap or for-comprehension.

You use only one partial-function case Some(_) => for pattern matching
and don't handle another value None.

You can use only one db.run and actions composition.

Your code can be like as:

def createCopyOfProcessTemplate(processTemplateId: Int): Future[Option[ProcessTemplatesModel]] = {
    val action = processTemplates.filter(...).result.map(_.headOption)

    val composedAction = action.flatMap {
       case Some(r) =>
           val copyAction = (processTemplates returning processTemplates...)
           copyAction.flatMap { id =>
               processTemplates.filter(_.id === id).result.headOption
           }
       case _ =>
           DBIO.successful(None) // issue #2 has been resolved here
    }

    db.run(composedAction)       // issue #3 has been resolved here
  }

We get rid of issue #1 (because we use actions composition).


来源: stackexchange

问:
python subprocess.call() modifies arguments before passing it to shell-script?
I am writing a python wrapper for calling programs of the AMOS package (specifically for merging genome assemblies from different sources using good ol' minimus2 from AMOS).

The scripts should be called like this when using the shell directly:

```<code>toAmos -s myinput.fasta -o testoutput.afg
minimus2 testoutput -D REFCOUNT=400 -D OVERLAP=500
</code>```

[just for clarification:

-toAmos:  converts my input.fasta file to .afg format and requires an input sequence argument ("-s") and an output argument ("-o")

-minimus2: merges a sequence dataset against reference contigs and requires an argument "-D REFCOUNT=x" for stating the number of rerference seqeunces in your input and an argument "-D OVERLAP=Y" for stating the minimum overlap between sequences]

So within my script I use subprocess.call() to call the necessary AMOS tools.

Basically I do this:

```<code>from subprocess import call:
output_basename = "testoutput"
inputfile = "myinput.fasta"

call(["toAmos", "-s " + inputfile, "-o " + output_basename + ".afg"])
call(["minimus2", output_basename, "-D REFCOUNT=400", "-D OVERLAP=500"])
</code>```

But in this case the AMOS tools cannot interpret the arguments anymore. The arguments seem get modified by subprocess.call() and passed incorrectly. The error message I get is:

```<code>Unknown option: s myinput.fasta
Unknown option: o testoutput.afg
You must specify an output AMOS AFG file with option -o
/home/jov14/tools/miniconda2/bin/runAmos: unrecognized option '-D REFCOUNT=400'
Command line parsing failed, use -h option for usage info
</code>```

It seems that the arguments get passed without the leading "-"? So I then tried passing the command as a single string (including arguments) like this:

```<code>call(["toAmos -s " + inputfile +" -o " + output_basename + ".afg"])
</code>```

But then I get this error...

```<code>OSError: [Errno 2] No such file or directory
</code>```

... presumably because subprocess.call is interpreting the whole string as the name for a single script.
I guess I COULD probably try shell=True as a workaround, but the internet is FULL of instructions clearly advising against this.

What seems to be the problem here?
What can I do?

答:
answer

Either do:

```<code>call("toAmos -s " + inputfile +" -o " + output_basename + ".afg") # single string
</code>```

or do:

```<code>call(["toAmos", "-s", inputfile, "-o", output_basename + ".afg"]) # list of arguments
</code>```

discussion

In the case of your:

```<code>call(["toAmos", "-s " + inputfile, "-o " + output_basename + ".afg"])
</code>```

you should supply:

either "-s" + inputfile (no space after -s), "-o" + output_basename + ".afg"

or "-s", inputfile (separate arguments), "-o", output_basename + ".afg"

In the case of your:

```<code>call(["minimus2", output_basename, "-D REFCOUNT=400", "-D OVERLAP=500"])
</code>```

the "-D REFCOUNT=400" and "-D OVERLAP=500" should be provided as two items each ('-D', 'REFCOUNT=400', '-D', 'OVERLAP=500'), or drop the spaces ('-DREFCOUNT=400', '-DOVERLAP=500').

additional info

You seem to lack knowledge of how a shell splits a command-line; I suggest you always use the single string method, unless there are spaces in filenames or you have to use the shell=False option; in that case, I suggest you always supply a list of arguments.

ContentLicense: CC BY-SA 3.0

Body:
I am writing a python wrapper for calling programs of the AMOS package (specifically for merging genome assemblies from different sources using good ol' minimus2 from AMOS).

The scripts should be called like this when using the shell directly:

toAmos -s myinput.fasta -o testoutput.afg
minimus2 testoutput -D REFCOUNT=400 -D OVERLAP=500

[just for clarification:

-toAmos:  converts my input.fasta file to .afg format and requires an input sequence argument ("-s") and an output argument ("-o")

-minimus2: merges a sequence dataset against reference contigs and requires an argument "-D REFCOUNT=x" for stating the number of rerference seqeunces in your input and an argument "-D OVERLAP=Y" for stating the minimum overlap between sequences]

So within my script I use subprocess.call() to call the necessary AMOS tools.

Basically I do this:

from subprocess import call:
output_basename = "testoutput"
inputfile = "myinput.fasta"

call(["toAmos", "-s " + inputfile, "-o " + output_basename + ".afg"])
call(["minimus2", output_basename, "-D REFCOUNT=400", "-D OVERLAP=500"])

But in this case the AMOS tools cannot interpret the arguments anymore. The arguments seem get modified by subprocess.call() and passed incorrectly. The error message I get is:

Unknown option: s myinput.fasta
Unknown option: o testoutput.afg
You must specify an output AMOS AFG file with option -o
/home/jov14/tools/miniconda2/bin/runAmos: unrecognized option '-D REFCOUNT=400'
Command line parsing failed, use -h option for usage info

It seems that the arguments get passed without the leading "-"? So I then tried passing the command as a single string (including arguments) like this:

call(["toAmos -s " + inputfile +" -o " + output_basename + ".afg"])

But then I get this error...

OSError: [Errno 2] No such file or directory

... presumably because subprocess.call is interpreting the whole string as the name for a single script.
I guess I COULD probably try shell=True as a workaround, but the internet is FULL of instructions clearly advising against this.

What seems to be the problem here?
What can I do?

Body:
answer

Either do:

call("toAmos -s " + inputfile +" -o " + output_basename + ".afg") # single string

or do:

call(["toAmos", "-s", inputfile, "-o", output_basename + ".afg"]) # list of arguments

discussion

In the case of your:

call(["toAmos", "-s " + inputfile, "-o " + output_basename + ".afg"])

you should supply:

either "-s" + inputfile (no space after -s), "-o" + output_basename + ".afg"

or "-s", inputfile (separate arguments), "-o", output_basename + ".afg"

In the case of your:

call(["minimus2", output_basename, "-D REFCOUNT=400", "-D OVERLAP=500"])

the "-D REFCOUNT=400" and "-D OVERLAP=500" should be provided as two items each ('-D', 'REFCOUNT=400', '-D', 'OVERLAP=500'), or drop the spaces ('-DREFCOUNT=400', '-DOVERLAP=500').

additional info

You seem to lack knowledge of how a shell splits a command-line; I suggest you always use the single string method, unless there are spaces in filenames or you have to use the shell=False option; in that case, I suggest you always supply a list of arguments.


问:
Textview overlapping button when opening keypad?
When I open keypad my textview overlap with button. Below "author info" is overlapping button when I open keypad. Can anyone tell me what's went wrong?

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/actionbar"
android:orientation="vertical" >

<ImageView
    android:id="@+id/imgLogo"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="60dp"
    android:src="@drawable/ic_launcher" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/imgLogo"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="15dp"
    android:text="@string/title"
    android:textColor="@color/white"
    android:textSize="13dp" />

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="20dp" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="15dp"
        android:text="@string/enter_name"
        android:textColor="@color/white"
        android:textSize="18dp" />

    <EditText
        android:id="@+id/username_input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:imeActionId="@+id/login"
        android:layout_marginBottom="10dp"
        android:imeActionLabel="@string/action_sign_in_short"
        android:imeOptions="actionUnspecified"
        android:layout_marginTop="10dp"
        android:background="@color/white"
        android:inputType="textCapWords"
        android:padding="10dp" />

    <Button
        android:id="@+id/sign_in_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:background="@color/bg_btn_join"
        android:paddingLeft="25dp"
        android:paddingRight="25dp"
        android:text="@string/btn_join"
        android:textColor="@color/white" />
</LinearLayout>

<!-- author info -->

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="20dp"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/author_name"
        android:textColor="@color/white"
        android:textSize="12dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/author_url"
        android:textColor="@color/white"
        android:textSize="12dp" />
</LinearLayout>

</RelativeLayout>
</code>```

Please help me to resolve this issue.I don't want that my textview overlap button. It should remain on it place even after I open my keypad.

答: In your activity on manifest set windowSoftInputMode="adjustPan", so the activity's main window is not resized to make room for the soft keyboard. For more check https://developer.android.com/guide/topics/manifest/activity-element.html#wsoft</p>

Body:
When I open keypad my textview overlap with button. Below "author info" is overlapping button when I open keypad. Can anyone tell me what's went wrong?

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/actionbar"
android:orientation="vertical" >

<ImageView
    android:id="@+id/imgLogo"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="60dp"
    android:src="@drawable/ic_launcher" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/imgLogo"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="15dp"
    android:text="@string/title"
    android:textColor="@color/white"
    android:textSize="13dp" />

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="20dp" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="15dp"
        android:text="@string/enter_name"
        android:textColor="@color/white"
        android:textSize="18dp" />

    <EditText
        android:id="@+id/username_input"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:imeActionId="@+id/login"
        android:layout_marginBottom="10dp"
        android:imeActionLabel="@string/action_sign_in_short"
        android:imeOptions="actionUnspecified"
        android:layout_marginTop="10dp"
        android:background="@color/white"
        android:inputType="textCapWords"
        android:padding="10dp" />

    <Button
        android:id="@+id/sign_in_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:background="@color/bg_btn_join"
        android:paddingLeft="25dp"
        android:paddingRight="25dp"
        android:text="@string/btn_join"
        android:textColor="@color/white" />
</LinearLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="20dp"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/author_name"
        android:textColor="@color/white"
        android:textSize="12dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/author_url"
        android:textColor="@color/white"
        android:textSize="12dp" />
</LinearLayout>

</RelativeLayout>

Please help me to resolve this issue.I don't want that my textview overlap button. It should remain on it place even after I open my keypad.


问:
AngularJS Redirect Hashbang to Hashban exclamationmark?
currently I'm trying to move my ui-router to #! from a simple Hashbang Prefix # however if I change my locationProvider to it:

```<code>$locationProvider.hashPrefix('!');
</code>```

It will always return a 404 if I try to access it via the old url.
So if somebody has a hyperlink to #/customer/list it will redirect to a 404 or the default page, is there a way to redirect it to #!/customer/list? (I actually have a lot of routes so it should be as automatic as possible).

答:
You can do this using $stateChangeStart as follows:

```<code>$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (/\#(?!\!)/.test(toState)) {
        e.preventDefault();
        toState.replace("#","#!");
        $state.go(toState);
    } else {
        angular.noop;
    }
});
</code>```

EDIT :

Not tried. But, hope it works:

```<code>$transitions.onStart({}, function(a) {
    var toState = a.$to().url.pattern;
    if (/\#(?!\!)/.test(toState)) {
      toState.replace("#", "#!");
      $state.go(toState)
    } else {
      angular.noop;
    }
});
</code>```

All the best.

Body:
currently I'm trying to move my ui-router to #! from a simple Hashbang Prefix # however if I change my locationProvider to it:

$locationProvider.hashPrefix('!');

It will always return a 404 if I try to access it via the old url.
So if somebody has a hyperlink to #/customer/list it will redirect to a 404 or the default page, is there a way to redirect it to #!/customer/list? (I actually have a lot of routes so it should be as automatic as possible).

Body:
You can do this using $stateChangeStart as follows:

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (/\#(?!\!)/.test(toState)) {
        e.preventDefault();
        toState.replace("#","#!");
        $state.go(toState);
    } else {
        angular.noop;
    }
});

EDIT :

Not tried. But, hope it works:

$transitions.onStart({}, function(a) {
    var toState = a.$to().url.pattern;
    if (/\#(?!\!)/.test(toState)) {
      toState.replace("#", "#!");
      $state.go(toState)
    } else {
      angular.noop;
    }
});

All the best.


问:
Destination toolbar disappeared on XCode 6.4
Today in the morning I tried to compile my project to run in my device and I found the destination toolbar disappeared and I cannot choose my IOS device or IOS Simulator device as target. (I can do it in the Product/Destination Menu)

After some research I found the >> at the right on the screen and when I pushed a Scheme option appeared but it is disabled and I can't enable again.

This is what I tried with no success:

Open an old project to see if the problem was in my project

Create a new project (with Swift and Objective C but I don't think this make any difference)

Restart my computer

Hide and show the toolbar (View menu/Hide Toolbar and the View menu/Show Toolbar)

I tried all the previous options with the device connected and disconnected

I have installed the IOS Simulator 8.4 (when I run my project it runs in the last selected simulator) and XCode 6.4.

答: On XCode 9.0 beta, this worked for me: select View -> Show Toolbar from menu


问:
Call a function in Python file using Flask
I have python file called testing_file.py:

```<code>    from datetime import datetime
    import MySQLdb

    # Open database connection
    class DB():
        def __init__(self, server, user, password, db_name):
            db = MySQLdb.connect(server, user, password, db_name )
            self.cur = db.cursor()

        def time_statistic(self, start_date, end_date):

            time_list = {}

            sql = "SELECT activity_log.datetime, activity_log.user_id FROM activity_log"
            self.cur.execute(sql)
            self.date_data = self.cur.fetchall()
            for content in self.date_data:

                timestamp = str(content[0])
                datetime_object = datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
                timestamps = datetime.strftime(datetime_object, "%Y-%m-%d")

                if start_dt <= timestamps and timestamps <= end_dt:
                    if timestamps not in time_list:
                        time_list[timestamps]=1
                    else:
                        time_list[timestamps]+=1

                    return json.dumps(time_list)

    start_date = datetime.strptime(str('2017-4-7'), '%Y-%m-%d')
    start_dt = datetime.strftime(start_date, "%Y-%m-%d")
    end_date = datetime.strptime(str('2017-5-4'), '%Y-%m-%d')
    end_dt = datetime.strftime(end_date, "%Y-%m-%d")

    db = DB("host","user_db","pass_db","db_name")
    db.time_statistic(start_date, end_date)
</code>```

I want to access the result (time_list) thru API using Flask. This is what i've wrote so far, doesn't work and also I've tried another way:

```<code>    from flask import Flask
    from testing_api import *

    app = Flask(__name__)

    @app.route("/")
    def get():
        db = DB("host","user_db","pass_db","db_name")
        d = db.time_statistic()
        return d

    if __name__ == "__main__":
        app.run(debug=True)
</code>```

Question: This is my first time work with API and Flask. Can anyone please help me thru this. Any hints are appreciated. Thank you

I've got empty list as result {}

答:
There are quite a few things that are wrong (ranging from "useless and unclear" to "plain wrong") in your code.

wrt/ the TypeError: as the error message says, your get() function expects two arguments (self and DB) which won't be passed by Flask - and are actually not used in the function anyway. Remove both arguments and you'll get rid of this error - just to find out you now have a NameError on the first line of the get() function (obviously since you didn't import time_statistic nor defined start_date and end_date).

Body:
I have python file called testing_file.py:

    from datetime import datetime
    import MySQLdb

    # Open database connection
    class DB():
        def __init__(self, server, user, password, db_name):
            db = MySQLdb.connect(server, user, password, db_name )
            self.cur = db.cursor()

        def time_statistic(self, start_date, end_date):

            time_list = {}

            sql = "SELECT activity_log.datetime, activity_log.user_id FROM activity_log"
            self.cur.execute(sql)
            self.date_data = self.cur.fetchall()
            for content in self.date_data:

                timestamp = str(content[0])
                datetime_object = datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S')
                timestamps = datetime.strftime(datetime_object, "%Y-%m-%d")

                if start_dt <= timestamps and timestamps <= end_dt:
                    if timestamps not in time_list:
                        time_list[timestamps]=1
                    else:
                        time_list[timestamps]+=1

                    return json.dumps(time_list)

    start_date = datetime.strptime(str('2017-4-7'), '%Y-%m-%d')
    start_dt = datetime.strftime(start_date, "%Y-%m-%d")
    end_date = datetime.strptime(str('2017-5-4'), '%Y-%m-%d')
    end_dt = datetime.strftime(end_date, "%Y-%m-%d")

    db = DB("host","user_db","pass_db","db_name")
    db.time_statistic(start_date, end_date)

I want to access the result (time_list) thru API using Flask. This is what i've wrote so far, doesn't work and also I've tried another way:

    from flask import Flask
    from testing_api import *

    app = Flask(__name__)

    @app.route("/")
    def get():
        db = DB("host","user_db","pass_db","db_name")
        d = db.time_statistic()
        return d

    if __name__ == "__main__":
        app.run(debug=True)

Question: This is my first time work with API and Flask. Can anyone please help me thru this. Any hints are appreciated. Thank you

I've got empty list as result {}


问:
Appending NSString with Zeros depending upon length
I have a string, length may vary but I have to check if its length is less then 12 and if yes append those many zeros to it.

Like:

str = Test123, output should be Test12300000

str = Test123456, output should be Test12345600

Only 12 Char is allowed in string.

Tried below code but not getting generic result. There must be a better and easy way to do.

```<code>- (NSString *)formatValue:(NSString *)str forDigits:(NSString *)zeros {
    return [NSString stringWithFormat:@"%@%@", str ,zeros];
}
</code>```

答:
how about something like this:</p>

```<code>- (NSString *)stringToFormat:(NSString *)str {
    while (str.length <12) {
        str = [NSString stringWithFormat:@"%@0", str];
    }

    return str;
}
</code>```

Body:
I have a string, length may vary but I have to check if its length is less then 12 and if yes append those many zeros to it.

Like:

str = Test123, output should be Test12300000

str = Test123456, output should be Test12345600

Only 12 Char is allowed in string.

Tried below code but not getting generic result. There must be a better and easy way to do.

- (NSString *)formatValue:(NSString *)str forDigits:(NSString *)zeros {
    return [NSString stringWithFormat:@"%@%@", str ,zeros];
}

Body:
how about something like this:

- (NSString *)stringToFormat:(NSString *)str {
    while (str.length <12) {
        str = [NSString stringWithFormat:@"%@0", str];
    }

    return str;
}


问:
Comparator<File> for "directories-first" order
I'm stumped... Let's say I have this directory tree:

```<code>{someRoot}/
{someRoot}/bar/
{someRoot}/bar/file1.txt
{someRoot}/foo/
{someRoot}/foo/baz/
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/file2.txt
{someRoot}/aardvark.txt
{someRoot}/food.txt
{someRoot}/zebra.txt
</code>```

You'll note the ordering. Call this order1. At each stage, the directories come first before the files. (NOTE:  bar/file1.txt comes before foo, so on a global basis, the directories do not all come before all the files.)

If I enumerate this directory tree, and then recursively enumerate the subdirectories, I'll get the following List<File>, with ordering order2.

```<code>{someRoot}/
{someRoot}/aardvark.txt
{someRoot}/bar/
{someRoot}/foo/
{someRoot}/food.txt
{someRoot}/zebra.txt
{someRoot}/bar/file1.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz/
{someRoot}/foo/file2.txt
{someRoot}/foo/baz/file3.txt
</code>```

If I create the straightforward Comparator<File>:

```<code>Comparator<File> fc = new Comparator<File>(){
    @Override public int compare(File o1, File o2) {
        return o1.compareTo(o2);
    }
};
</code>```

and I sort, I get this ordering (order3) from lexicographic ordering:

```<code>{someRoot}
{someRoot}/aardvark.txt
{someRoot}/bar
{someRoot}/bar/file1.txt
{someRoot}/foo
{someRoot}/food.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/file2.txt
{someRoot}/zebra.txt
</code>```

But I don't want this ordering (which has problems: note that food.txt comes between directory foo and its sub-items), I want order1. How can I write a Comparator to get me that?

答:
```<code>Comparator<File> fc = new Comparator<File>(){
        @Override public int compare(File o1, File o2) {
            boolean isFirstDirectory = o1.isDirectory();
            boolean isSecondDirectory = o2.isDirectory();

            if(!isFirstDirectory && !isSecondDirectory) {
                return o1.compareTo(o2);

            } else if (isFirstDirectory && !isSecondDirectory){
                return (int) 1;
            } else if(isSecondDirectory && !isFirstDirectory) {
                return -1;
            } else {
                return o1.compareTo(o2);
            }

        }
    };
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm stumped... Let's say I have this directory tree:

{someRoot}/
{someRoot}/bar/
{someRoot}/bar/file1.txt
{someRoot}/foo/
{someRoot}/foo/baz/
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/file2.txt
{someRoot}/aardvark.txt
{someRoot}/food.txt
{someRoot}/zebra.txt

You'll note the ordering. Call this order1. At each stage, the directories come first before the files. (NOTE:  bar/file1.txt comes before foo, so on a global basis, the directories do not all come before all the files.)

If I enumerate this directory tree, and then recursively enumerate the subdirectories, I'll get the following List<File>, with ordering order2.

{someRoot}/
{someRoot}/aardvark.txt
{someRoot}/bar/
{someRoot}/foo/
{someRoot}/food.txt
{someRoot}/zebra.txt
{someRoot}/bar/file1.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz/
{someRoot}/foo/file2.txt
{someRoot}/foo/baz/file3.txt

If I create the straightforward Comparator<File>:

Comparator<File> fc = new Comparator<File>(){
    @Override public int compare(File o1, File o2) {
        return o1.compareTo(o2);
    }
};

and I sort, I get this ordering (order3) from lexicographic ordering:

{someRoot}
{someRoot}/aardvark.txt
{someRoot}/bar
{someRoot}/bar/file1.txt
{someRoot}/foo
{someRoot}/food.txt
{someRoot}/foo/abracadabra.txt
{someRoot}/foo/baz
{someRoot}/foo/baz/file3.txt
{someRoot}/foo/file2.txt
{someRoot}/zebra.txt

But I don't want this ordering (which has problems: note that food.txt comes between directory foo and its sub-items), I want order1. How can I write a Comparator to get me that?


答:
-s and following input file name should be separate arguments to call, as they are in the command line:

```<code>call(["toAmos", "-s", inputfile, "-o", output_basename + ".afg"])
</code>```

Title: python subprocess.call() modifies arguments before passing it to shell-script?

Body:
-s and following input file name should be separate arguments to call, as they are in the command line:

call(["toAmos", "-s", inputfile, "-o", output_basename + ".afg"])


问:
How to get a persistent udid in Android?
I am developing a social media app and I want to generate a unique number for every device that registers to my server. My question is, how to generate a udid that won't change in the furure.

For example, the user uninstall the app and than install it again (udid generation activated) it has to be the same one that was before the uninstall. Also, the udid has to be in the following format:

```<code>c376e418-da42-39fb-0000-d821f1fd2804
</code>```

Please share any ideas!

答:
You can use check following code to to generate unique udid.</p>

```<code> TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String deviceId;
if (telephonyManager.getDeviceId() != null)
    deviceId = telephonyManager.getDeviceId(); //*** use for mobiles
else {
    deviceId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
}
return deviceId;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am developing a social media app and I want to generate a unique number for every device that registers to my server. My question is, how to generate a udid that won't change in the furure.

For example, the user uninstall the app and than install it again (udid generation activated) it has to be the same one that was before the uninstall. Also, the udid has to be in the following format:

c376e418-da42-39fb-0000-d821f1fd2804

Please share any ideas!

Body:
You can use check following code to to generate unique udid.

 TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String deviceId;
if (telephonyManager.getDeviceId() != null)
    deviceId = telephonyManager.getDeviceId(); //*** use for mobiles
else {
    deviceId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
}
return deviceId;


问:
TreeNode Breadth first enum?
Right now my loop is

```<code>for (TreeNode n = e.Node.FirstNode; n != null; n = n.NextNode)
</code>```

and my data is something like

```<code>a
    a1
    a2
b
    b1
</code>```

I want to enum breadth only (a, b etc, not a1, a2 etc). How do i do this?

答:
Modify code provided by bstoney
1. push root node to currentLevel queue
2. mark nextLevel = new Queue();</p>

```<code>        Queue<TreeNode> currentLevel = new Queue<TreeNode>();
        Queue<TreeNode> nextLevel = new Queue<TreeNode>();
        // 1. push root to the queue
        currentLevel.Enqueue(treeView1.Nodes[0]);

        // pop the first item from the front of the queue
        while (currentLevel.Count > 0)
        {
            while (currentLevel.Count > 0)
            {
                TreeNode n = currentLevel.Dequeue();
                Console.WriteLine(n.Text);

                // Add child items to next level
                foreach (TreeNode child in n.Nodes)
                {
                    nextLevel.Enqueue(child);
                }

            }
            // Switch to next level
            currentLevel = nextLevel;
            // 2. mark this line
            //nextLevel = new Queue<TreeNode>();
        }
</code>```

Title: TreeNode Breadth first enum?

Body:
Right now my loop is

for (TreeNode n = e.Node.FirstNode; n != null; n = n.NextNode)

and my data is something like

a
    a1
    a2
b
    b1

I want to enum breadth only (a, b etc, not a1, a2 etc). How do i do this?

Body:
Modify code provided by bstoney
1. push root node to currentLevel queue
2. mark nextLevel = new Queue();

        Queue<TreeNode> currentLevel = new Queue<TreeNode>();
        Queue<TreeNode> nextLevel = new Queue<TreeNode>();
        // 1. push root to the queue
        currentLevel.Enqueue(treeView1.Nodes[0]);

        // pop the first item from the front of the queue
        while (currentLevel.Count > 0)
        {
            while (currentLevel.Count > 0)
            {
                TreeNode n = currentLevel.Dequeue();
                Console.WriteLine(n.Text);

                // Add child items to next level
                foreach (TreeNode child in n.Nodes)
                {
                    nextLevel.Enqueue(child);
                }

            }
            // Switch to next level
            currentLevel = nextLevel;
            // 2. mark this line
            //nextLevel = new Queue<TreeNode>();
        }


问:
ng-repeat not populating table
I've populated a table with data from a JSON file, and then when the user clicks on an item in the table, a container and it's fields display below and it SHOULD be populated with that specific data, though it isn't.

The function select is invoked through list-patents.htm which contains the table with a list of patents. I have used the $rootScope object so the function is accessible from multiple controllers i.e. patentDetailsCtrl

Why isn't my table in patent-item.htm being populated with the ng-repeat directive?

```<code>var app = angular.module('myApp', ['ngRoute', 'angularMoment', 'ui.router', "chart.js"]);

$stateProvider
    .state("patents.list.item", {
        url: "/patent-item",
        templateUrl: "templates/patents/list/patent-item.htm",
        params: {
            id: null,
            appNo: null,
            clientRef: null,
            costToRenew: null,
            renewalDueDate: null,
            basketStatus: null,
            costBandEnd: null,
            nextStage: null
        },
        controller: "patentDetailsCtrl"
    })

app.run(function($rootScope) {
    $rootScope.select = function() {
        return $rootScope.patentItem = item;
    }
});

app.controller('patentDetailsCtrl', ['$scope', '$http', function($scope, $http) {

    $scope.selectedPatent = $scope.patentItem;

    console.log($scope.selectedPatent);

}]);
</code>```

list-patents.htm

```<code><tbody>
    <tr ng-repeat="x in patents">
        <td ng-click="select(x)"><a ui-sref="patents.list.item({id: x.id, appNo: x.applicationNumber, clientRef: x.clientRef, costToRenew: x.costToRenew, renewalDueDate: x.renewalDueDate, basketStatus: x.basketStatus, costBandEnd: x.costBandEnd, nextStage: x.nextStage})">{{x.applicationNumber}}</a></td>
        <td ng-bind="x.clientRef"></td>
        <td ng-bind="x.costToRenew">$</td>
        <td ng-bind="x.renewalDueDate"></td>
        <td><button type="button" class="btn btn-danger" ng-click="remove(x.id)">Remove</button></td>
    </tr>
</tbody>
</code>```

patent-item.htm

```<code><table>
    <tbody>
        <thead>
            <tr>
                <td>applicationNumber</td>
                <td>clientRef</td>
                <td>costToRenew</td>
                <td>renewalDueDate</td>
                <td>basketStatus</td>
                <td>costBandEnd</td>
                <td>nextStage</td>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="x in selectedPatent">
                <td>{{x.applicationNumber}}</td>
                <td>{{x.clientRef}}</td>
                <td>{{x.costToRenew}}</td>
                <td>{{x.renewalDueDate}}</td>
                <td>{{x.basketStatus}}</td>
                <td>{{x.costBandEnd}}</td>
                <td>{{x.nextStage}}</td>
            </tr>
        </tbody>
    </table>
</tbody>
</code>```

答:
To me it seems like you're trying to access the patentItem selected in your select function. If you're passing it to the $rootScope this way, you will also need to access it this way.

So change the line as follows...

```<code>$scope.selectedPatent = $rootScope.patentItem
</code>```

Title: ng-repeat not populating table

Body:
I've populated a table with data from a JSON file, and then when the user clicks on an item in the table, a container and it's fields display below and it SHOULD be populated with that specific data, though it isn't.

The function select is invoked through list-patents.htm which contains the table with a list of patents. I have used the $rootScope object so the function is accessible from multiple controllers i.e. patentDetailsCtrl

Why isn't my table in patent-item.htm being populated with the ng-repeat directive?

var app = angular.module('myApp', ['ngRoute', 'angularMoment', 'ui.router', "chart.js"]);

$stateProvider
    .state("patents.list.item", {
        url: "/patent-item",
        templateUrl: "templates/patents/list/patent-item.htm",
        params: {
            id: null,
            appNo: null,
            clientRef: null,
            costToRenew: null,
            renewalDueDate: null,
            basketStatus: null,
            costBandEnd: null,
            nextStage: null
        },
        controller: "patentDetailsCtrl"
    })

app.run(function($rootScope) {
    $rootScope.select = function() {
        return $rootScope.patentItem = item;
    }
});

app.controller('patentDetailsCtrl', ['$scope', '$http', function($scope, $http) {

    $scope.selectedPatent = $scope.patentItem;

    console.log($scope.selectedPatent);

}]);

list-patents.htm

        {{x.applicationNumber}}

        $

        <button type="button" class="btn btn-danger" ng-click="remove(x.id)">Remove</button>

patent-item.htm

                applicationNumber
                clientRef
                costToRenew
                renewalDueDate
                basketStatus
                costBandEnd
                nextStage

                {{x.applicationNumber}}
                {{x.clientRef}}
                {{x.costToRenew}}
                {{x.renewalDueDate}}
                {{x.basketStatus}}
                {{x.costBandEnd}}
                {{x.nextStage}}

Body:
To me it seems like you're trying to access the patentItem selected in your select function. If you're passing it to the $rootScope this way, you will also need to access it this way.

So change the line as follows...

$scope.selectedPatent = $rootScope.patentItem


问:
Invalid content was found starting with element 'converter-for-class' in jsf
I use JSF for my project and I define a converter in faces-config.xml like bellow:

```<code><converter>
  <description>myDateTimeConverter</description>
  <display-name>myDateTimeConverter</display-name>
  <converter-id>myDateTimeConverter</converter-id>
  <converter-for-class>java.util.Date</converter-for-class>
  <converter-class>controller.MyDateTimeConverter</converter-class>
 </converter>
</code>```

And I get an error in  (in eclipse):

```<code>cvc-complex-type.2.4.a: Invalid content was found starting with element 'converter-for-class'. One of '{"http://java.sun.com/xml/ns/javaee":converter-class}' is
 expected.
</code>```

答:
Either use converter-id or either use converter-class. If you use id then JSF expects converter-class after it. That's why it says 'One of '{"http://java.sun.com/xml/ns/javaee":converter-class}' is
 expected.'. If you copied this from a tutorial, the tutorial contains an error ;-).</p>

Body:
I use JSF for my project and I define a converter in faces-config.xml like bellow:

<converter>
  <description>myDateTimeConverter</description>
  <display-name>myDateTimeConverter</display-name>
  <converter-id>myDateTimeConverter</converter-id>
  <converter-for-class>java.util.Date</converter-for-class>
  <converter-class>controller.MyDateTimeConverter</converter-class>
 </converter>

And I get an error in  (in eclipse):

cvc-complex-type.2.4.a: Invalid content was found starting with element 'converter-for-class'. One of '{"http://java.sun.com/xml/ns/javaee":converter-class}' is
 expected.


问:
How to set Meld as git mergetool
I've set:

```<code>git config --global merge.tool meld
git config --global mergetool.meld.path c:/Progra~2/meld/bin/
</code>```

On "git mergetool" it writes:

```<code>Hit return to start merge resolution tool (meld):
The merge tool meld is not available as 'c:/Progra~2/meld/bin/'
</code>```

I have tried also:

/c/Progra~2/meld/bin/

"/c/Program files (x86)/meld/bin/"

"c:/Program files (x86)/meld/bin/"

result is the same.

when I go to C:/Program files (x86)/meld/bin/ and run

```<code>python meld
</code>```

the tool runs.

答:
For windows add the path for meld is like below:

```<code> git config --global mergetool.meld.path C:\\Meld_run\\Meld.exe
</code>```

Title: How to set Meld as git mergetool

Body:
I've set:

git config --global merge.tool meld
git config --global mergetool.meld.path c:/Progra~2/meld/bin/

On "git mergetool" it writes:

Hit return to start merge resolution tool (meld):
The merge tool meld is not available as 'c:/Progra~2/meld/bin/'

I have tried also:

/c/Progra~2/meld/bin/

"/c/Program files (x86)/meld/bin/"

"c:/Program files (x86)/meld/bin/"

result is the same.

when I go to C:/Program files (x86)/meld/bin/ and run

python meld

the tool runs.

Body:
For windows add the path for meld is like below:

 git config --global mergetool.meld.path C:\\Meld_run\\Meld.exe


问:
Monoidal folds on fixed points
Given an arbitrary datastructure with a fixed point, can we construct an monoidal algebra without manually specifying all cases?

Assume we are given the datatype Expr as below. Using the recursion-schemes library, we can derive a base functor ExprF, which automatically also has Functor, Foldable and Traversable instances.

{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}

import Data.Semigroup (Sum(..))
import Data.Functor.Foldable
import Data.Functor.Foldable.TH

import Prelude hiding (fail)

data Expr = Var String
          | Const Int
          | Add [Expr]
          | Mult [Expr]
          deriving Show

$(makeBaseFunctor ''Expr)

expr :: Fix ExprF
expr = ana project $ Add [Const 1, Const 2, Mult [Const 3, Const 4], Var "hello"]
```

<p>Now, let's say we want to count the number of leaves in <code>expr</code>. We can easily write an algebra for such a small datastructure:</p>

<pre class="lang-haskell prettyprint-override"><code>alg (ConstF _) = 1
alg (VarF   _) = 1
alg (AddF  xs) = sum xs
alg (MulF  xs) = sum xs
</code>```

Now, we can call cata alg expr, which returns 5, the correct result.

Let's assume Expr grows really big and complex and we don't want to manually write cases for all data constructors. How does cata know how to combine the results from all cases? I suspect that this is possible using Monoids, possibly in conjunction with the Const functor (not entirely sure about that last part though).

fail = getSum $ foldMap (const (Sum 1) . unfix) $ unfix expr
```

fail returns 4, whereas we actually have 5 leaves. I assume that the problem lies in the fixed point, because we are only able to peel of one layer of Fixing and therefore the Mult [..] is only counted as one leaf.

Is it possible to somehow generically fold the entire fixed point and collecting the results in a Monoid-like structure without manually specifying all instances? What I want is kind of foldMap but in a more generic way.

I have a feeling I am missing something really obvious.

答:
Here's the essence of a solution. I've switched on

```<code>{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable, PatternSynonyms #-}
</code>```

Let's just recap fixpoints and catamorphisms.

```<code>newtype Fix f = In {out :: f (Fix f)}

cata :: Functor f => (f t -> t) -> Fix f -> t
cata alg = alg . fmap (cata alg) . out
</code>```

The algebra, alg :: f t -> t, takes a node where the children have already been replaced by a t value, then returns the t for the parent. The cata operator works by unpacking the parent node, processing all its children recursively, then applying alg to finish the job.

So, if we want to count leaves in such a structure, we can start like this:

```<code>leaves :: (Foldable f, Functor f) => Fix f -> Integer
leaves = cata sumOrOne where
  -- sumOrOne :: f Integer -> Integer
</code>```

The algebra, sumOrOne can see the number of leaves in each child of the parent node. We can use cata because f is a Functor. And because f is Foldable, we can compute the total number of leaves in the children.

```<code>  sumOrOne fl = case sum fl of
    ...
</code>```

There are then two possibilities: if the parent has no children, its leaf sum will be 0, which we can detect, but that means the parent is itself a leaf, so 1 should be returned. Otherwise, the leaf sum will be nonzero, in which case the parent is not a leaf, so its leaf sum is indeed the total leaf sum of its children. That gives us

```<code>leaves :: (Foldable f, Functor f) => Fix f -> Integer
leaves = cata sumOrOne where
  sumOrOne fl{- number of leaves in each child-} = case sum fl of
    0 -> 1  -- no leaves in my children means I am a leaf
    l -> l  -- otherwise, pass on the total
</code>```

A quick example, based on Hutton's Razor (the expression language with integers and addition, which is often the simplest thing that illustrates the point). The expressions are generated from Hutton's functor.

```<code>data HF h = Val Int | h :+: h deriving (Functor, Foldable, Traversable)
</code>```

I introduce some pattern synonyms to recover the look and feel of a bespoke type.

```<code>pattern V x    = In (Val x)
pattern s :+ t = In (s :+: t)
</code>```

I cook up a quick example expression, with some leaves that are three levels deep.

```<code>example :: Fix HF
example = (V 1 :+ V 2) :+ ((V 3 :+ V 4) :+ V 5)
</code>```

Sure enough

```<code>Ok, modules loaded: Leaves.
*Leaves> leaves example
5
</code>```

An alternative approach is to be functorial and foldable in substructures of interest, in this case, stuff at leaves. (We get exactly the free monads.)

```<code>data Tree f x = Leaf x | Node (f (Tree f x)) deriving (Functor, Foldable)
</code>```

Once you've made the leaf/node separation part of your basic construction, you can visit the leaves directly with foldMap. Throwing in a bit of Control.Newtype, we get

```<code>ala' Sum foldMap (const 1)  :: Foldable f => f x -> Integer
</code>```

which is below the Fairbairn Threshold (i.e., short enough not to need a name and all the clearer for not having one).

The trouble, of course, is that data structures are often functorial in "substructures of interest" in multiple interesting but conflicting ways. Haskell isn't always the best at letting us access "found functoriality": we somehow have to predict the functoriality we need when we parametrise a data type at declaration time. But there's still time to change all that...

Title: Monoidal folds on fixed points

Body:
Given an arbitrary datastructure with a fixed point, can we construct an monoidal algebra without manually specifying all cases?

Assume we are given the datatype Expr as below. Using the recursion-schemes library, we can derive a base functor ExprF, which automatically also has Functor, Foldable and Traversable instances.

{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}

import Data.Semigroup (Sum(..))
import Data.Functor.Foldable
import Data.Functor.Foldable.TH

import Prelude hiding (fail)

data Expr = Var String
          | Const Int
          | Add [Expr]
          | Mult [Expr]
          deriving Show

$(makeBaseFunctor ''Expr)

expr :: Fix ExprF
expr = ana project $ Add [Const 1, Const 2, Mult [Const 3, Const 4], Var "hello"]

Now, let's say we want to count the number of leaves in expr. We can easily write an algebra for such a small datastructure:

alg (ConstF _) = 1
alg (VarF   _) = 1
alg (AddF  xs) = sum xs
alg (MulF  xs) = sum xs

Now, we can call cata alg expr, which returns 5, the correct result.

Let's assume Expr grows really big and complex and we don't want to manually write cases for all data constructors. How does cata know how to combine the results from all cases? I suspect that this is possible using Monoids, possibly in conjunction with the Const functor (not entirely sure about that last part though).

fail = getSum $ foldMap (const (Sum 1) . unfix) $ unfix expr

fail returns 4, whereas we actually have 5 leaves. I assume that the problem lies in the fixed point, because we are only able to peel of one layer of Fixing and therefore the Mult [..] is only counted as one leaf.

Is it possible to somehow generically fold the entire fixed point and collecting the results in a Monoid-like structure without manually specifying all instances? What I want is kind of foldMap but in a more generic way.

I have a feeling I am missing something really obvious.

Body:
Here's the essence of a solution. I've switched on

{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable, PatternSynonyms #-}

Let's just recap fixpoints and catamorphisms.

newtype Fix f = In {out :: f (Fix f)}

cata :: Functor f => (f t -> t) -> Fix f -> t
cata alg = alg . fmap (cata alg) . out

The algebra, alg :: f t -> t, takes a node where the children have already been replaced by a t value, then returns the t for the parent. The cata operator works by unpacking the parent node, processing all its children recursively, then applying alg to finish the job.

So, if we want to count leaves in such a structure, we can start like this:

leaves :: (Foldable f, Functor f) => Fix f -> Integer
leaves = cata sumOrOne where
  -- sumOrOne :: f Integer -> Integer

The algebra, sumOrOne can see the number of leaves in each child of the parent node. We can use cata because f is a Functor. And because f is Foldable, we can compute the total number of leaves in the children.

  sumOrOne fl = case sum fl of
    ...

There are then two possibilities: if the parent has no children, its leaf sum will be 0, which we can detect, but that means the parent is itself a leaf, so 1 should be returned. Otherwise, the leaf sum will be nonzero, in which case the parent is not a leaf, so its leaf sum is indeed the total leaf sum of its children. That gives us

leaves :: (Foldable f, Functor f) => Fix f -> Integer
leaves = cata sumOrOne where
  sumOrOne fl{- number of leaves in each child-} = case sum fl of
    0 -> 1  -- no leaves in my children means I am a leaf
    l -> l  -- otherwise, pass on the total

A quick example, based on Hutton's Razor (the expression language with integers and addition, which is often the simplest thing that illustrates the point). The expressions are generated from Hutton's functor.

data HF h = Val Int | h :+: h deriving (Functor, Foldable, Traversable)

I introduce some pattern synonyms to recover the look and feel of a bespoke type.

pattern V x    = In (Val x)
pattern s :+ t = In (s :+: t)

I cook up a quick example expression, with some leaves that are three levels deep.

example :: Fix HF
example = (V 1 :+ V 2) :+ ((V 3 :+ V 4) :+ V 5)

Sure enough

Ok, modules loaded: Leaves.
*Leaves> leaves example
5

An alternative approach is to be functorial and foldable in substructures of interest, in this case, stuff at leaves. (We get exactly the free monads.)

data Tree f x = Leaf x | Node (f (Tree f x)) deriving (Functor, Foldable)

Once you've made the leaf/node separation part of your basic construction, you can visit the leaves directly with foldMap. Throwing in a bit of Control.Newtype, we get

ala' Sum foldMap (const 1)  :: Foldable f => f x -> Integer

which is below the Fairbairn Threshold (i.e., short enough not to need a name and all the clearer for not having one).

The trouble, of course, is that data structures are often functorial in "substructures of interest" in multiple interesting but conflicting ways. Haskell isn't always the best at letting us access "found functoriality": we somehow have to predict the functoriality we need when we parametrise a data type at declaration time. But there's still time to change all that...


问:
Symfony : Get key value from object doctrine
I have this array of objects with doctrine,
how do i scope out one of the values?

This doesnt seem to work for me : todolist[0]->todo_body

```<code>todolist
(
    [0] => AppBundle\Entity\Todo Object
    (
        [todo_id:AppBundle\Entity\Todo:private] => 1
        [todo_body:AppBundle\Entity\Todo:private] => Install Symfony
    )

    [1] => AppBundle\Entity\Todo Object
    (
        [todo_id:AppBundle\Entity\Todo:private] => 2
        [todo_body:AppBundle\Entity\Todo:private] => Learn Symfony
    )

    [2] => AppBundle\Entity\Todo Object
    (
        [todo_id:AppBundle\Entity\Todo:private] => 3
        [todo_body:AppBundle\Entity\Todo:private] => Create Controller
    )

    [3] => AppBundle\Entity\Todo Object
    (
        [todo_id:AppBundle\Entity\Todo:private] => 4
        [todo_body:AppBundle\Entity\Todo:private] => Create first page
    )

)
</code>```

答:
AppBundle\Entity\Todo properties like 'todo_body' are clearly private (as stated in dump that you've provided) and therefore you cannot access them directly from outside with $todo->todo_body.

You need a getter method to access such properties.

You can try with something like $todolist[0]->getTodoBody() if you already have a getter in your AppBundle\Entity\Todo class.

If not, you will need to create it in first place. It would look something like:

```<code>public function getTodoBody() {
    return $this->todo_body;
}
</code>```

And similar for todo_id

Body:
I have this array of objects with doctrine,
how do i scope out one of the values?

This doesnt seem to work for me : todolist[0]->todo_body

todolist
(
    [0] => AppBundle\Entity\Todo Object
    (
        [todo_id:AppBundle\Entity\Todo:private] => 1
        [todo_body:AppBundle\Entity\Todo:private] => Install Symfony
    )

    [1] => AppBundle\Entity\Todo Object
    (
        [todo_id:AppBundle\Entity\Todo:private] => 2
        [todo_body:AppBundle\Entity\Todo:private] => Learn Symfony
    )

    [2] => AppBundle\Entity\Todo Object
    (
        [todo_id:AppBundle\Entity\Todo:private] => 3
        [todo_body:AppBundle\Entity\Todo:private] => Create Controller
    )

    [3] => AppBundle\Entity\Todo Object
    (
        [todo_id:AppBundle\Entity\Todo:private] => 4
        [todo_body:AppBundle\Entity\Todo:private] => Create first page
    )

)

Body:
AppBundle\Entity\Todo properties like 'todo_body' are clearly private (as stated in dump that you've provided) and therefore you cannot access them directly from outside with $todo->todo_body.

You need a getter method to access such properties.

You can try with something like $todolist[0]->getTodoBody() if you already have a getter in your AppBundle\Entity\Todo class.

If not, you will need to create it in first place. It would look something like:

public function getTodoBody() {
    return $this->todo_body;
}

And similar for todo_id


问:
objective-c code to right pad a NSString?
Can someone give a code example of how to right pad an NSString in objective-c please?

For example want these strings:

```<code>Testing 123 Long String
Hello World
Short
</code>```

if right padded to a column width of say 12: and then a sting "XXX" is added to the end of each, it would give:

```<code>Testing 123 xxx
Hello World xxx
Short       xxx
</code>```

That is a 2nd column would like up.

答:
Try below. its working for me.</p>

```<code>NSString *someString = @"1234";
NSString *padded = [someString stringByPaddingToLength: 16 withString: @"x" startingAtIndex:0];

NSLog(@"%@", someString);
NSLog(@"%@", padded);
</code>```

Body:
Can someone give a code example of how to right pad an NSString in objective-c please?

For example want these strings:

Testing 123 Long String
Hello World
Short

if right padded to a column width of say 12: and then a sting "XXX" is added to the end of each, it would give:

Testing 123 xxx
Hello World xxx
Short       xxx

That is a 2nd column would like up.

Body:
Try below. its working for me.

NSString *someString = @"1234";
NSString *padded = [someString stringByPaddingToLength: 16 withString: @"x" startingAtIndex:0];

NSLog(@"%@", someString);
NSLog(@"%@", padded);


问:
JMS connection handshake is failing for SSLCipherSuite SSL_RSA_WITH_3DES_EDE_CBC_SHA
I am using Spring boot 1.2.2 and JDK1.8.0.40, I have specified the SSL cipher suit as SSL_RSA_WITH_3DES_EDE_CBC_SHA and also import cer file to keystore.

When I run my project, I set the jvm arguments as following:

```<code>-Djavax.net.debug=all -Djavax.net.ssl.keyStore=/java_home/jre/lib/security/cacerts -Djava.net.keyStorePassword=changeit
</code>```

But I always get

```<code>handing exception:javax.net.ssl.SSLHandshakeException: No appropriate protocol(protocol is disabled or cipher suites are inappropriate)
SEND TLSv1.2 ALERT: fatal, description = handshake_failure
WRITE: TLSv1.2 Alert, length = 2
[Raw write]: length = 7
0000: 15 03 03 00 02 02 28       ......(
called closeSocket()
com.ibm.msg.client.jms.DetailedJMSException: JMSWMQ0018: Failed to connect to queue manager 'XXXX' with connection mode 'Client' and host name 'xxx.xxx.com(xxxxx)'.
</code>```

Indeed I have do several operations to fix the issue, such as:

Replace jce jars to unlimit encrypt

Import cer file to jks

specified jks path in jvm arguments

Using matched SSL Cipher Suite

Using SSL channel

But now, I still failed on handshake and the error logs are same as above.

Or do I need generate the cer from my machine and upload to the server? Could you kindly give some advice?

答:
SSL_RSA_WITH_3DES_EDE_CBC_SHA is an SSL 3 cipher suite. SSL 3 is insecure and disabled by default in Java 8. Is there any reason why you're using a ciphersuite for an insecure protocol?

If you want to stick to a single cipher suite, you can pick one that Java 8 supports.

Body:
I am using Spring boot 1.2.2 and JDK1.8.0.40, I have specified the SSL cipher suit as SSL_RSA_WITH_3DES_EDE_CBC_SHA and also import cer file to keystore.

When I run my project, I set the jvm arguments as following:

-Djavax.net.debug=all -Djavax.net.ssl.keyStore=/java_home/jre/lib/security/cacerts -Djava.net.keyStorePassword=changeit

But I always get

handing exception:javax.net.ssl.SSLHandshakeException: No appropriate protocol(protocol is disabled or cipher suites are inappropriate)
SEND TLSv1.2 ALERT: fatal, description = handshake_failure
WRITE: TLSv1.2 Alert, length = 2
[Raw write]: length = 7
0000: 15 03 03 00 02 02 28       ......(
called closeSocket()
com.ibm.msg.client.jms.DetailedJMSException: JMSWMQ0018: Failed to connect to queue manager 'XXXX' with connection mode 'Client' and host name 'xxx.xxx.com(xxxxx)'.

Indeed I have do several operations to fix the issue, such as:

Replace jce jars to unlimit encrypt

Import cer file to jks

specified jks path in jvm arguments

Using matched SSL Cipher Suite

Using SSL channel

But now, I still failed on handshake and the error logs are same as above.

Or do I need generate the cer from my machine and upload to the server? Could you kindly give some advice?


问:
Remove highlight color but maintain image highlight in Custom UITableViewCell
I am searching this for some time but I never found a solution.

I have a UITableView with custom cells, those cells have an image and I place the labels on it.

The thing is, when I select a cell, the whole cell frame is selected using the default highlight color. I tried changing the style, but if I use cell.selectionStyle = UITableViewCellSelectionStyleNone; the image won't highlight...

Just in case someone asks I created distincts images for highlighted / normal states.

答:
Here's how I made it work:

I'm using a XIB for my cell.  In there I have a background image (not connected to any outlets) that is my normal-state background.  I set that image to also have a highlighted image (a blue version in my case).

I added another UIView, set its background color to clear, and attached it to the cell's selectedBackgroundView outlet. Doing that prevents the normal built-in "set the entire background blue" behavior.

Then I set the cell's selection style to blue (just can't be None as the highlighting won't happen then).


问:
how to delete record through primary key in android
While deleting record through primary key, primary key get null value and record doesn't deleted.

Please look in to my code,

```<code> dataBase.delete(DbHelper.TABLE_PARKSAL_TABLELIST, DbHelper.PARKSALE_PrimeryID+ "=" + primarykeytableid, null);
</code>```

I want to delete whole row data with primary key as well. How to fix it? Thanks in advance.

答:
If you want to delete the row with key is empty or null or your given value, We can delete the row using following,</p>

```<code>String whereClause = DbHelper.PARKSALE_PrimeryID + " = ? OR " // For the value which you give
        + DbHelper.PARKSALE_PrimeryID + " = ? OR " // For empty values
        + DbHelper.PARKSALE_PrimeryID + " IS NUL"; // For Null values
String[] whereArr = new String[] {
        primarykeytableid, "''"
};

dataBase.delete(DbHelper.TABLE_PARKSAL_TABLELIST, whereClause, whereArr);
</code>```

Body:
While deleting record through primary key, primary key get null value and record doesn't deleted.

Please look in to my code,

 dataBase.delete(DbHelper.TABLE_PARKSAL_TABLELIST, DbHelper.PARKSALE_PrimeryID+ "=" + primarykeytableid, null);

I want to delete whole row data with primary key as well. How to fix it? Thanks in advance.

Body:
If you want to delete the row with key is empty or null or your given value, We can delete the row using following,

String whereClause = DbHelper.PARKSALE_PrimeryID + " = ? OR " // For the value which you give
        + DbHelper.PARKSALE_PrimeryID + " = ? OR " // For empty values
        + DbHelper.PARKSALE_PrimeryID + " IS NUL"; // For Null values
String[] whereArr = new String[] {
        primarykeytableid, "''"
};

dataBase.delete(DbHelper.TABLE_PARKSAL_TABLELIST, whereClause, whereArr);


问:
How to get the view UNID in Lotus Notes
I am trying to build a URL to access the attachment in a document in Lotus Notes.

According to IBM lotus notes document, the url to access to an attachment in browser will be like this:
notes://server/db/view/document/$FILE/filename

The document said view could be view name or view id, document could be document id or document name.
I know how to retrieve document UNID in a view. But I don't know how to get the view UNID.
I tried to use the view name but no luck. It does not work.

I am not running any lotus scripts.

Actually, my final goal is to export all documents in a view to a spreadsheet. And build URL for attachments for each row. I am using @Text(@DocumentUniqueID) to get the doc id.

But not sure how to get view id.

答:
To get the view unid without programming, you can open the Domino Designer and then the view list. Without opening a view, you can highlight the view in the view list, then look for the 'properties' pane/section. Open the 'Document IDs' tab and there you will find the UNID, NoteID and some other details for the view.

Of course, these can change, so either a 'db.nsf/0/...'  or a specific view name, 'db.nsf/vwfiles/...' view name is preferable (as noted elsewhere).

Title: How to get the view UNID in Lotus Notes


问:
Bindings from Multiple ViewModels in same View WPF MVVM
I have a WPF MVVM project that includes a View which contains several controls.

There is a DockPanel which contains all the controls in the View with DataContext to a MainViewModel Class, and inside of it there is a Grid with DataContext to other object ViewModel which it's property contained in the MainViewModel Class.

Now, in that Grid I have a 2 buttons surrounds with WrapPanel, and the buttons have a Commands to a property which wrote in the MainViewModel Class, and when I pressed on it nothing happens (Because the Grid's DataContext is to other object).

I need the Commands to be stay in the MainViewModel Class, How can I do that?

XAML: (just the relevant parts)

```<code><DockPanel x:Name="MonitorParent" DataContext="{Binding MonitorMainViewModel}" LastChildFill="False" Width="1144" HorizontalAlignment="Left">
      .......
    <StackPanel>
        <ContentControl Visibility="{Binding Path=NoMonitorsMessageVisibility, Converter={StaticResource visibilityConverter}}">
            <StackPanel Width="804" Height="574">
                <Grid DataContext="{Binding CurrentMonitor}" Margin="10 0" Height="auto">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" MinHeight="23" />
                        <RowDefinition Height="Auto" MinHeight="23" />
                        <RowDefinition Height="Auto" MinHeight="23" />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="140" />
                    </Grid.ColumnDefinitions>
                    <Label Grid.Column="0" Grid.Row="15"  Content="Serial Number" x:Name="SerialNumber"   />
                    <WrapPanel  DataContext="{Binding MonitorMainViewModel}" HorizontalAlignment="Center" Margin="0,10,0,10" Grid.ColumnSpan="2" Grid.Row="6" >
                        <Button Content="Add" Width="60" Margin="0,0,40,0" Command="{Binding AddConfidenceCommand}" />
                        <Button Content="Delete" Width="60" Margin="30,0,0,0" Command="{Binding DeleteConfidenceCommand}"/>
                    </WrapPanel>

                     ........
  </DockPanel
</code>```

答:
Try this:

```<code><Button Content="Add" Width="60" Margin="0,0,40,0"
        Command="{Binding DataContext.AddConfidenceCommand, ElementName=MonitorParent}" />
</code>```

Or:

```<code><Button Content="Add" Width="60" Margin="0,0,40,0"
        Command="{Binding DataContext.AddConfidenceCommand, RelativeSource={RelativeSource AncestorType=DockPanel}}" />
</code>```

Body:
I have a WPF MVVM project that includes a View which contains several controls.

There is a DockPanel which contains all the controls in the View with DataContext to a MainViewModel Class, and inside of it there is a Grid with DataContext to other object ViewModel which it's property contained in the MainViewModel Class.

Now, in that Grid I have a 2 buttons surrounds with WrapPanel, and the buttons have a Commands to a property which wrote in the MainViewModel Class, and when I pressed on it nothing happens (Because the Grid's DataContext is to other object).

I need the Commands to be stay in the MainViewModel Class, How can I do that?

XAML: (just the relevant parts)

<DockPanel x:Name="MonitorParent" DataContext="{Binding MonitorMainViewModel}" LastChildFill="False" Width="1144" HorizontalAlignment="Left">
      .......
    <StackPanel>
        <ContentControl Visibility="{Binding Path=NoMonitorsMessageVisibility, Converter={StaticResource visibilityConverter}}">
            <StackPanel Width="804" Height="574">
                <Grid DataContext="{Binding CurrentMonitor}" Margin="10 0" Height="auto">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" MinHeight="23" />
                        <RowDefinition Height="Auto" MinHeight="23" />
                        <RowDefinition Height="Auto" MinHeight="23" />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="140" />
                    </Grid.ColumnDefinitions>

                    <WrapPanel  DataContext="{Binding MonitorMainViewModel}" HorizontalAlignment="Center" Margin="0,10,0,10" Grid.ColumnSpan="2" Grid.Row="6" >
                        <Button Content="Add" Width="60" Margin="0,0,40,0" Command="{Binding AddConfidenceCommand}" />
                        <Button Content="Delete" Width="60" Margin="30,0,0,0" Command="{Binding DeleteConfidenceCommand}"/>
                    </WrapPanel>

                     ........
  </DockPanel

Body:
Try this:

<Button Content="Add" Width="60" Margin="0,0,40,0"
        Command="{Binding DataContext.AddConfidenceCommand, ElementName=MonitorParent}" />

Or:

<Button Content="Add" Width="60" Margin="0,0,40,0"
        Command="{Binding DataContext.AddConfidenceCommand, RelativeSource={RelativeSource AncestorType=DockPanel}}" />


问:
How to loop through two Sass maps?
I have two sass maps.

```<code>$map-one: (
 name1: value1,
 name2: value2,
 name3: value3,
 name4: value4,
);

$map-two: (
 name5: value5,
 name6: value6,
);
</code>```

I created an each loop to generate a class with the name as the class name holding the value as the content.

```<code>@each $name, $value in $map-one {
 .#{$name} {
  content: $value;
 }
}
</code>```

Now the above is for only one map. But I want to do the same for map-two. Is there a way to add that to the same loop above without creating another loop?

Something like:

```<code>@each $name, $value in $map-one and $name2, $value2 in $map-two {
 .#{$name} {
  content: $value;
 }

 .#{$name2} {
  content: $value2;
 }
}
</code>```

答:
If both maps has same structure then you should use a single map only, but if you want to use both then use map-merge() like,</p>

```<code>$map-one: (
   name1: value1,
   name2: value2,
   name3: value3,
   name4: value4,
);

$map-two: (
   name5: value5,
   name6: value6,
);

$merged: map-merge($map-one, $map-two);
@each $name, $value in $merged {
   .#{$name} {
       content: $value;
    }
}
</code>```

Title: How to loop through two Sass maps?

Body:
I have two sass maps.

$map-one: (
 name1: value1,
 name2: value2,
 name3: value3,
 name4: value4,
);

$map-two: (
 name5: value5,
 name6: value6,
);

I created an each loop to generate a class with the name as the class name holding the value as the content.

@each $name, $value in $map-one {
 .#{$name} {
  content: $value;
 }
}

Now the above is for only one map. But I want to do the same for map-two. Is there a way to add that to the same loop above without creating another loop?

Something like:

@each $name, $value in $map-one and $name2, $value2 in $map-two {
 .#{$name} {
  content: $value;
 }

 .#{$name2} {
  content: $value2;
 }
}

Body:
If both maps has same structure then you should use a single map only, but if you want to use both then use map-merge() like,

$map-one: (
   name1: value1,
   name2: value2,
   name3: value3,
   name4: value4,
);

$map-two: (
   name5: value5,
   name6: value6,
);

$merged: map-merge($map-one, $map-two);
@each $name, $value in $merged {
   .#{$name} {
       content: $value;
    }
}


问:
Upgrade from Megento 2.0.2 fails "An error has happened during application run. See exception log for details."
Magento 2.0.2 on CentOS using Bitnami stack. Followed command line upgrade using Composer.

Trying to load the shop front after upgrade (followed steps without errors) results in the error above. The /var/log/exception.log file shows:-

```<code>[2016-06-09 15:18:04] main.CRITICAL: exception 'Magento\Framework\Exception\LocalizedException' with message 'Source class "" for "Magento\Framework\App\Response\Http\Interceptor" generation does not exist.' in /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/Code/Generator.php:171
Stack trace:
0 /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/Code/Generator.php(100): Magento\Framework\Code\Generator->tryToLoadSourceClass('Magento\\Framewo...', Object(Magento\Framework\Interception\Code\Generator\Interceptor))
1 /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/Code/Generator/Autoloader.php(35): Magento\Framework\Code\Generator->generateClass('Magento\\Framewo...')
2 [internal function]: Magento\Framework\Code\Generator\Autoloader->load('Magento\\Framewo...')
3 /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/ObjectManager/Factory/AbstractFactory.php(105): spl_autoload_call('Magento\\Framewo...')
4 /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/ObjectManager/Factory/Compiled.php(88): Magento\Framework\ObjectManager\Factory\AbstractFactory->createObject('Magento\\Framewo...', Array)
5 /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/ObjectManager/Factory/Compiled.php(130): Magento\Framework\ObjectManager\Factory\Compiled->create('Magento\\Framewo...')
6 /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/ObjectManager/Factory/Compiled.php(67): Magento\Framework\ObjectManager\Factory\Compiled->get('Magento\\Framewo...')
7 /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/ObjectManager/ObjectManager.php(57): Magento\Framework\ObjectManager\Factory\Compiled->create('Magento\\Framewo...', Array)
8 /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/App/Bootstrap.php(233): Magento\Framework\ObjectManager\ObjectManager->create('Magento\\Framewo...', Array)
9 /opt/bitnami/apps/magento/htdocs/index.php(38): Magento\Framework\App\Bootstrap->createApplication('Magento\\Framewo...')
10 {main} [] []
}
</code>```

Checked permissions and cleared var/cache manually, but to no avail.

Any ideas how I can resolve this error?

答:
for ubuntu:
1) goto var/www/html/magento(Root Folder where your magento is) or in htdocs if you have installed lampp.
2) sudo rm -Rf var/generation
3) sudo bin/magento cache:clean
4) sudo bin/magento cache:flush

Done.....

Body:
Magento 2.0.2 on CentOS using Bitnami stack. Followed command line upgrade using Composer.

Trying to load the shop front after upgrade (followed steps without errors) results in the error above. The /var/log/exception.log file shows:-

[2016-06-09 15:18:04] main.CRITICAL: exception 'Magento\Framework\Exception\LocalizedException' with message 'Source class "" for "Magento\Framework\App\Response\Http\Interceptor" generation does not exist.' in /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/Code/Generator.php:171
Stack trace:
0 /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/Code/Generator.php(100): Magento\Framework\Code\Generator->tryToLoadSourceClass('Magento\\Framewo...', Object(Magento\Framework\Interception\Code\Generator\Interceptor))
1 /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/Code/Generator/Autoloader.php(35): Magento\Framework\Code\Generator->generateClass('Magento\\Framewo...')
2 [internal function]: Magento\Framework\Code\Generator\Autoloader->load('Magento\\Framewo...')
3 /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/ObjectManager/Factory/AbstractFactory.php(105): spl_autoload_call('Magento\\Framewo...')
4 /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/ObjectManager/Factory/Compiled.php(88): Magento\Framework\ObjectManager\Factory\AbstractFactory->createObject('Magento\\Framewo...', Array)
5 /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/ObjectManager/Factory/Compiled.php(130): Magento\Framework\ObjectManager\Factory\Compiled->create('Magento\\Framewo...')
6 /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/ObjectManager/Factory/Compiled.php(67): Magento\Framework\ObjectManager\Factory\Compiled->get('Magento\\Framewo...')
7 /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/ObjectManager/ObjectManager.php(57): Magento\Framework\ObjectManager\Factory\Compiled->create('Magento\\Framewo...', Array)
8 /opt/bitnami/apps/magento/htdocs/lib/internal/Magento/Framework/App/Bootstrap.php(233): Magento\Framework\ObjectManager\ObjectManager->create('Magento\\Framewo...', Array)
9 /opt/bitnami/apps/magento/htdocs/index.php(38): Magento\Framework\App\Bootstrap->createApplication('Magento\\Framewo...')
10 {main} [] []
}

Checked permissions and cleared var/cache manually, but to no avail.

Any ideas how I can resolve this error?


问:
Spring boot running from Eclipse vs running from Terminal [Not Loading properties file]
I am working on spring boot application in which I have made a property file,

application.properties

```<code>#Generated by Eclipse Messages Editor (Eclipse Babel)
# ===============================
# = Spring Application
# ===============================

server.port = 80
</code>```

and here is main method:

```<code>public static void main(String[] args) throws Exception {
    new SpringApplicationBuilder().sources(SpringBootWebApplication.class).properties(System.getProperties()).run(args);
}
</code>```

it is working fine when I am running it on eclipse.

if when I am running using commandline:

```<code>java -jar target\tmfboot-0.0.1-SNAPSHOT.jar
</code>```

application is running on default port of tomcat 8080

I think it is not loading application.properties file while running using terminal.

I’m using Maven 3.2.

答:
Your properties file should be under the resources folder.

if you using maven/gradle it should be under src/main/java/resources/application.properties

Body:
I am working on spring boot application in which I have made a property file,

application.properties

#Generated by Eclipse Messages Editor (Eclipse Babel)
# ===============================
# = Spring Application
# ===============================

server.port = 80

and here is main method:

public static void main(String[] args) throws Exception {
    new SpringApplicationBuilder().sources(SpringBootWebApplication.class).properties(System.getProperties()).run(args);
}

it is working fine when I am running it on eclipse.

if when I am running using commandline:

java -jar target\tmfboot-0.0.1-SNAPSHOT.jar

application is running on default port of tomcat 8080

I think it is not loading application.properties file while running using terminal.

I’m using Maven 3.2.


问:
fill cells with formula 'MATCH', where the lookup_value increments but lookup_array stays
For example, in this case:

```<code>1| A     |    B   |     C  |
2|MyData | Lookup | Result |
3|Apple  | Grape  |   4    |
4|Banana | Cherry |   3    |
5|Cherry | Cat    |  #N/A  |
6|Grape  | Dog    |  #N/A  |
7|Mango  | ...    | ...    |
8|       | ...    | ...    |
</code>```

I know the formula for cell C3 is =MATCH(B3,A3:A7,0).
Then for C4, it's =MATCH(B4,A3:A7,0).

The issue is, I can't find a way to copy it down. Excel tries to increment the range offset (i.e. change A3:A7 to A5:A9) and I can't find a way to stop this.

Obviously I don't want to fill the formula cell-by-cell, so is it possible to let Excel fill it for me, while incrementing lookup_value without incrementing lookup_array?

答:
Take a look at this article about absolute and relative cell references.

A relative cell reference uses just the column letter and the row number. Think about this in relation to the current cell. Think of the current cell as "that's ME".

Let's say the current cell is B2 and the formula in that cell is =A1.

For Excel, this relative reference means "the cell one column to the left of ME and one row above ME".

If you copy the formula down, it will still be the same relationship to the current cell, i.e. one column to the left and one row above "ME" or the current cell.

With a $ sign you can throw an anchor and hook a cell reference to an absolute position. The "hook" can be used for either the column letter, or the row number, or both.

So, using our above formula in cell B2:

=$A1 means a cell in column A, but one row above ME. If you copy that formula down it will change to =$A2 and =$A3 etc, and always refer to column A and always refer to one row above the current row (ME). If the formula is copied to the right, the $ sign will lock the column and it will not change. The row will stay the same, anyway, if the formula is copied sideways.

If you use a dollar sign only in front of the row number like this:

=A$1 it means the cell in row 1 in the column to the left of ME. If you copy that formula down, the row number will not change, because it is locked with the $ sign. If you copy the formula to the right, the column letter will adjust to B, then C, then D, etc., because that will be relative to the current cell, the "ME".

If you use a $ sign in front of both the column letter AND the row number, the cell reference will not change when copied anywhere.

With this in mind, lock the reference for the range that you want to use for the Match function. You always want to look in A3 to A7, so you need to use $A$3:$A$7 in the formula

```<code>=MATCH(B3,$A$3:$A$7,0)
</code>```

Don't worry about the B3, because you'll be copying DOWN, so only the row number of the B3 will change to B4, B5, etc. But you ALWAYS want to look in A3:A7, so you want to make at least the row references of that range absolute. Making the column references absolute is not required in this scenario, but it does not hurt.

Body:
For example, in this case:

1| A     |    B   |     C  |
2|MyData | Lookup | Result |
3|Apple  | Grape  |   4    |
4|Banana | Cherry |   3    |
5|Cherry | Cat    |  #N/A  |
6|Grape  | Dog    |  #N/A  |
7|Mango  | ...    | ...    |
8|       | ...    | ...    |

I know the formula for cell C3 is =MATCH(B3,A3:A7,0).
Then for C4, it's =MATCH(B4,A3:A7,0).

The issue is, I can't find a way to copy it down. Excel tries to increment the range offset (i.e. change A3:A7 to A5:A9) and I can't find a way to stop this.

Obviously I don't want to fill the formula cell-by-cell, so is it possible to let Excel fill it for me, while incrementing lookup_value without incrementing lookup_array?

Body:
Take a look at this article about absolute and relative cell references.

A relative cell reference uses just the column letter and the row number. Think about this in relation to the current cell. Think of the current cell as "that's ME".

Let's say the current cell is B2 and the formula in that cell is =A1.

For Excel, this relative reference means "the cell one column to the left of ME and one row above ME".

If you copy the formula down, it will still be the same relationship to the current cell, i.e. one column to the left and one row above "ME" or the current cell.

With a $ sign you can throw an anchor and hook a cell reference to an absolute position. The "hook" can be used for either the column letter, or the row number, or both.

So, using our above formula in cell B2:

=$A1 means a cell in column A, but one row above ME. If you copy that formula down it will change to =$A2 and =$A3 etc, and always refer to column A and always refer to one row above the current row (ME). If the formula is copied to the right, the $ sign will lock the column and it will not change. The row will stay the same, anyway, if the formula is copied sideways.

If you use a dollar sign only in front of the row number like this:

=A$1 it means the cell in row 1 in the column to the left of ME. If you copy that formula down, the row number will not change, because it is locked with the $ sign. If you copy the formula to the right, the column letter will adjust to B, then C, then D, etc., because that will be relative to the current cell, the "ME".

If you use a $ sign in front of both the column letter AND the row number, the cell reference will not change when copied anywhere.

With this in mind, lock the reference for the range that you want to use for the Match function. You always want to look in A3 to A7, so you need to use $A$3:$A$7 in the formula

=MATCH(B3,$A$3:$A$7,0)

Don't worry about the B3, because you'll be copying DOWN, so only the row number of the B3 will change to B4, B5, etc. But you ALWAYS want to look in A3:A7, so you want to make at least the row references of that range absolute. Making the column references absolute is not required in this scenario, but it does not hurt.


问:
iOS 32 vs 64 bit apps
So with Apple forcing new apps to support 64 bit, support for iPhone 5 will be completely dropped.

I do know that iPhone 5 can't support 64 bit apps however right now all apps run fine on iPhone 5.

As a developer, I just write my app and I never check a box that converts it to 64. Do all new apps support both 32 and 64 by default? Do I need to take extra steps to support 32 bit?

I'm pretty confused. Sorry if it's a silly question.

答:
Yes - every app has 32 and 64 runtimes inside so it can run on both architectures.

You won't be able to send app to the AppStore with very old Xcode versions anyway. It's about devices - iPhone 5 has 32bit architecture. They dropped 32bit so in the future they may remove 32bit runtimes to reduce app size. For now it's an excuse for abandoning old devices.

Title: iOS 32 vs 64 bit apps


问:
JButton in Eclipse: "Button cannot be resolved or is not a field"
New to Java and this Page.
I am trying to perfom a certain action when a JButton is pressed. Following this tutorial (in German, sorry) http://www.java-tutorial.org/actionlistener.html, I used the JFrame Design feature and added content afterwards:

```<code>public class JFrame extends javax.swing.JFrame implements ActionListener
{

private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                JFrame frame = new JFrame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public JFrame()
{

    this.setTitle("BMS Anpassen");

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JButton btnFlush = new JButton("Flush!");
    btnFlush.setBounds(170, 209, 89, 23);
    contentPane.add(btnFlush);

    JSpinner spinner = new JSpinner();
    spinner.setToolTipText("Gib die Spannung ein!");
    spinner.setModel(new SpinnerNumberModel(new Float(3000), new Float(2700), new Float(4100), new Float(100)));
    spinner.setBounds(56, 49, 52, 20);
    contentPane.add(spinner);

    JLabel lblMv = new JLabel("mV");
    lblMv.setFont(new Font("Tahoma", Font.PLAIN, 13));
    lblMv.setBounds(113, 51, 24, 14);
    contentPane.add(lblMv);

    JButton btnSetParameters = new JButton("Set Parameters");
    btnSetParameters.setBounds(152, 175, 130, 23);
    contentPane.add(btnSetParameters);

    //Buttons dem Listener zuordnen
    btnFlush.addActionListener(this);
    btnSetParameters.addActionListener(this);

}

public void actionPerformed(ActionEvent ae){

    if(ae.getSource() == this.btnSetParameters){

    // Parameter in Config schreiben/Write parameters in Config
    FileWriter fw = new FileWriter("ConfigBMS.txt");
    BufferedWriter bw = new BufferedWriter(fw);

    bw.write("25000");
    bw.newLine();
    bw.write("42000");
    bw.newLine();
    bw.write("27000");
    bw.newLine();
    bw.write("41000");

    bw.close();
    }
    else
    {
    }
}

}
</code>```

It now gives me the errormessage "btnSetParameters cannot be resolved or is not a field". Reading through other posts on JButtons here didn't help me or I didn't understand it. I feel like the this in if(ae.getSource() == this.btnSetParameters){ is the problem, but I can't find a way to fix it.

Any push in the right direction is greatly appreciated and thank you in advance,

Oli

答: You have to make the the JButton btnSetParameters a field of the class - currently it's just in the context of the constructor.

Body:
New to Java and this Page.
I am trying to perfom a certain action when a JButton is pressed. Following this tutorial (in German, sorry) http://www.java-tutorial.org/actionlistener.html, I used the JFrame Design feature and added content afterwards:

public class JFrame extends javax.swing.JFrame implements ActionListener
{

private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                JFrame frame = new JFrame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public JFrame()
{

    this.setTitle("BMS Anpassen");

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JButton btnFlush = new JButton("Flush!");
    btnFlush.setBounds(170, 209, 89, 23);
    contentPane.add(btnFlush);

    JSpinner spinner = new JSpinner();
    spinner.setToolTipText("Gib die Spannung ein!");
    spinner.setModel(new SpinnerNumberModel(new Float(3000), new Float(2700), new Float(4100), new Float(100)));
    spinner.setBounds(56, 49, 52, 20);
    contentPane.add(spinner);

    JLabel lblMv = new JLabel("mV");
    lblMv.setFont(new Font("Tahoma", Font.PLAIN, 13));
    lblMv.setBounds(113, 51, 24, 14);
    contentPane.add(lblMv);

    JButton btnSetParameters = new JButton("Set Parameters");
    btnSetParameters.setBounds(152, 175, 130, 23);
    contentPane.add(btnSetParameters);

    //Buttons dem Listener zuordnen
    btnFlush.addActionListener(this);
    btnSetParameters.addActionListener(this);

}

public void actionPerformed(ActionEvent ae){

    if(ae.getSource() == this.btnSetParameters){

    // Parameter in Config schreiben/Write parameters in Config
    FileWriter fw = new FileWriter("ConfigBMS.txt");
    BufferedWriter bw = new BufferedWriter(fw);

    bw.write("25000");
    bw.newLine();
    bw.write("42000");
    bw.newLine();
    bw.write("27000");
    bw.newLine();
    bw.write("41000");

    bw.close();
    }
    else
    {
    }
}

}

It now gives me the errormessage "btnSetParameters cannot be resolved or is not a field". Reading through other posts on JButtons here didn't help me or I didn't understand it. I feel like the this in if(ae.getSource() == this.btnSetParameters){ is the problem, but I can't find a way to fix it.

Any push in the right direction is greatly appreciated and thank you in advance,

Oli


问:
'utf-8' codec error while doc2vec
Unable to run the programme getting decode error. Actually, I am using gensim and trying Doc2vec library and while doing this I am getting this error?
Code:-

```<code>def to_array(self):
    self.sentences = []
    for source, prefix in self.sources.items():
        with utils.smart_open(source) as fin:
            for item_no, line in enumerate(fin):
                self.sentences.append(LabeledSentence(
                    utils.to_unicode(line).split(), [prefix + '_%s' %
item_no]))
    return self.sentences

sentences = LabeledLineSentence(sources)
model = Doc2Vec(min_count=1, window=10, size=100, dm_mean=0, sample=1e-5,
negative=5, workers=12)
model.build_vocab(sentences.to_array())
</code>```

Error:-

```<code>File "<ipython-input-88-eab20df20acc>", line 75, in <module>
model.build_vocab(sentences.to_array())

File "<ipython-input-88-eab20df20acc>", line 58, in to_array
utils.to_unicode(line).split(), [prefix + '_%s' % item_no]))

File "C:\Users\summert\AppData\Local\Continuum\Anaconda3\lib\site-
packages\gensim\utils.py", line 235, in any2unicode
return unicode(text, encoding, errors=errors)

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xef in position 21:
invalid continuation byt
</code>```

答:
It looks like this anaconda gensim program is getting a byte when it wants utf-8. model.build_vocab(sentences.to_array()) is not being fed the type it wants.

Where did you find to_unicode anyhow? Where was 'utils' imported from? I don't think that is regular Python 3. Have a look at this.

Given that you are using Python 3 you probably don't need anything there.

Just replace

```<code>(LabeledSentence(utils.to_unicode(line).split()...
</code>```

with

```<code>(LabeledSentence(line.split()...
</code>```

If that doesn't work try:

```<code> (LabeledSentence(line.encode('utf-8').split()...
</code>```

Title: 'utf-8' codec error while doc2vec

Body:
Unable to run the programme getting decode error. Actually, I am using gensim and trying Doc2vec library and while doing this I am getting this error?
Code:-

def to_array(self):
    self.sentences = []
    for source, prefix in self.sources.items():
        with utils.smart_open(source) as fin:
            for item_no, line in enumerate(fin):
                self.sentences.append(LabeledSentence(
                    utils.to_unicode(line).split(), [prefix + '_%s' %
item_no]))
    return self.sentences

sentences = LabeledLineSentence(sources)
model = Doc2Vec(min_count=1, window=10, size=100, dm_mean=0, sample=1e-5,
negative=5, workers=12)
model.build_vocab(sentences.to_array())

Error:-

File "<ipython-input-88-eab20df20acc>", line 75, in <module>
model.build_vocab(sentences.to_array())

File "<ipython-input-88-eab20df20acc>", line 58, in to_array
utils.to_unicode(line).split(), [prefix + '_%s' % item_no]))

File "C:\Users\summert\AppData\Local\Continuum\Anaconda3\lib\site-
packages\gensim\utils.py", line 235, in any2unicode
return unicode(text, encoding, errors=errors)

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xef in position 21:
invalid continuation byt

Body:
It looks like this anaconda gensim program is getting a byte when it wants utf-8. model.build_vocab(sentences.to_array()) is not being fed the type it wants.

Where did you find to_unicode anyhow? Where was 'utils' imported from? I don't think that is regular Python 3. Have a look at this.

Given that you are using Python 3 you probably don't need anything there.

Just replace

(LabeledSentence(utils.to_unicode(line).split()...

with

(LabeledSentence(line.split()...

If that doesn't work try:

 (LabeledSentence(line.encode('utf-8').split()...