问:
Limit file name before uploading to server in PHP, HTML and Javascript
I have searched in the previous question, but most of the answer is only trim the file name. But for me, I would like to display an alert message to user when their filename length exceeds certain number.

Let say I have an file upload input box:

```<code><input type="file" name="userfile" id="userfile" accept="image/jpeg, application/pdf">
</code>```

When user uploads a file, a function will detect or calculate the length of the filename. If I limit the length to 15, user can only upload 15 characters-name file which includes the extension, like mickymouse.jpg, else if more than this number, display a warning message.

I have no idea how do I do this in JavaScript. Thanks for your help, much appreciated.

答:
You can use the File.name web API for this.

To accomplish this, you'll want to add an onchange event to your input field, and then create a javascript function to capture the event. In that function, you'll access the selected file's name and perform the validation. For example:

```<code><input
    type="file" name="userfile" id="userfile"
    accept="image/jpeg, application/pdf"
    onchange="validateFile(this)"
/>

<script>
    function validateFile(fileInput) {
        var files = fileInput.files;
        if (files.length === 0) {
            return;
        }

        var fileName = files[0].name;
        if (fileName.length > 15) {
            alert('File input name to long.');
        }
    }
</script>
</code>```

It's worth noting, for security reasons, you should not store the file with the name the user supplies. It's safe to store it in a database and used as a label when showing users (pending you sanitize it first) - but the file path you save on your server should be 100% controlled by you.

Body:
I have searched in the previous question, but most of the answer is only trim the file name. But for me, I would like to display an alert message to user when their filename length exceeds certain number.

Let say I have an file upload input box:

<input type="file" name="userfile" id="userfile" accept="image/jpeg, application/pdf">

When user uploads a file, a function will detect or calculate the length of the filename. If I limit the length to 15, user can only upload 15 characters-name file which includes the extension, like mickymouse.jpg, else if more than this number, display a warning message.

I have no idea how do I do this in JavaScript. Thanks for your help, much appreciated.

Body:
You can use the File.name web API for this.

To accomplish this, you'll want to add an onchange event to your input field, and then create a javascript function to capture the event. In that function, you'll access the selected file's name and perform the validation. For example:

<input
    type="file" name="userfile" id="userfile"
    accept="image/jpeg, application/pdf"
    onchange="validateFile(this)"
/>

<script>
    function validateFile(fileInput) {
        var files = fileInput.files;
        if (files.length === 0) {
            return;
        }

        var fileName = files[0].name;
        if (fileName.length > 15) {
            alert('File input name to long.');
        }
    }
</script>

It's worth noting, for security reasons, you should not store the file with the name the user supplies. It's safe to store it in a database and used as a label when showing users (pending you sanitize it first) - but the file path you save on your server should be 100% controlled by you.


来源: stackexchange

问:
Infinite loop for tag-it wrapped into a knockout component
I created a knockout custom binding to wrap tag-it based on the proposal of Droyad. The final code (simplified) is:

```<code>ko.bindingHandlers.tagit = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var bind = function () {
            valueAccessor().tagsList($(element).tagit("assignedTags"));
        };

        var options = $.extend({
            afterTagAdded: bind,
            afterTagRemoved: bind
        }, valueAccessor().options || {});

        // Create tags editor
        $(element).tagit(options);

        ////// Block 1
        var value = ko.utils.unwrapObservable(valueAccessor());
        var tags = value.tagsList();
        for(var x = 0; x < tags.length; x++) {
            $(element).tagit("createTag", tags[x]);
        }
        ////// End Block 1
    },
    ////// Block 2
    update: function (element, valueAccessor, allBindingsAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        var tags = value.tagsList();
        $(element).tagit("removeAll");
        for(var x = 0; x < tags.length; x++) {
            $(element).tagit("createTag", tags[x]);
        }
    }
    ////// End Block 2
};
</code>```

The corresponding HTML is:

```<code><div data-bind="with: currentDocument">
  <input data-bind="tagit: {tagsList: tags}"></input>
</div>
</code>```

My problem: I have to use "Block 1" and remove "Block 2" otherwise the component enter an infinite loop.
Without block 2, tag-it displays the tags every time I change document (currentDocument changes) and I can edit manually the tags without problems. Instead, if I change currentDocument.tags programmatically, the change is not visualized (obviously).
If I remove block 1 and add block 2, the afterTagAdded callback fires for every added tag, that in turn change the tags array, that fires the update function and so forth.

Any idea on how solve the problem? I think if the afterTagAdded and afterTagRemoved callbacks fire only for manual modifications and not for $(element).tagit("createTag", tags[x]); the problem could be solved.
Thanks for your help!

答:
The solution is simple albeit not elegant. I defined a "loading" variable that is set to true when the change is caused by loading the tags editor. When true blocks the observable update. (In the previous code remove block 1 and add block 2).

Trying to explain the problem on SO, as usual, help me to find a solution. Thanks also for this!

```<code>ko.bindingHandlers.tagit = {
    loading: false,
    init: function (element, valueAccessor, allBindingsAccessor) {
        var bind = function () {
            if(ko.bindingHandlers.tagit.loading) return;
            valueAccessor().tagsList($(element).tagit("assignedTags"));
        };
        ...
    },
    update: function (element, valueAccessor, allBindingsAccessor) {
        // Load data
        ko.bindingHandlers.tagit.loading = true;
        var value = ko.utils.unwrapObservable(valueAccessor());
        var tags = value.tagsList();
        $(element).tagit("removeAll");
        for(var x = 0; x < tags.length; x++) {
            $(element).tagit("createTag", tags[x]);
        }
        ko.bindingHandlers.tagit.loading = false;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I created a knockout custom binding to wrap tag-it based on the proposal of Droyad. The final code (simplified) is:

ko.bindingHandlers.tagit = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var bind = function () {
            valueAccessor().tagsList($(element).tagit("assignedTags"));
        };

        var options = $.extend({
            afterTagAdded: bind,
            afterTagRemoved: bind
        }, valueAccessor().options || {});

        // Create tags editor
        $(element).tagit(options);

        ////// Block 1
        var value = ko.utils.unwrapObservable(valueAccessor());
        var tags = value.tagsList();
        for(var x = 0; x < tags.length; x++) {
            $(element).tagit("createTag", tags[x]);
        }
        ////// End Block 1
    },
    ////// Block 2
    update: function (element, valueAccessor, allBindingsAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        var tags = value.tagsList();
        $(element).tagit("removeAll");
        for(var x = 0; x < tags.length; x++) {
            $(element).tagit("createTag", tags[x]);
        }
    }
    ////// End Block 2
};

The corresponding HTML is:

  <input data-bind="tagit: {tagsList: tags}"></input>

My problem: I have to use "Block 1" and remove "Block 2" otherwise the component enter an infinite loop.
Without block 2, tag-it displays the tags every time I change document (currentDocument changes) and I can edit manually the tags without problems. Instead, if I change currentDocument.tags programmatically, the change is not visualized (obviously).
If I remove block 1 and add block 2, the afterTagAdded callback fires for every added tag, that in turn change the tags array, that fires the update function and so forth.

Any idea on how solve the problem? I think if the afterTagAdded and afterTagRemoved callbacks fire only for manual modifications and not for $(element).tagit("createTag", tags[x]); the problem could be solved.
Thanks for your help!

Body:
The solution is simple albeit not elegant. I defined a "loading" variable that is set to true when the change is caused by loading the tags editor. When true blocks the observable update. (In the previous code remove block 1 and add block 2).

Trying to explain the problem on SO, as usual, help me to find a solution. Thanks also for this!

ko.bindingHandlers.tagit = {
    loading: false,
    init: function (element, valueAccessor, allBindingsAccessor) {
        var bind = function () {
            if(ko.bindingHandlers.tagit.loading) return;
            valueAccessor().tagsList($(element).tagit("assignedTags"));
        };
        ...
    },
    update: function (element, valueAccessor, allBindingsAccessor) {
        // Load data
        ko.bindingHandlers.tagit.loading = true;
        var value = ko.utils.unwrapObservable(valueAccessor());
        var tags = value.tagsList();
        $(element).tagit("removeAll");
        for(var x = 0; x < tags.length; x++) {
            $(element).tagit("createTag", tags[x]);
        }
        ko.bindingHandlers.tagit.loading = false;
    }


问:
How To setfocus on spinner?
I have spinner and edittext, and i want if spinner is selected can setfocus in edittext. I am already try, but not going to work, how to fix this?

This is my code :

```<code>edkontak1.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId== EditorInfo.IME_ACTION_NEXT) {
                    sembunyikanKeyboard();
                    v.clearFocus();
                    spinnerkontak1.requestFocus();
                    spinnerkontak1.performClick();
                }
                return true;
            }
        });

 spinnerkontak1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String jeniskontak1 = spinnerkontak1.getSelectedItem().toString();
                if(jeniskontak1.equals("--")){
                    edkontak1.setText("");
                    edkontak1.setEnabled(false);
                    tkontak2.setVisibility(View.GONE);
                    tkontak3.setVisibility(View.GONE);
                    tkontak4.setVisibility(View.GONE);
                    tkontak5.setVisibility(View.GONE);
                }
                else{
                    edkontak1.setEnabled(true);
                    tkontak2.setVisibility(View.VISIBLE);
                    spinnerkontak1.setFocusable(true);
                    spinnerkontak1.setFocusableInTouchMode(true);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

private void sembunyikanKeyboard() {
        InputMethodManager inputmanaget = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        inputmanaget.hideSoftInputFromInputMethod(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
</code>```

Thanks in advance.

答:
What you have done is correct. But you have to add this line too.</p>

```<code>spinnerkontak1.setFocusable(true);
</code>```

Title: How To setfocus on spinner?

Body:
I have spinner and edittext, and i want if spinner is selected can setfocus in edittext. I am already try, but not going to work, how to fix this?

This is my code :

edkontak1.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId== EditorInfo.IME_ACTION_NEXT) {
                    sembunyikanKeyboard();
                    v.clearFocus();
                    spinnerkontak1.requestFocus();
                    spinnerkontak1.performClick();
                }
                return true;
            }
        });

 spinnerkontak1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String jeniskontak1 = spinnerkontak1.getSelectedItem().toString();
                if(jeniskontak1.equals("--")){
                    edkontak1.setText("");
                    edkontak1.setEnabled(false);
                    tkontak2.setVisibility(View.GONE);
                    tkontak3.setVisibility(View.GONE);
                    tkontak4.setVisibility(View.GONE);
                    tkontak5.setVisibility(View.GONE);
                }
                else{
                    edkontak1.setEnabled(true);
                    tkontak2.setVisibility(View.VISIBLE);
                    spinnerkontak1.setFocusable(true);
                    spinnerkontak1.setFocusableInTouchMode(true);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

private void sembunyikanKeyboard() {
        InputMethodManager inputmanaget = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        inputmanaget.hideSoftInputFromInputMethod(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

Thanks in advance.

Body:
What you have done is correct. But you have to add this line too.

spinnerkontak1.setFocusable(true);


问:
Many to many dimension table Library Database
I need to find which category of books were the most borrowed. So, I have the following UML diagram.

So when making the dimension tables and fact table I've come up up with the following:

But the Auth (dimension)association table doesn't seem right. Is there a mistake and how can I correct it?
Edit: Probably Category and Publisher dimension tables shouldn't be there. They should be attached with book.

答:
your dimensional model needs to be redesigned.

Fact table must be "Auth" with the following fields:

Staff_ID

Student_ID

Book_ID

Issued_Date

Borrowed_Till

Then you need 4 dimension tables:

Staff (contains Staff key, Staff attributes, Library attributes)

Student (Student key, Student attributes)

Book (Book key, Book attributes, Publisher, Category)

Calendar (Date key, calendar attributes)
you might need a second Calendar for Borrowed_Till.


问:
how to compile spring-boot-maven-plugin without dependencies?
I am trying to do an excercise with micro-services in Java with Spring boot, for this I am developing two web services in different projects with the intention of deploying them in tomcat like two independent files (.war).

I have read about set up tomcat to have the dependencies in an specified folder to share it with other services and this way not to increase the same libraries in all services.

The ploblem is that when I compiled the service with maven through the artifact spring-boot-maven-plugin the .war files always has the dependencies inside. Because of I want to know if someone know how to configure maven to
remove dependencies from .war file..... in Spring Boot.

The .war follows with the dependencies inside, Edited:
I have added the provided like said Michael Potter and the execution. it works fine.  My pom.xml is the follow:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>demo1</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
              <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
              <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                    <configuration>
                        <skip>true</skip>
                    </configuration>
                </execution>
            </executions>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

答:
For Maven not to include dependency in your WAR file you need to specify its scope to provided. The description of the scope from official Maven documentation:

This is much like compile, but indicates you expect the JDK or a
  container to provide the dependency at runtime. For example, when
  building a web application for the Java Enterprise Edition, you would
  set the dependency on the Servlet API and related Java EE APIs to
  scope provided because the web container provides those classes. This
  scope is only available on the compilation and test classpath, and is
  not transitive.

```<code><dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.192</version>
    <scope>provided</scope>
</dependency>
</code>```

The dependency will be downloaded to compile the sources, but not packed in the WAR.

Concerning spring-boot-maven-plugin. By default it makes repackaging of a WAR that allows you to launch it from console. Thus, it packages all required dependencies to the archive - even with the provided scope. You can see in your target directory two files: {project-name}.war which is repackaged and {project-name}.war.original - the one that should not contain provided dependencies. To disable repackaging you should change spring-boot-maven-plugin configuration to the following:

```<code><plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
            <configuration>
                <skip>true</skip>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

Then you need to place the required dependency to tomcat/lib folder and restart the Tomcat.

Body:
I am trying to do an excercise with micro-services in Java with Spring boot, for this I am developing two web services in different projects with the intention of deploying them in tomcat like two independent files (.war).

I have read about set up tomcat to have the dependencies in an specified folder to share it with other services and this way not to increase the same libraries in all services.

The ploblem is that when I compiled the service with maven through the artifact spring-boot-maven-plugin the .war files always has the dependencies inside. Because of I want to know if someone know how to configure maven to
remove dependencies from .war file..... in Spring Boot.

The .war follows with the dependencies inside, Edited:
I have added the provided like said Michael Potter and the execution. it works fine.  My pom.xml is the follow:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>demo1</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
              <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
              <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                    <configuration>
                        <skip>true</skip>
                    </configuration>
                </execution>
            </executions>
            </plugin>
        </plugins>
    </build>

</project>

Body:
For Maven not to include dependency in your WAR file you need to specify its scope to provided. The description of the scope from official Maven documentation:

This is much like compile, but indicates you expect the JDK or a
  container to provide the dependency at runtime. For example, when
  building a web application for the Java Enterprise Edition, you would
  set the dependency on the Servlet API and related Java EE APIs to
  scope provided because the web container provides those classes. This
  scope is only available on the compilation and test classpath, and is
  not transitive.

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.192</version>
    <scope>provided</scope>
</dependency>

The dependency will be downloaded to compile the sources, but not packed in the WAR.

Concerning spring-boot-maven-plugin. By default it makes repackaging of a WAR that allows you to launch it from console. Thus, it packages all required dependencies to the archive - even with the provided scope. You can see in your target directory two files: {project-name}.war which is repackaged and {project-name}.war.original - the one that should not contain provided dependencies. To disable repackaging you should change spring-boot-maven-plugin configuration to the following:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
            <configuration>
                <skip>true</skip>
            </configuration>
        </execution>
    </executions>
</plugin>

Then you need to place the required dependency to tomcat/lib folder and restart the Tomcat.


问:
In C++, is it possible to use a string literal as a macro name?
Here's my scenario: I have a set of source files that I'd prefer to not modify, but I'd like to replace some of the string literals with other values.  Here's an example:</p>

```<code>#define "oldString" "newString"
</code>```

答: No, that's not possible. If you had already used macros in place of the strings, it would have been simple to change the macro definition to use a different string -- better late than never, you might want to do it now.</p>

Body:
Here's my scenario: I have a set of source files that I'd prefer to not modify, but I'd like to replace some of the string literals with other values.  Here's an example:

#define "oldString" "newString"

ContentLicense: CC BY-SA 2.5


问:
How to use the visual composer attach_images as in a shortcode
I am trying to create a custom image slider using visual composers attach_images but cant quite work out how to get the URLs from the array of image IDs.
Any help would be appreciated.

var_dump($bg_images) returns
string(9) "19,6,1692"

```<code>vc_map( array(
     "name" => __( "Fading Background Block", "farrat_vc" ),
     "base" => "block_background",
     "class" => "",
     "category" => __( "Farrat Shortcodes", "farrat_vc"),
     "as_parent" => array('except' => 'farrat_panel'), // Use only|except attributes to limit child shortcodes (separate multiple values with comma)
     "content_element" => true,
     "show_settings_on_create" => true,
     "is_container" => true,
     'admin_enqueue_css' => array(get_template_directory_uri().'/wp-content/themes/unite/inc/css/gallery.css'),
     "params" => array(
            array(
                 "type" => "attach_images",
                 "heading" => __( "Backgroud Images", "farrat_vc" ),
                 "param_name" => "bg_images",
            ),
        ),
  "js_view" => 'VcColumnView'
) );
</code>```

答:
// Hi try this one this is perfectly working  </p>

```<code>//Param Registration

  function designas_partners() {
    // Title
    vc_map(
        array(
            'name' => __( 'Clients' ),
            'base' => 'designas_partners_content',
            'category' => __( 'Easy Component' ),
            'params' => array(

                array(
                "type"        => "attach_images",
                "heading"     => esc_html__( "Add Clients Images", "appcastle-core" ),
                "description" => esc_html__( "Add Clients Images", "appcastle-core" ),
                "param_name"  => "screenshots",
                "value"       => "",
                ),

            )
        )
    );
    }

add_action( 'vc_before_init', 'designas_partners' );
</code>```

<p>// Short code</p>

```<code>function designas_partners_content_function( $atts, $content ) {
$gallery = shortcode_atts(
    array(
        'screenshots'      =>  'screenshots',
    ), $atts );

 $image_ids = explode(',',$gallery['screenshots']);
 $return = '
    <div class="clients">';
    foreach( $image_ids as $image_id ){
    $images = wp_get_attachment_image_src( $image_id, 'company_logo' );
    $return .='<div class="images"><img src="'.$images[0].'" alt="'.$atts['title'].'"></div>';
    $images++;
    }
    $return .='</div>';
return $return;
}
add_shortcode( 'designas_partners_content', 'designas_partners_content_function' )
</code>```

Body:
I am trying to create a custom image slider using visual composers attach_images but cant quite work out how to get the URLs from the array of image IDs.
Any help would be appreciated.

var_dump($bg_images) returns
string(9) "19,6,1692"

vc_map( array(
     "name" => __( "Fading Background Block", "farrat_vc" ),
     "base" => "block_background",
     "class" => "",
     "category" => __( "Farrat Shortcodes", "farrat_vc"),
     "as_parent" => array('except' => 'farrat_panel'), // Use only|except attributes to limit child shortcodes (separate multiple values with comma)
     "content_element" => true,
     "show_settings_on_create" => true,
     "is_container" => true,
     'admin_enqueue_css' => array(get_template_directory_uri().'/wp-content/themes/unite/inc/css/gallery.css'),
     "params" => array(
            array(
                 "type" => "attach_images",
                 "heading" => __( "Backgroud Images", "farrat_vc" ),
                 "param_name" => "bg_images",
            ),
        ),
  "js_view" => 'VcColumnView'
) );

Body:
// Hi try this one this is perfectly working

//Param Registration

  function designas_partners() {
    // Title
    vc_map(
        array(
            'name' => __( 'Clients' ),
            'base' => 'designas_partners_content',
            'category' => __( 'Easy Component' ),
            'params' => array(

                array(
                "type"        => "attach_images",
                "heading"     => esc_html__( "Add Clients Images", "appcastle-core" ),
                "description" => esc_html__( "Add Clients Images", "appcastle-core" ),
                "param_name"  => "screenshots",
                "value"       => "",
                ),

            )
        )
    );
    }

add_action( 'vc_before_init', 'designas_partners' );

// Short code

function designas_partners_content_function( $atts, $content ) {
$gallery = shortcode_atts(
    array(
        'screenshots'      =>  'screenshots',
    ), $atts );

 $image_ids = explode(',',$gallery['screenshots']);
 $return = '
    <div class="clients">';
    foreach( $image_ids as $image_id ){
    $images = wp_get_attachment_image_src( $image_id, 'company_logo' );
    $return .='<div class="images"><img src="'.$images[0].'" alt="'.$atts['title'].'"></div>';
    $images++;
    }
    $return .='</div>';
return $return;
}
add_shortcode( 'designas_partners_content', 'designas_partners_content_function' )


问:
Adding and removing classes depending on window size
I am trying to add and remove classes depending on the window size and resizing:

```<code>var windoSizing = function() {
    var $toggleClass;
    var $window = $(window);
    var $iconsContainer = $('.fragments-content > .icons-container');
    $toggleClass = ($window.width() > 769) ? $iconsContainer.addClass('mob-only') : $iconsContainer.removeClass('mob-only');
    $window.resize(function(event) {
        $toggleClass = ($window.width() > 769) ? $iconsContainer.addClass('mob-only') : $iconsContainer.removeClass('mob-only');
    });
};
</code>```

Do you think is there a better way to do it?

答:
Use CSS media queries to set styles for different screen sizes instead of JS.

```<code><style>
  .icons-container { /** general styles */ }

  @media(max-width: 769px) {
    .icons-container { /** mobile styles */ }
  }
</style>
</code>```

Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

Body:
I am trying to add and remove classes depending on the window size and resizing:

var windoSizing = function() {
    var $toggleClass;
    var $window = $(window);
    var $iconsContainer = $('.fragments-content > .icons-container');
    $toggleClass = ($window.width() > 769) ? $iconsContainer.addClass('mob-only') : $iconsContainer.removeClass('mob-only');
    $window.resize(function(event) {
        $toggleClass = ($window.width() > 769) ? $iconsContainer.addClass('mob-only') : $iconsContainer.removeClass('mob-only');
    });
};

Do you think is there a better way to do it?

Body:
Use CSS media queries to set styles for different screen sizes instead of JS.

<style>
  .icons-container { /** general styles */ }

  @media(max-width: 769px) {
    .icons-container { /** mobile styles */ }
  }
</style>

Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries


问:
iOS - Load cells one by one
I want to load the cell of a collection view one by one using the API collectionView.insertItems(at:). There are many answers online which accomplish this by animating the alpha of the cell inside of willDisplayCell and other methods, for example here - link. However, nothing works perfectly. The reason for using collectionView.insertItems(at:) is that the animation is already built in and no hacks needed.

However using collectionView.insertItems(at:), I get error such as:

*** Terminating app due to uncaught exception  'NSInternalInconsistencyException', reason: 'Invalid update: invalid
  number of items in section 0.  The number of items contained in an
  existing section after the update (5) must be equal to the number of
  items contained in that section before the update (5), plus or minus
  the number of items inserted or deleted from that section (1 inserted,
  0 deleted) and plus or minus the number of items moved into or out of
  that section (0 moved in, 0 moved out).

This is an example of what I have, it's crashing as shown above, but it's a start I think in the right direction (hopefully):

```<code>class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!

    /// This array is populated from a network call.
    let images = [Image]()

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        animateCells()
    }

    func animateCells() {
        let indexPaths = [IndexPath(item: 0, section: 0),
                          IndexPath(item: 1, section: 0),
                          IndexPath(item: 2, section: 0),
                          IndexPath(item: 3, section: 0),
                          IndexPath(item: 4, section: 0)]

        for indexPath in indexPaths {
            let delayTime = 0.1 + Double(indexPath.row) * 0.3

            delay(delayTime) {
                self.collectionView.performBatchUpdates({
                    self.collectionView.insertItems(at: [indexPath])
                }, completion: nil)
            }
        }
    }

    func delay(_ delay: TimeInterval, closure: @escaping () -> Void) {
        let when = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
    }
}

// MARK: - UICollectionViewDataSource

extension ViewController: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)

        return cell
    }
}
</code>```

One of the main problems I see is that I do return images.count inside of numberOfItemsInSection.

Any thoughts?

答:
Did you try to append element to imageswith delay too?

```<code>var images = Array(repeating: 0, count: 0)

delay(delayTime) {
     self.collectionView.performBatchUpdates({
                self.images.append(0)
                self.collectionView.insertItems(at: [indexPath])
     }, completion: nil)
}
</code>```

Title: iOS - Load cells one by one

Body:
I want to load the cell of a collection view one by one using the API collectionView.insertItems(at:). There are many answers online which accomplish this by animating the alpha of the cell inside of willDisplayCell and other methods, for example here - link. However, nothing works perfectly. The reason for using collectionView.insertItems(at:) is that the animation is already built in and no hacks needed.

However using collectionView.insertItems(at:), I get error such as:

*** Terminating app due to uncaught exception  'NSInternalInconsistencyException', reason: 'Invalid update: invalid
  number of items in section 0.  The number of items contained in an
  existing section after the update (5) must be equal to the number of
  items contained in that section before the update (5), plus or minus
  the number of items inserted or deleted from that section (1 inserted,
  0 deleted) and plus or minus the number of items moved into or out of
  that section (0 moved in, 0 moved out).

This is an example of what I have, it's crashing as shown above, but it's a start I think in the right direction (hopefully):

class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!

    /// This array is populated from a network call.
    let images = [Image]()

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        animateCells()
    }

    func animateCells() {
        let indexPaths = [IndexPath(item: 0, section: 0),
                          IndexPath(item: 1, section: 0),
                          IndexPath(item: 2, section: 0),
                          IndexPath(item: 3, section: 0),
                          IndexPath(item: 4, section: 0)]

        for indexPath in indexPaths {
            let delayTime = 0.1 + Double(indexPath.row) * 0.3

            delay(delayTime) {
                self.collectionView.performBatchUpdates({
                    self.collectionView.insertItems(at: [indexPath])
                }, completion: nil)
            }
        }
    }

    func delay(_ delay: TimeInterval, closure: @escaping () -> Void) {
        let when = DispatchTime.now() + delay
        DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
    }
}

// MARK: - UICollectionViewDataSource

extension ViewController: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)

        return cell
    }
}

One of the main problems I see is that I do return images.count inside of numberOfItemsInSection.

Any thoughts?

Body:
Did you try to append element to imageswith delay too?

var images = Array(repeating: 0, count: 0)

delay(delayTime) {
     self.collectionView.performBatchUpdates({
                self.images.append(0)
                self.collectionView.insertItems(at: [indexPath])
     }, completion: nil)
}


问:
Python: call method of another class, specified as parameter of function
I know the simplified example below is embarrassingly ugly ... hence why I have come to SO to share it with the world.

I would like to be able to call a class method from cls, specifying the particular method within callmethod.

```<code>class cls(object):
    def __init__(self, var1):
        self.var1 = var1
    def method1(self):
        return self.var1 ** 2
    def method2(self):
        return self.var1 ** 3

def callmethod(method, var1):
    methods = {'method1' : cls(var1).method1(),
               'method2' : cls(var1).method2()
              }
    return methods[method]

callmethod('method1', 2)
Out[56]: 4
</code>```

Is there a way to go about this without creating a (possibly large and cumbersome) dict that links a string form of each method to the actual thing?

答:
What you're looking for is likely just:

```<code>def callmethod(method, arg)
    inst = cls(arg)
    return getattr(inst, method)()
</code>```

You can think of a.b as a syntax sugar for getattr(a, "b")

Body:
I know the simplified example below is embarrassingly ugly ... hence why I have come to SO to share it with the world.

I would like to be able to call a class method from cls, specifying the particular method within callmethod.

class cls(object):
    def __init__(self, var1):
        self.var1 = var1
    def method1(self):
        return self.var1 ** 2
    def method2(self):
        return self.var1 ** 3

def callmethod(method, var1):
    methods = {'method1' : cls(var1).method1(),
               'method2' : cls(var1).method2()
              }
    return methods[method]

callmethod('method1', 2)
Out[56]: 4

Is there a way to go about this without creating a (possibly large and cumbersome) dict that links a string form of each method to the actual thing?

Body:
What you're looking for is likely just:

def callmethod(method, arg)
    inst = cls(arg)
    return getattr(inst, method)()

You can think of a.b as a syntax sugar for getattr(a, "b")


问:
What is a fractal?
Duplicate of How to program a fractal

What are fractals?

Is this is one of the concepts that is brought over from Mathematics to programming to simplify or solve a particular set of problems?

 I am closing this question and have posted a related  question

答:
its a type of self-similar shape, often grounded in a repeated mathematical function (but not necessarily). It has nothing to do with programming technique, but the easiest way to view one is to write a program to draw it. (drawing a fractal with pen-and-paper is pretty time-consuming)

By 'self-similar' i mean, if you keep zooming in on different parts of the fractal, it doesn't get any "smoother" or more linear, as would happen with a non-fractal shape. It's degree of complexity is invariant of the zoom level.

the Wikipedia page is pretty useful

OwnerDisplayName: Nick

Title: What is a fractal?

LastEditorDisplayName: Nick

OwnerDisplayName: Jimmy


问:
Best way of adding SNMP support to your own application on Debian
I am working on Debian and I have this server we want to monitor.

The application is ours and there are around a hundred real-time counters we want to export for monitoring purposes, graphs and alarms.

I've been looking at the Debian way of doing this because we do use Debian packaging to install the app, and Debian uses snmpd daemon, based on net-snmp, to export SNMP.
So far every approach I've seen looks very complicated, from recompiling snmpd to load a dynamic library into it, and compiling a form of subagent that replicates what snmpd does.

While all of those options make me think I should go for something else than SNMP I don't want to give up that early and I was wondering if anybody has found a feasible implementation.

Ideally it should be coded in C or C++ as the app is in C++, but I'm open to wrappers or other kind of suggestions.

答: The traditional way to do this in linux is to use the net-snmp package. Make sure you write the MIB first. Everything is based on the MIB and changes to the MIB usually results in lots of changes in the code. Coding for net-snmp is not difficult and there is lots of documentation to get you started, eg: http://www.net-snmp.org/wiki/index.php/Tutorials#Coding_Tutorials</p>


问:
Replace get parameters in Codeigniter pagination?
The following piece of code for my pagination function like following:-

```<code>public function news()
    {
        $this->load->library('pagination');
        $config = array();

        $config["base_url"] = base_url() . "index.php/welcome/news";
        $this->load->model('news_model');
        $total_row = $this->news_model->record_count();
        $config["total_rows"] = $total_row;
        $config["per_page"] = 1;
        $config['use_page_numbers'] = TRUE;
        $config['num_links'] = $total_row;
        $config['cur_tag_open'] = ' <a class="current">';
        $config['cur_tag_close'] = '</a>';

        $config['page_query_string'] = TRUE;
        $config['next_link'] = 'Next';
        $config['prev_link'] = 'Previous';
        $config['first_url'] = $config['base_url'].'?'.http_build_query($_GET);
        $this->pagination->initialize($config);
        if($this->uri->segment(3)){
        $page = ($this->uri->segment(3)) ;
        }
        else{
        $page = 1;
        } //echo $config["per_page"].'/'.$page; exit();
        $this->load->model('news_model');
        $data["results"] = $this->news_model->fetch_data($config["per_page"], $page);
        $str_links = $this->pagination->create_links();
        $data["links"] = explode(' ',$str_links );

        $this->load->model('news_model');
        $data['lt_news'] = $this->news_model->get_lt_newsletter();
        $data['rm_news'] = $this->news_model->get_rm_newsletter();
        $this->load->view('newsletter/newsletter',$data);
    }
</code>```

From the above code, the url browser shows like the following:-

```<code>http://localhost/ins/index.php/welcome/news?per_page=2
</code>```

I am like jammed as to how to change it to be look like the following:

```<code>http://localhost/ins/index.php/welcome/news/2
</code>```

Is there a way to do it..?  I am newbie to the pagination in codeigniter so, i do not know if there is a necessity to change the url parameters to be looking like the above..?

答:
Set $config['page_query_string'] to false.

From the doc https://www.codeigniter.com/userguide3/libraries/pagination.html#customizing-the-pagination:

By default, the pagination library assume you are using URI Segments,
  and constructs your links something like:

http://example.com/index.php/test/page/20 If you have
  $config['enable_query_strings'] set to TRUE your links will
  automatically be re-written using Query Strings. This option can also
  be explicitly set. Using $config['page_query_string'] set to TRUE, the
  pagination link will become:

http://example.com/index.php?c=test&m=page&per_page=20

ContentLicense: CC BY-SA 4.0

Body:
The following piece of code for my pagination function like following:-

public function news()
    {
        $this->load->library('pagination');
        $config = array();

        $config["base_url"] = base_url() . "index.php/welcome/news";
        $this->load->model('news_model');
        $total_row = $this->news_model->record_count();
        $config["total_rows"] = $total_row;
        $config["per_page"] = 1;
        $config['use_page_numbers'] = TRUE;
        $config['num_links'] = $total_row;
        $config['cur_tag_open'] = ' ';
        $config['cur_tag_close'] = '';

        $config['page_query_string'] = TRUE;
        $config['next_link'] = 'Next';
        $config['prev_link'] = 'Previous';
        $config['first_url'] = $config['base_url'].'?'.http_build_query($_GET);
        $this->pagination->initialize($config);
        if($this->uri->segment(3)){
        $page = ($this->uri->segment(3)) ;
        }
        else{
        $page = 1;
        } //echo $config["per_page"].'/'.$page; exit();
        $this->load->model('news_model');
        $data["results"] = $this->news_model->fetch_data($config["per_page"], $page);
        $str_links = $this->pagination->create_links();
        $data["links"] = explode(' ',$str_links );

        $this->load->model('news_model');
        $data['lt_news'] = $this->news_model->get_lt_newsletter();
        $data['rm_news'] = $this->news_model->get_rm_newsletter();
        $this->load->view('newsletter/newsletter',$data);
    }

From the above code, the url browser shows like the following:-

http://localhost/ins/index.php/welcome/news?per_page=2

I am like jammed as to how to change it to be look like the following:

http://localhost/ins/index.php/welcome/news/2

Is there a way to do it..?  I am newbie to the pagination in codeigniter so, i do not know if there is a necessity to change the url parameters to be looking like the above..?


问:
How to inject dbcontext with StructureMap and WebApi2
I would like to inject my dbcontext into my services in web api 2 project.  But I’m a little unsure of how to do that.  I've read through the docs but lifecycles, scopes, requests, nested containers...they all leave me a little unsure.  I have pieced together the following code from my best understanding.  After installing the Nuget package StructureMap.WebApi2, I proceeded to update SM from v3 to v4, as well as the SM.MVC5 from v3 to v4.

The following code appears to have the desired effect of using one dbcontext per http request (I think that's what i want...i'm so confused about scopes) so that the same dbcontext is shared for all services during a users transaction, and then disposed when the transaction (http request) is closed. But appearances are not always right.

IoC.cs

```<code>    public static IContainer Initialize()
    {
        var container = new Container(_ =>
        {
            _.AddRegistry<DefaultRegistry>();
            _.ForConcreteType<MyDbContext>().Configure.ContainerScoped();
        });
        DomainEvents.Initialize(container);
        return container;
    }}
</code>```

DefaultRegistry.cs:

```<code>    public DefaultRegistry()
    {
        var mapperConfig = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile(new Common.Map.MapProfile());
            cfg.CreateMissingTypeMaps = true;
        });
        var mapper = mapperConfig.CreateMapper();
        For<IMapper>().Use(() => mapperConfig.CreateMapper());
        For<MyDbContext>().Use(()=> new MyDbContext());

        Scan(
            scan =>
            {
                scan.AssemblyContainingType<ServiceBase>();
                scan.TheCallingAssembly();
                scan.WithDefaultConventions();
                scan.ConnectImplementationsToTypesClosing(typeof(IHandle<>));
            });
    }
</code>```

The Nuget package StructureMap.WebApi2 created some other files for wiring up resolution and nested containers, but i'm leaving them out of this question for the sake of brevity.

答:
Have a look at the Mehdime DbContext Scope Factory / Locator: https://github.com/mehdime/DbContextScope and he has a bit of a run-down of it on his blog. (link in the project description.) There are forks off there updated to the latest EF versions.

I've found it to be an excellent unit of work wrapper for EF contexts without having to worry about injecting or passing around those contexts directly.

The trouble with IoC containers and constructor injection is that if you register your DBContext it means that it's hard to work with things like a unit of work within the scope of a request without it essentially being the entire scope of the request. The DbContext Scope solves this by having you register a Scope Factory and a Scope Locator in your Container. Code controlling the Scope (unit of work) will use the Scope Factory to initialize a context scope for your DbContexts.   Code operating with DbSets etc. in a DbContext use the ContextScopeLocator to get their UoW /w it's DbContext & sets.

Body:
I would like to inject my dbcontext into my services in web api 2 project.  But I’m a little unsure of how to do that.  I've read through the docs but lifecycles, scopes, requests, nested containers...they all leave me a little unsure.  I have pieced together the following code from my best understanding.  After installing the Nuget package StructureMap.WebApi2, I proceeded to update SM from v3 to v4, as well as the SM.MVC5 from v3 to v4.

The following code appears to have the desired effect of using one dbcontext per http request (I think that's what i want...i'm so confused about scopes) so that the same dbcontext is shared for all services during a users transaction, and then disposed when the transaction (http request) is closed. But appearances are not always right.

IoC.cs

    public static IContainer Initialize()
    {
        var container = new Container(_ =>
        {
            _.AddRegistry<DefaultRegistry>();
            _.ForConcreteType<MyDbContext>().Configure.ContainerScoped();
        });
        DomainEvents.Initialize(container);
        return container;
    }}

DefaultRegistry.cs:

    public DefaultRegistry()
    {
        var mapperConfig = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile(new Common.Map.MapProfile());
            cfg.CreateMissingTypeMaps = true;
        });
        var mapper = mapperConfig.CreateMapper();
        For<IMapper>().Use(() => mapperConfig.CreateMapper());
        For<MyDbContext>().Use(()=> new MyDbContext());

        Scan(
            scan =>
            {
                scan.AssemblyContainingType<ServiceBase>();
                scan.TheCallingAssembly();
                scan.WithDefaultConventions();
                scan.ConnectImplementationsToTypesClosing(typeof(IHandle<>));
            });
    }

The Nuget package StructureMap.WebApi2 created some other files for wiring up resolution and nested containers, but i'm leaving them out of this question for the sake of brevity.


问:
Fill select list in form with values from database + Symfony 2 & Doctrine
I want to create a form with to begin only a select list wtih values selected from a database.

This is the entity Region and I would like to fill the dropdown with regions.

```<code><?php

namespace Reuzze\ReuzzeBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Regions
 *
 * @ORM\Table(name="regions")
 * @ORM\Entity
*/
class Regions
{
    /**
     * @var integer
     *
     * @ORM\Column(name="region_id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $regionId;

    /**
     * @var string
     *
     * @ORM\Column(name="region_name", type="string", length=45, nullable=false)
     */
     protected $regionName;

    /**
     * Get regionId
     *
     * @return integer
     */
    public function getRegionId()
    {
        return $this->regionId;
    }

    /**
     * Set regionName
     *
     * @param string $regionName
     * @return Regions
     */
    public function setRegionName($regionName)
    {
        $this->regionName = $regionName;

        return $this;
    }

    /**
     * Get regionName
     *
     * @return string
     */
    public function getRegionName()
    {
        return $this->regionName;
    }
}
</code>```

This is my form:

```<code>class RegionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('regionName'   , 'text', array(
            'label' => 'Region Name',
            'attr' => array('placeholder' => 'Region Name')
        ));
    }

    public function getName()
    {
        return 'region';
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Reuzze\ReuzzeBundle\Entity\Regions',
        ));
    }

}
</code>```

But now I would like to show the regions in a select list instead of giving in the name in a textbox. Does anybody know how I can do this in my form? And how I show it in my view?

答:
Updated answer for Symfony 3+:

You now need to use the EntityType class and the choice_label option.

See docs here: http://symfony.com/doc/current/reference/forms/types/entity.html

```<code>use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Reuzze\ReuzzeBundle\Entity\Regions;

class RegionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add(
            'regionName',
            EntityType::class,
            [
                'class' => Regions::class,
                'choice_label' => 'regionName',
                'expanded' => false,
                'multiple' => false
            ]
        );

        $builder->setMethod('POST');

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

Body:
I want to create a form with to begin only a select list wtih values selected from a database.

This is the entity Region and I would like to fill the dropdown with regions.

<?php

namespace Reuzze\ReuzzeBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Regions
 *
 * @ORM\Table(name="regions")
 * @ORM\Entity
*/
class Regions
{
    /**
     * @var integer
     *
     * @ORM\Column(name="region_id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $regionId;

    /**
     * @var string
     *
     * @ORM\Column(name="region_name", type="string", length=45, nullable=false)
     */
     protected $regionName;

    /**
     * Get regionId
     *
     * @return integer
     */
    public function getRegionId()
    {
        return $this->regionId;
    }

    /**
     * Set regionName
     *
     * @param string $regionName
     * @return Regions
     */
    public function setRegionName($regionName)
    {
        $this->regionName = $regionName;

        return $this;
    }

    /**
     * Get regionName
     *
     * @return string
     */
    public function getRegionName()
    {
        return $this->regionName;
    }
}

This is my form:

class RegionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('regionName'   , 'text', array(
            'label' => 'Region Name',
            'attr' => array('placeholder' => 'Region Name')
        ));
    }

    public function getName()
    {
        return 'region';
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Reuzze\ReuzzeBundle\Entity\Regions',
        ));
    }

}

But now I would like to show the regions in a select list instead of giving in the name in a textbox. Does anybody know how I can do this in my form? And how I show it in my view?

Body:
Updated answer for Symfony 3+:

You now need to use the EntityType class and the choice_label option.

See docs here: http://symfony.com/doc/current/reference/forms/types/entity.html

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Reuzze\ReuzzeBundle\Entity\Regions;

class RegionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add(
            'regionName',
            EntityType::class,
            [
                'class' => Regions::class,
                'choice_label' => 'regionName',
                'expanded' => false,
                'multiple' => false
            ]
        );

        $builder->setMethod('POST');

        return $builder;
    }
}


答: No, #define allows you to give a value to an identifier.  Identifiers can't contain the quote character.

Title: In C++, is it possible to use a string literal as a macro name?


问:
The LDAP server is unavailable
I'm a total newbie to this

Trying to connect to an ldap server with PrincipalContext. I have tried all solutions on this site to no avail.

Things I've tried:

```<code>PrincipalContext insPrincipalContext =
   new PrincipalContext(ContextType.Domain);

PrincipalContext insPrincipalContext =
   new PrincipalContext(ContextType.Domain, "ldap://localhost:389/dc=maxcrc,dc=com");

PrincipalContext insPrincipalContext =
   new PrincipalContext(ContextType.Domain, "maxcrc.com");
</code>```

All give the same result:

LDAP server not available

Only ContextType.Machine works basically.

Not sure if my LDAP server is set up correctly:

Host: localhost

Port: 389

Base DN: dc=maxcrc,dc=com

URL: ldap://localhost:389/dc=maxcrc,dc=com

Testing with Softerra LDAP Browser

Any tutorials from start to finish will be much appreciated...

答:
In my environment I had to create the principal context with just the domain controller host name, and then separately validate the user credentials.

```<code>string domainControllerName = "PDC";
string domainName = "MyDomain"; // leave out the .Local, this is just to use as the prefix for the username if the user left it off or didn't use the principal address notation
string username = "TestUser";
string password = "password";

using (var ldap = new PrincipalContext(ContextType.Domain, domainControllerName))
{
    var usernameToValidate = username;
    if (!usernameToValidate.Any(c => c == '@' || c == '\\'))
            usernameToValidate = $"{domainName}\\{username}";

    if (!ldap.ValidateCredentials(username, context.Password, ContextOptions.SimpleBind))
        throw new UnauthorizedException();
}
</code>```

This example allows for all three of these variations to the username to validate:

TestUser

MyDomain\TestUser

TestUser@MyDomain.Local

Title: The LDAP server is unavailable

Body:
I'm a total newbie to this

Trying to connect to an ldap server with PrincipalContext. I have tried all solutions on this site to no avail.

Things I've tried:

PrincipalContext insPrincipalContext =
   new PrincipalContext(ContextType.Domain);

PrincipalContext insPrincipalContext =
   new PrincipalContext(ContextType.Domain, "ldap://localhost:389/dc=maxcrc,dc=com");

PrincipalContext insPrincipalContext =
   new PrincipalContext(ContextType.Domain, "maxcrc.com");

All give the same result:

LDAP server not available

Only ContextType.Machine works basically.

Not sure if my LDAP server is set up correctly:

Host: localhost

Port: 389

Base DN: dc=maxcrc,dc=com

URL: ldap://localhost:389/dc=maxcrc,dc=com

Testing with Softerra LDAP Browser

Any tutorials from start to finish will be much appreciated...

Body:
In my environment I had to create the principal context with just the domain controller host name, and then separately validate the user credentials.

string domainControllerName = "PDC";
string domainName = "MyDomain"; // leave out the .Local, this is just to use as the prefix for the username if the user left it off or didn't use the principal address notation
string username = "TestUser";
string password = "password";

using (var ldap = new PrincipalContext(ContextType.Domain, domainControllerName))
{
    var usernameToValidate = username;
    if (!usernameToValidate.Any(c => c == '@' || c == '\\'))
            usernameToValidate = $"{domainName}\\{username}";

    if (!ldap.ValidateCredentials(username, context.Password, ContextOptions.SimpleBind))
        throw new UnauthorizedException();
}

This example allows for all three of these variations to the username to validate:

TestUser

MyDomain\TestUser

TestUser@MyDomain.Local


问:
Maya Python: matching the bounding boxes of two different objects
I have two objects that will always have random different bounding box sizes, particularly heights. But both will have the pivot at the origin.

I want to match, via scaling, one objects bounding box height with the other's. But I can only think of gradually scaling the smaller one up by very small increments. That seems a little tedious and sub-optimal.

Is there a better way within Python and Maya to match the height of the two bounding boxes?

答:
You should be able to take the height of the larger object and divide it by the height of the smaller object to get a scale factor to use on the smaller object.

very very simple example (in pseudo code):

```<code>objectA height = 20
objectB height = 10
20 / 10 = 2 (so, scale objectB by 2 to match the height)
</code>```

Your actual code will be a matter of extracting the height from each bounding box, comparing the heights to determine the smaller object and scale factor, and then scaling the smaller one.  Hope that helps!

Body:
You should be able to take the height of the larger object and divide it by the height of the smaller object to get a scale factor to use on the smaller object.

very very simple example (in pseudo code):

objectA height = 20
objectB height = 10
20 / 10 = 2 (so, scale objectB by 2 to match the height)

Your actual code will be a matter of extracting the height from each bounding box, comparing the heights to determine the smaller object and scale factor, and then scaling the smaller one.  Hope that helps!


问:
php not getting key and value from generated url
I am trying to create a forgot password and password reset module using PHP.

Users upon entering the email id, I am fetching the record from MySQL that matches with the email id. I am able to fetch the record.

My reset_password form:

```<code><html>
  <body>
    <form method="post" action="sendlink.php">
      <p>Enter Email Address To Send Password Link</p>
      <input type="text" name="email">
      <input type="submit" name="submit_email">
    </form>
  </body>
</html>
</code>```

I am creating a link with the email id and password and send it as a mail to the user.  I am able to send the email.  I am providing a part of the code that enables me to send the email with the link.

```<code><?php
if(isset($_POST['submit_email']) && $_POST['email'])
{
  require 'connect.php';
  $email = $_POST['email'];
  $select=mysqli_query($connection, "select * from users where email='$email'");
  if(mysqli_num_rows($select)==1)
  {
    while($row=mysqli_fetch_array($select))
    {
      $email=$row['email'];
      $pass=$row['pass'];
    }
    $link="<a href='www.mywebsite.com/reset_pass.php?key=".$email."&?reset=".$pass."'>Click to reset password.</a>";
    require_once "phpmailer/class.phpmailer.php";
    $mail = new PHPMailer(true);
    $mail->CharSet =  "utf-8";
</code>```

This is continued by other codes to send the mail.  This part is working correctly and I am receiving the mail.

When I click on the link received in the mail, I intend to open up a form to reset the password using reset_pass.php given in the link.

The following is the link that gets generated:

```<code>http://www.mywebsite.com/reset_pass.php?key=user@theshoecompany.com&?reset=39eb0152f5a43c08169716dbf158f08e
</code>```

Code to open the form to accept new password:

```<code><?php
if($_GET['key'] && $_GET['reset'])
{
  $email=$_GET['key'];
  $pass=$_GET['reset'];
  require('connect.php');
  $query = "SELECT * FROM `users` WHERE email='$email' and pass='$pass'";
  $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
  $count = mysqli_num_rows($result);

//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1)
  {
    ?>
    <form method="post" action="submit_new.php">
    <input type="hidden" name="emailnew" value="<?php echo $email;?>">
    <p>Enter New password</p>
    <input type="password" name='passwordnew'>
    <input type="submit" name="Submit">
    </form>
    <?php
  }
}
else {
  echo "<script>
                alert('could not get email or password');
                </script>";
}
?>
</code>```

With the above code I wanted to open a form for the user to type in a new password.  But the values of email and password are not getting posted from the link.  The browser opens blank page, loads it and just remains blank without opening the form to accept the password.

How do i rectify this?

答:
Your form's method is POST, you should get the values from $_POST instead of $GET.

The input value pairs will NOT be shown in URL but within HTTP request body if the method is POST.

Body:
I am trying to create a forgot password and password reset module using PHP.

Users upon entering the email id, I am fetching the record from MySQL that matches with the email id. I am able to fetch the record.

My reset_password form:

    <form method="post" action="sendlink.php">

Enter Email Address To Send Password Link

      <input type="text" name="email">
      <input type="submit" name="submit_email">
    </form>

I am creating a link with the email id and password and send it as a mail to the user.  I am able to send the email.  I am providing a part of the code that enables me to send the email with the link.

<?php
if(isset($_POST['submit_email']) && $_POST['email'])
{
  require 'connect.php';
  $email = $_POST['email'];
  $select=mysqli_query($connection, "select * from users where email='$email'");
  if(mysqli_num_rows($select)==1)
  {
    while($row=mysqli_fetch_array($select))
    {
      $email=$row['email'];
      $pass=$row['pass'];
    }
    $link="Click to reset password.";
    require_once "phpmailer/class.phpmailer.php";
    $mail = new PHPMailer(true);
    $mail->CharSet =  "utf-8";

This is continued by other codes to send the mail.  This part is working correctly and I am receiving the mail.

When I click on the link received in the mail, I intend to open up a form to reset the password using reset_pass.php given in the link.

The following is the link that gets generated:

http://www.mywebsite.com/reset_pass.php?key=user@theshoecompany.com&?reset=39eb0152f5a43c08169716dbf158f08e

Code to open the form to accept new password:

<?php
if($_GET['key'] && $_GET['reset'])
{
  $email=$_GET['key'];
  $pass=$_GET['reset'];
  require('connect.php');
  $query = "SELECT * FROM `users` WHERE email='$email' and pass='$pass'";
  $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
  $count = mysqli_num_rows($result);

//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1)
  {
    ?>
    <form method="post" action="submit_new.php">
    <input type="hidden" name="emailnew" value="<?php echo $email;?>">

Enter New password

    <input type="password" name='passwordnew'>
    <input type="submit" name="Submit">
    </form>
    <?php
  }
}
else {
  echo "";
}
?>

With the above code I wanted to open a form for the user to type in a new password.  But the values of email and password are not getting posted from the link.  The browser opens blank page, loads it and just remains blank without opening the form to accept the password.

How do i rectify this?


问:
How to show new image in Visual Composer in frontend wordpress?
I am using Visual Composer I have added new filed in back-end in using this code

```<code>array(
    "type" => "attach_images",
    "heading" => __("Flag Upload", "js_composer"),
    "param_name" => "flag_image_id",
    "value" => "",
    "description" => ""
),
</code>```

it is worrying fine in back-end but now I am stuck how to show this filed in front-end?

I have attached image for more understanding.

答:
```<code>function designas_partners() {
    // Title
    vc_map(
        array(
            'name' => __( 'Clients' ),
            'base' => 'designas_partners_content',
            'category' => __( 'Easy Component' ),
            'params' => array(

                array(
                "type"        => "attach_images",
                "heading"     => esc_html__( "Add Clients Images", "appcastle-core" ),
                "description" => esc_html__( "Add Clients Images", "appcastle-core" ),
                "param_name"  => "screenshots",
                "value"       => "",
                ),

            )
        )
    );
}

add_action( 'vc_before_init', 'designas_partners' );

function designas_partners_content_function( $atts, $content ) {

$gallery = shortcode_atts(
    array(
        'screenshots'      =>  'screenshots',
    ), $atts );

 $image_ids = explode(',',$gallery['screenshots']);
 $return = '
    <div class="clients">';
    foreach( $image_ids as $image_id ){
    $images = wp_get_attachment_image_src( $image_id, 'company_logo' );
    $return .='<div class="images"><img src="'.$images[0].'" alt="'.$atts['title'].'"></div>';
    $images++;
    }
    $return .='</div>';
return $return;
}

add_shortcode( 'designas_partners_content', 'designas_partners_content_function' )
</code>```

Body:
I am using Visual Composer I have added new filed in back-end in using this code

array(
    "type" => "attach_images",
    "heading" => __("Flag Upload", "js_composer"),
    "param_name" => "flag_image_id",
    "value" => "",
    "description" => ""
),

it is worrying fine in back-end but now I am stuck how to show this filed in front-end?

I have attached image for more understanding.


问:
Run app on iTouch w/o iTunes
I have written a small app using Ojective-C w/ XCode. It's only for personal fun and I don't want to pay Apple $99 to just let it run on my iTouch. Is there any alternative for me to run it on iTouch instead of iPhone simulator? Please give me some suggestion.</p>

答:
You cannot install an app on a stock OS iOS device except from the App store, or through a paid iOS Developer certificate (individual, company or enterprise).  There are no alternatives for app installation.

As for paying the $99 yourself... if you have a friend who is already registered as a Company in the iOS Developer Program, and isn't planning on using all of their allowed 100 UDID's, perhaps you could bum a "team membership" off of them, have them add you as a team member (consulting contract or whatever), and use their Company Developer enrollment to create a team member's Developer certificate, instead of paying the $99 yourself.

Title: Run app on iTouch w/o iTunes


问:
android how to recycle image before loading a new one
I have a out of memory problem here in which i have full screen images being displayed. I want to show images in full screen and I have two buttons to cycle through them to the left or to the right. How can i have the past images be recycled before showing the next to prevent the out of memory exception? or is there an even better way to do so?

here is my class in which i view the image.

```<code>public class ImageViewActivity extends Activity
{
private Button btnHome;
private Button btnBack;
private ImageButton btnLeft;
private ImageButton btnRight;
ImageView imageView;
RelativeLayout layout;

int height;
int width;

Bitmap bitmap;
String[] imagesPath;
int position;

// These matrices will be used to move and zoom image
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();

// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;

// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
String savedItemClicked;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.imageview_activity);

    btnHome = (Button) findViewById(R.id.btnHome);
    btnBack = (Button) findViewById(R.id.btnBack);
    btnLeft = (ImageButton) findViewById(R.id.leftArrow);
    btnRight = (ImageButton) findViewById(R.id.rightArrow);

    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    height = displayMetrics.heightPixels;
    width = displayMetrics.widthPixels;

    imagesPath = getIntent().getStringExtra("IMAGES").split("\\|");
    position = getIntent().getIntExtra("POSITION", 0);

    bitmap = BitmapFactory.decodeFile(imagesPath[position]);

    imageView = (ImageView)findViewById(R.id.displayImage);
    imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, width, height, false));

    btnLeft.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View arg0)
        {
            if (position == 0)
                position = 5;
            else
                position--;

            RectF imageRectF = new RectF(0, 0, width, height);
            RectF viewRectF = new RectF(0, 0, width, height);
            matrix.setRectToRect(imageRectF, viewRectF, Matrix.ScaleToFit.CENTER);

            bitmap = BitmapFactory.decodeFile(imagesPath[position]);
            ImageView imageView = (ImageView)findViewById(R.id.displayImage);
            imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, width, height, false));

            imageView.setImageMatrix(matrix);
        }
    });

    btnRight.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View arg0)
        {
            if (position == 5)
                position = 0;
            else
                position++;

            RectF imageRectF = new RectF(0, 0, width, height);
            RectF viewRectF = new RectF(0, 0, width, height);
            matrix.setRectToRect(imageRectF, viewRectF, Matrix.ScaleToFit.CENTER);

            bitmap = BitmapFactory.decodeFile(imagesPath[position]);
            ImageView imageView = (ImageView)findViewById(R.id.displayImage);
            imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, width, height, false));

            imageView.setImageMatrix(matrix);
        }
    });

    btnHome.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View arg0)
        {
            Intent ActivitySwitch = new Intent(getApplicationContext(), MainMenuActivity.class);
            startActivity(ActivitySwitch);
        }
    });

    btnBack.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View arg0)
        {
            Intent ActivitySwitch = new Intent(getApplicationContext(), AddClientActivity.class);
            startActivity(ActivitySwitch);
        }
    });

    imageView.setOnTouchListener(new View.OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            ImageView view = (ImageView) v;
            dumpEvent(event);

            // Handle touch events here...
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:
                    savedMatrix.set(matrix);
                    start.set(event.getX(), event.getY());
                    mode = DRAG;
                    break;
                case MotionEvent.ACTION_POINTER_DOWN:
                    oldDist = spacing(event);
                    if (oldDist > 10f) {
                        savedMatrix.set(matrix);
                        midPoint(mid, event);
                        mode = ZOOM;
                    }
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_POINTER_UP:
                    mode = NONE;
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (mode == DRAG) {
                        // ...
                        matrix.set(savedMatrix);
                        matrix.postTranslate(event.getX() - start.x, event.getY()
                                - start.y);
                    } else if (mode == ZOOM) {
                        float newDist = spacing(event);
                        if (newDist > 10f) {
                            matrix.set(savedMatrix);
                            float scale = newDist / oldDist;
                            matrix.postScale(scale, scale, mid.x, mid.y);
                        }
                    }
                    break;
            }

            view.setImageMatrix(matrix);
            return true;
        }
    });

}

private void dumpEvent(MotionEvent event) {
    String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
            "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
    StringBuilder sb = new StringBuilder();
    int action = event.getAction();
    int actionCode = action & MotionEvent.ACTION_MASK;
    sb.append("event ACTION_").append(names[actionCode]);
    if (actionCode == MotionEvent.ACTION_POINTER_DOWN
            || actionCode == MotionEvent.ACTION_POINTER_UP) {
        sb.append("(pid ").append(
                action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
        sb.append(")");
    }
    sb.append("[");
    for (int i = 0; i < event.getPointerCount(); i++) {
        sb.append("#").append(i);
        sb.append("(pid ").append(event.getPointerId(i));
        sb.append(")=").append((int) event.getX(i));
        sb.append(",").append((int) event.getY(i));
        if (i + 1 < event.getPointerCount())
            sb.append(";");
    }
    sb.append("]");
}

/** Determine the space between the first two fingers */
private float spacing(MotionEvent event) {
    float x = event.getX(0) - event.getX(1);
    float y = event.getY(0) - event.getY(1);
    return (float)Math.sqrt(x * x + y * y);
}

/** Calculate the mid point of the first two fingers */
private void midPoint(PointF point, MotionEvent event) {
    float x = event.getX(0) + event.getX(1);
    float y = event.getY(0) + event.getY(1);
    point.set(x / 2, y / 2);
}
</code>```

thank you for any input and if you need any additional information please feel free to ask!

答:
it was a lot simpler then i first imagined. i simply added this

```<code>bitmap.recycle();
</code>```

before i declared my bitmap to the new image.

Body:
I have a out of memory problem here in which i have full screen images being displayed. I want to show images in full screen and I have two buttons to cycle through them to the left or to the right. How can i have the past images be recycled before showing the next to prevent the out of memory exception? or is there an even better way to do so?

here is my class in which i view the image.

public class ImageViewActivity extends Activity
{
private Button btnHome;
private Button btnBack;
private ImageButton btnLeft;
private ImageButton btnRight;
ImageView imageView;
RelativeLayout layout;

int height;
int width;

Bitmap bitmap;
String[] imagesPath;
int position;

// These matrices will be used to move and zoom image
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();

// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;

// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
String savedItemClicked;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.imageview_activity);

    btnHome = (Button) findViewById(R.id.btnHome);
    btnBack = (Button) findViewById(R.id.btnBack);
    btnLeft = (ImageButton) findViewById(R.id.leftArrow);
    btnRight = (ImageButton) findViewById(R.id.rightArrow);

    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    height = displayMetrics.heightPixels;
    width = displayMetrics.widthPixels;

    imagesPath = getIntent().getStringExtra("IMAGES").split("\\|");
    position = getIntent().getIntExtra("POSITION", 0);

    bitmap = BitmapFactory.decodeFile(imagesPath[position]);

    imageView = (ImageView)findViewById(R.id.displayImage);
    imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, width, height, false));

    btnLeft.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View arg0)
        {
            if (position == 0)
                position = 5;
            else
                position--;

            RectF imageRectF = new RectF(0, 0, width, height);
            RectF viewRectF = new RectF(0, 0, width, height);
            matrix.setRectToRect(imageRectF, viewRectF, Matrix.ScaleToFit.CENTER);

            bitmap = BitmapFactory.decodeFile(imagesPath[position]);
            ImageView imageView = (ImageView)findViewById(R.id.displayImage);
            imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, width, height, false));

            imageView.setImageMatrix(matrix);
        }
    });

    btnRight.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View arg0)
        {
            if (position == 5)
                position = 0;
            else
                position++;

            RectF imageRectF = new RectF(0, 0, width, height);
            RectF viewRectF = new RectF(0, 0, width, height);
            matrix.setRectToRect(imageRectF, viewRectF, Matrix.ScaleToFit.CENTER);

            bitmap = BitmapFactory.decodeFile(imagesPath[position]);
            ImageView imageView = (ImageView)findViewById(R.id.displayImage);
            imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, width, height, false));

            imageView.setImageMatrix(matrix);
        }
    });

    btnHome.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View arg0)
        {
            Intent ActivitySwitch = new Intent(getApplicationContext(), MainMenuActivity.class);
            startActivity(ActivitySwitch);
        }
    });

    btnBack.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View arg0)
        {
            Intent ActivitySwitch = new Intent(getApplicationContext(), AddClientActivity.class);
            startActivity(ActivitySwitch);
        }
    });

    imageView.setOnTouchListener(new View.OnTouchListener()
    {
        @Override
        public boolean onTouch(View v, MotionEvent event)
        {
            ImageView view = (ImageView) v;
            dumpEvent(event);

            // Handle touch events here...
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_DOWN:
                    savedMatrix.set(matrix);
                    start.set(event.getX(), event.getY());
                    mode = DRAG;
                    break;
                case MotionEvent.ACTION_POINTER_DOWN:
                    oldDist = spacing(event);
                    if (oldDist > 10f) {
                        savedMatrix.set(matrix);
                        midPoint(mid, event);
                        mode = ZOOM;
                    }
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_POINTER_UP:
                    mode = NONE;
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (mode == DRAG) {
                        // ...
                        matrix.set(savedMatrix);
                        matrix.postTranslate(event.getX() - start.x, event.getY()
                                - start.y);
                    } else if (mode == ZOOM) {
                        float newDist = spacing(event);
                        if (newDist > 10f) {
                            matrix.set(savedMatrix);
                            float scale = newDist / oldDist;
                            matrix.postScale(scale, scale, mid.x, mid.y);
                        }
                    }
                    break;
            }

            view.setImageMatrix(matrix);
            return true;
        }
    });

}

private void dumpEvent(MotionEvent event) {
    String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
            "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
    StringBuilder sb = new StringBuilder();
    int action = event.getAction();
    int actionCode = action & MotionEvent.ACTION_MASK;
    sb.append("event ACTION_").append(names[actionCode]);
    if (actionCode == MotionEvent.ACTION_POINTER_DOWN
            || actionCode == MotionEvent.ACTION_POINTER_UP) {
        sb.append("(pid ").append(
                action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
        sb.append(")");
    }
    sb.append("[");
    for (int i = 0; i < event.getPointerCount(); i++) {
        sb.append("#").append(i);
        sb.append("(pid ").append(event.getPointerId(i));
        sb.append(")=").append((int) event.getX(i));
        sb.append(",").append((int) event.getY(i));
        if (i + 1 < event.getPointerCount())
            sb.append(";");
    }
    sb.append("]");
}

/** Determine the space between the first two fingers */
private float spacing(MotionEvent event) {
    float x = event.getX(0) - event.getX(1);
    float y = event.getY(0) - event.getY(1);
    return (float)Math.sqrt(x * x + y * y);
}

/** Calculate the mid point of the first two fingers */
private void midPoint(PointF point, MotionEvent event) {
    float x = event.getX(0) + event.getX(1);
    float y = event.getY(0) + event.getY(1);
    point.set(x / 2, y / 2);
}

thank you for any input and if you need any additional information please feel free to ask!

Body:
it was a lot simpler then i first imagined. i simply added this

bitmap.recycle();

before i declared my bitmap to the new image.


问:
set field data = true on java elasticsearch
Running a java elastic search query through Eclipse. Getting this error when I am testing it, and I can't find anywhere in the API that tells me how I can set this field data to true

IllegalArgumentException[Fielddata is disabled on text fields by
  default. Set fielddata=true on [created] in order to load fielddata in
  memory by uninverting the inverted index. Note that this can however
  use significant memory. Alternatively use a keyword field instead.]

Does anyone know how I can fix this?

答:
In Elasticsearch 5.0, String fields were broken into two - Text and Keyword. If the property is supposed to be Analyzed, you'd want to migrate your String fields to Text, if not then migrate them to Keyword.

Look into your type mapping - If you had a property like this -

```<code>{
  "your_field": {
    "type" "string",
    "index": "not_analyzed"
  }
}
</code>```

You'd want to convert it to this -

```<code>{
  "your_field": {
    "type" "keyword",
    "index": true
  }
}
</code>```

Similarly, if your property was supposed to be analyzed and you had it like this-

```<code>{
  "your_field": {
    "type" "string",
    "index": "analyzed"
  }
}
</code>```

then you'd want to convert it to this-

```<code>{
  "your_field": {
    "type" "text",
    "index": true
  }
}
</code>```

Details on Elasticsearch official page

Body:
In Elasticsearch 5.0, String fields were broken into two - Text and Keyword. If the property is supposed to be Analyzed, you'd want to migrate your String fields to Text, if not then migrate them to Keyword.

Look into your type mapping - If you had a property like this -

{
  "your_field": {
    "type" "string",
    "index": "not_analyzed"
  }
}

You'd want to convert it to this -

{
  "your_field": {
    "type" "keyword",
    "index": true
  }
}

Similarly, if your property was supposed to be analyzed and you had it like this-

{
  "your_field": {
    "type" "string",
    "index": "analyzed"
  }
}

then you'd want to convert it to this-

{
  "your_field": {
    "type" "text",
    "index": true
  }
}

Details on Elasticsearch official page


问:
Remove/hide a preference from the screen
I have an activity which extends PreferenceActivity.
I'm loading preferences from the xml file.
But in some cases i need completely hide one of the preferences from the screen based on my app state. There is a setEnabled method, but it's not exactly what i want. I want to remove that preference from the screen completely.
Is it possible ?</p>

答:
I recommend using v7 preference, it has setVisible() method. But I have not tried it yet. Accordingly you have to use PreferenceFragment instead of PreferenceActivity.

https://developer.android.google.cn/reference/android/support/v7/preference/Preference.html#setVisible(boolean)


问:
R: cropping/zooming a map
I am trying to overlay data on top of a map of Canada, however I can't adjust the zoom as I would like. In the map, I want to be able to see the lines for each province anong with its name (so using map("world", "Canada") isn't desirable)

I have tried altering the zoom, but one is too zoomed out and the other is too zoomed in:

```<code>qmap(location = "Canada", zoom = 3)
</code>```

```<code>qmap(location = "Canada", zoom = 4)
</code>```

I have tried researching on how to crop the image but have been unsuccessful

Thank you!

答:
You can approach this using either the maps and mapsdata packages or continue with ggmap. It just depends on how much detail you want.

```<code>library(raster)
library(maps)
library(mapdata)
canada<-getData("GADM",country="CAN",level=1)

plot(canada,xlim=c(-141,-53),ylim=c(40,85),col="gray80",border="gray40",axes=T,las=1)
invisible(text(getSpPPolygonsLabptSlots(canada),labels=as.character(substr(canada$HASC_1,4,5)),
               cex=0.75, col="black",font=2))
</code>```

Using ggmap, you can specify a bounding box when grabbing your spatial data. It still overplots some of the area you are interested in (i.e., plots most of the US). Therefore, reapplying the bounding box values to the ggmap function cuts down the viewable area.

```<code>library(ggmap)

lats<-c(40,85)
lons<-c(-141,-53)
bb<-make_bbox(lon=lons,lat=lats,f=0.05)
cda<-get_map(bb,zoom=3,maptype="terrain")
ggmap(cda)+xlim(lons)+ylim(lats)+theme_bw()+labs(x="Longitude",y="Latitude")
</code>```

Title: R: cropping/zooming a map

Body:
I am trying to overlay data on top of a map of Canada, however I can't adjust the zoom as I would like. In the map, I want to be able to see the lines for each province anong with its name (so using map("world", "Canada") isn't desirable)

I have tried altering the zoom, but one is too zoomed out and the other is too zoomed in:

qmap(location = "Canada", zoom = 3)

qmap(location = "Canada", zoom = 4)

I have tried researching on how to crop the image but have been unsuccessful

Thank you!

Body:
You can approach this using either the maps and mapsdata packages or continue with ggmap. It just depends on how much detail you want.

library(raster)
library(maps)
library(mapdata)
canada<-getData("GADM",country="CAN",level=1)

plot(canada,xlim=c(-141,-53),ylim=c(40,85),col="gray80",border="gray40",axes=T,las=1)
invisible(text(getSpPPolygonsLabptSlots(canada),labels=as.character(substr(canada$HASC_1,4,5)),
               cex=0.75, col="black",font=2))

Using ggmap, you can specify a bounding box when grabbing your spatial data. It still overplots some of the area you are interested in (i.e., plots most of the US). Therefore, reapplying the bounding box values to the ggmap function cuts down the viewable area.

library(ggmap)

lats<-c(40,85)
lons<-c(-141,-53)
bb<-make_bbox(lon=lons,lat=lats,f=0.05)
cda<-get_map(bb,zoom=3,maptype="terrain")
ggmap(cda)+xlim(lons)+ylim(lats)+theme_bw()+labs(x="Longitude",y="Latitude")


问:
Java NullPointer Exception with Jpanel
Hello guys I started a personal project to where I would basically make a meal planner based of how many calories a person wants to consume per day for myself. I know it maybe a tough challenge for me since I'm a beginner, but I can do it! I will leave the backend later, but for now I wanted to work on the UI and I'm having trouble with this piece of code. I want to make a list of panels to be held in a panel, based on how many number of meals they want is how many panels will appear. any insight on this will be much appreciated. </p>

```<code>package mealplanner;

import javax.swing.*;

/**
 * Created by Usman on 6/8/2017.
 */
public class MealPlannerPanel extends JPanel {

    JPanel[] panel;
    int mealsPerDay, caloriesPerDay;
    public MealPlannerPanel(){
        mealsPerDay = Integer.parseInt(JOptionPane.showInputDialog("How many meals would you like per day?",null));
        caloriesPerDay = Integer.parseInt(JOptionPane.showInputDialog("What is your daily calorie aim?",null));
        panel = new JPanel[mealsPerDay];
        for(int i = 0; i < panel.length; i++){
            add(panel[i]);
        }
    }
    public static void main(String[] args){
        MealPlannerPanel planner = new MealPlannerPanel();
        JFrame frame = new JFrame("Meal Planner");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(planner);
        frame.pack();
        frame.setVisible(true);
    }
}
</code>```

答:
```<code>panel = new JPanel[mealsPerDay];
</code>```

That statement just creates an array that is able to hold the given number of panels.

It does not actually create the panel (so when you index into the array you will get a null object).

So you need something like:

```<code>    for(int i = 0; i < panel.length; i++){
        JPanel onePanel = new JPanel();
        panel[i] = onePanel;
        add(panel[i]);
    }
</code>```

Also, be more descriptive with you variable names. "panel" implies a single component. Given it is meant to represent an array the least you can do is call it "panels" so we know there is more than one.

Title: Java NullPointer Exception with Jpanel

Body:
Hello guys I started a personal project to where I would basically make a meal planner based of how many calories a person wants to consume per day for myself. I know it maybe a tough challenge for me since I'm a beginner, but I can do it! I will leave the backend later, but for now I wanted to work on the UI and I'm having trouble with this piece of code. I want to make a list of panels to be held in a panel, based on how many number of meals they want is how many panels will appear. any insight on this will be much appreciated.

package mealplanner;

import javax.swing.*;

/**
 * Created by Usman on 6/8/2017.
 */
public class MealPlannerPanel extends JPanel {

    JPanel[] panel;
    int mealsPerDay, caloriesPerDay;
    public MealPlannerPanel(){
        mealsPerDay = Integer.parseInt(JOptionPane.showInputDialog("How many meals would you like per day?",null));
        caloriesPerDay = Integer.parseInt(JOptionPane.showInputDialog("What is your daily calorie aim?",null));
        panel = new JPanel[mealsPerDay];
        for(int i = 0; i < panel.length; i++){
            add(panel[i]);
        }
    }
    public static void main(String[] args){
        MealPlannerPanel planner = new MealPlannerPanel();
        JFrame frame = new JFrame("Meal Planner");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(planner);
        frame.pack();
        frame.setVisible(true);
    }
}

Body:
panel = new JPanel[mealsPerDay];

That statement just creates an array that is able to hold the given number of panels.

It does not actually create the panel (so when you index into the array you will get a null object).

So you need something like:

    for(int i = 0; i < panel.length; i++){
        JPanel onePanel = new JPanel();
        panel[i] = onePanel;
        add(panel[i]);
    }

Also, be more descriptive with you variable names. "panel" implies a single component. Given it is meant to represent an array the least you can do is call it "panels" so we know there is more than one.