问:
how to change listen port from default 7001 to something different?
Can anyone tell me how to change the default listening port of Weblogic 10.3 to something different? I saw some posts on discussion boards which say that change it under ...//config/config.xml. Even I thought so, but surprisingly, there is no mention of word "port" in that file. Here is the file:</p>

```<code><?xml version='1.0' encoding='UTF-8'?>
<domain xmlns="http://xmlns.oracle.com/weblogic/domain" xmlns:sec="http://xmlns.oracle.com/weblogic/security" xmlns:wls="http://xmlns.oracle.com/weblogic/security/wls" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.oracle.com/weblogic/security/xacml http://xmlns.oracle.com/weblogic/security/xacml/1.0/xacml.xsd http://xmlns.oracle.com/weblogic/security/providers/passwordvalidator http://xmlns.oracle.com/weblogic/security/providers/passwordvalidator/1.0/passwordvalidator.xsd http://xmlns.oracle.com/weblogic/domain http://xmlns.oracle.com/weblogic/1.0/domain.xsd http://xmlns.oracle.com/weblogic/security http://xmlns.oracle.com/weblogic/1.0/security.xsd http://xmlns.oracle.com/weblogic/security/wls http://xmlns.oracle.com/weblogic/security/wls/1.0/wls.xsd">
  <name>vistakon</name>
  <domain-version>10.3.5.0</domain-version>
  <security-configuration>
    <name>vistakon</name>
    <realm>
      <sec:authentication-provider xsi:type="wls:default-authenticatorType"></sec:authentication-provider>
      <sec:authentication-provider xsi:type="wls:default-identity-asserterType">
        <sec:active-type>AuthenticatedUser</sec:active-type>
      </sec:authentication-provider>
      <sec:role-mapper xmlns:xac="http://xmlns.oracle.com/weblogic/security/xacml" xsi:type="xac:xacml-role-mapperType"></sec:role-mapper>
      <sec:authorizer xmlns:xac="http://xmlns.oracle.com/weblogic/security/xacml" xsi:type="xac:xacml-authorizerType"></sec:authorizer>
      <sec:adjudicator xsi:type="wls:default-adjudicatorType"></sec:adjudicator>
      <sec:credential-mapper xsi:type="wls:default-credential-mapperType"></sec:credential-mapper>
      <sec:cert-path-provider xsi:type="wls:web-logic-cert-path-providerType"></sec:cert-path-provider>
      <sec:cert-path-builder>WebLogicCertPathProvider</sec:cert-path-builder>
      <sec:name>myrealm</sec:name>
      <sec:password-validator xmlns:pas="http://xmlns.oracle.com/weblogic/security/providers/passwordvalidator" xsi:type="pas:system-password-validatorType">
        <sec:name>SystemPasswordValidator</sec:name>
        <pas:min-password-length>8</pas:min-password-length>
        <pas:min-numeric-or-special-characters>1</pas:min-numeric-or-special-characters>
      </sec:password-validator>
    </realm>
    <default-realm>myrealm</default-realm>
    <credential-encrypted>{AES}1NMyZAwXiucj9+d8cj/LGFmw+yhHyIj/YprGOq/PA9Vg0Se2+DkV54N5AwFzW+fN2SWvU5YtojWvVSTnifrUdT6uso4fpO6inAa3LQccOQv59VFxdceHOMv2h1dkngxq</credential-encrypted>
    <node-manager-username>weblogic</node-manager-username>
    <node-manager-password-encrypted>{AES}tRw5L/hFc8+4J4w1H8uBj3unE0BC06cdk42CyMLR6Pk=</node-manager-password-encrypted>
  </security-configuration>
  <server>
    <name>AdminServer</name>
    <ssl>
      <name>AdminServer</name>
      <enabled>true</enabled>
    </ssl>
    <listen-port>8080</listen-port>
    <listen-port-enabled>true</listen-port-enabled>
    <listen-address></listen-address>
    <java-compiler>javac</java-compiler>
    <client-cert-proxy-enabled>false</client-cert-proxy-enabled>
    <server-diagnostic-config>
      <wldf-diagnostic-volume>Low</wldf-diagnostic-volume>
    </server-diagnostic-config>
  </server>
  <embedded-ldap>
    <name>vistakon</name>
    <credential-encrypted>{AES}U6dM6LlDLLUYzefQ3M3NnsqijzWKSOgqLqNdJHVJEmeIU5v0wRZGm3ffumXif/uX</credential-encrypted>
  </embedded-ldap>
  <configuration-version>10.3.5.0</configuration-version>
  <app-deployment>
    <name>tbl</name>
    <target>AdminServer</target>
    <module-type>war</module-type>
    <source-path>C:\Documents and Settings\bchitte\Desktop\tbl.war</source-path>
    <security-dd-model>DDOnly</security-dd-model>
  </app-deployment>
  <app-deployment>
    <name>DatabaseLoggerService</name>
    <target>AdminServer</target>
    <module-type>war</module-type>
    <source-path>C:\Documents and Settings\bchitte\workspace\DatabaseLoggerService\DatabaseLoggerService.war</source-path>
    <security-dd-model>DDOnly</security-dd-model>
  </app-deployment>
  <app-deployment>
    <name>ReadingsProgressLogService</name>
    <target>AdminServer</target>
    <module-type>war</module-type>
    <source-path>C:\Documents and Settings\bchitte\workspace\ReadingsProgressLogService\ReadingsProgressLogService.war</source-path>
    <security-dd-model>DDOnly</security-dd-model>
  </app-deployment>
  <app-deployment>
    <name>de</name>
    <target>AdminServer</target>
    <module-type>war</module-type>
    <source-path>C:\Documents and Settings\bchitte\workspace\de.vogella.jersey.first\de.vogella.jersey.first.war</source-path>
    <security-dd-model>DDOnly</security-dd-model>
  </app-deployment>
  <app-deployment>
    <name>UpdateWIPQService</name>
    <target>AdminServer</target>
    <module-type>war</module-type>
    <source-path>C:\Documents and Settings\bchitte\workspace\UpdateWIPQService\UpdateWIPQService.war</source-path>
    <security-dd-model>DDOnly</security-dd-model>
  </app-deployment>
  <jms-server>
    <name>VistakonJMSServer</name>
    <target>AdminServer</target>
    <persistent-store>VistakonFileStore</persistent-store>
  </jms-server>
  <file-store>
    <name>VistakonFileStore</name>
    <target>AdminServer</target>
  </file-store>
  <jms-system-resource>
    <name>VistakonModule</name>
    <target>AdminServer</target>
    <sub-deployment>
      <name>sdVistakon</name>
      <target>VistakonJMSServer</target>
    </sub-deployment>
    <descriptor-file-name>jms/VistakonModule-jms.xml</descriptor-file-name>
  </jms-system-resource>
  <admin-server-name>AdminServer</admin-server-name>
  <jdbc-system-resource>
    <name>jdbc/MSSQL1</name>
    <target></target>
    <descriptor-file-name>jdbc/jdbc2fMSSQL1-5853-jdbc.xml</descriptor-file-name>
  </jdbc-system-resource>
</domain>
</code>```

答:
To update the listen ports for a server:
   1.Click Lock & Edit in the Change Center of the webLogic Administration Console
   2.expand Environment and select Server
   3.click the name of the server and select Configuration > General
   4.Find Listen Port to change it
   5.click Save and start server.

Body:
Can anyone tell me how to change the default listening port of Weblogic 10.3 to something different? I saw some posts on discussion boards which say that change it under ...//config/config.xml. Even I thought so, but surprisingly, there is no mention of word "port" in that file. Here is the file:

<?xml version='1.0' encoding='UTF-8'?>
<domain xmlns="http://xmlns.oracle.com/weblogic/domain" xmlns:sec="http://xmlns.oracle.com/weblogic/security" xmlns:wls="http://xmlns.oracle.com/weblogic/security/wls" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.oracle.com/weblogic/security/xacml http://xmlns.oracle.com/weblogic/security/xacml/1.0/xacml.xsd http://xmlns.oracle.com/weblogic/security/providers/passwordvalidator http://xmlns.oracle.com/weblogic/security/providers/passwordvalidator/1.0/passwordvalidator.xsd http://xmlns.oracle.com/weblogic/domain http://xmlns.oracle.com/weblogic/1.0/domain.xsd http://xmlns.oracle.com/weblogic/security http://xmlns.oracle.com/weblogic/1.0/security.xsd http://xmlns.oracle.com/weblogic/security/wls http://xmlns.oracle.com/weblogic/security/wls/1.0/wls.xsd">
  <name>vistakon</name>
  <domain-version>10.3.5.0</domain-version>
  <security-configuration>
    <name>vistakon</name>
    <realm>
      <sec:authentication-provider xsi:type="wls:default-authenticatorType"></sec:authentication-provider>
      <sec:authentication-provider xsi:type="wls:default-identity-asserterType">
        <sec:active-type>AuthenticatedUser</sec:active-type>
      </sec:authentication-provider>
      <sec:role-mapper xmlns:xac="http://xmlns.oracle.com/weblogic/security/xacml" xsi:type="xac:xacml-role-mapperType"></sec:role-mapper>
      <sec:authorizer xmlns:xac="http://xmlns.oracle.com/weblogic/security/xacml" xsi:type="xac:xacml-authorizerType"></sec:authorizer>
      <sec:adjudicator xsi:type="wls:default-adjudicatorType"></sec:adjudicator>
      <sec:credential-mapper xsi:type="wls:default-credential-mapperType"></sec:credential-mapper>
      <sec:cert-path-provider xsi:type="wls:web-logic-cert-path-providerType"></sec:cert-path-provider>
      <sec:cert-path-builder>WebLogicCertPathProvider</sec:cert-path-builder>
      <sec:name>myrealm</sec:name>
      <sec:password-validator xmlns:pas="http://xmlns.oracle.com/weblogic/security/providers/passwordvalidator" xsi:type="pas:system-password-validatorType">
        <sec:name>SystemPasswordValidator</sec:name>
        <pas:min-password-length>8</pas:min-password-length>
        <pas:min-numeric-or-special-characters>1</pas:min-numeric-or-special-characters>
      </sec:password-validator>
    </realm>
    <default-realm>myrealm</default-realm>
    <credential-encrypted>{AES}1NMyZAwXiucj9+d8cj/LGFmw+yhHyIj/YprGOq/PA9Vg0Se2+DkV54N5AwFzW+fN2SWvU5YtojWvVSTnifrUdT6uso4fpO6inAa3LQccOQv59VFxdceHOMv2h1dkngxq</credential-encrypted>
    <node-manager-username>weblogic</node-manager-username>
    <node-manager-password-encrypted>{AES}tRw5L/hFc8+4J4w1H8uBj3unE0BC06cdk42CyMLR6Pk=</node-manager-password-encrypted>
  </security-configuration>
  <server>
    <name>AdminServer</name>
    <ssl>
      <name>AdminServer</name>
      <enabled>true</enabled>
    </ssl>
    <listen-port>8080</listen-port>
    <listen-port-enabled>true</listen-port-enabled>
    <listen-address></listen-address>
    <java-compiler>javac</java-compiler>
    <client-cert-proxy-enabled>false</client-cert-proxy-enabled>
    <server-diagnostic-config>
      <wldf-diagnostic-volume>Low</wldf-diagnostic-volume>
    </server-diagnostic-config>
  </server>
  <embedded-ldap>
    <name>vistakon</name>
    <credential-encrypted>{AES}U6dM6LlDLLUYzefQ3M3NnsqijzWKSOgqLqNdJHVJEmeIU5v0wRZGm3ffumXif/uX</credential-encrypted>
  </embedded-ldap>
  <configuration-version>10.3.5.0</configuration-version>
  <app-deployment>
    <name>tbl</name>
    <target>AdminServer</target>
    <module-type>war</module-type>
    <source-path>C:\Documents and Settings\bchitte\Desktop\tbl.war</source-path>
    <security-dd-model>DDOnly</security-dd-model>
  </app-deployment>
  <app-deployment>
    <name>DatabaseLoggerService</name>
    <target>AdminServer</target>
    <module-type>war</module-type>
    <source-path>C:\Documents and Settings\bchitte\workspace\DatabaseLoggerService\DatabaseLoggerService.war</source-path>
    <security-dd-model>DDOnly</security-dd-model>
  </app-deployment>
  <app-deployment>
    <name>ReadingsProgressLogService</name>
    <target>AdminServer</target>
    <module-type>war</module-type>
    <source-path>C:\Documents and Settings\bchitte\workspace\ReadingsProgressLogService\ReadingsProgressLogService.war</source-path>
    <security-dd-model>DDOnly</security-dd-model>
  </app-deployment>
  <app-deployment>
    <name>de</name>
    <target>AdminServer</target>
    <module-type>war</module-type>
    <source-path>C:\Documents and Settings\bchitte\workspace\de.vogella.jersey.first\de.vogella.jersey.first.war</source-path>
    <security-dd-model>DDOnly</security-dd-model>
  </app-deployment>
  <app-deployment>
    <name>UpdateWIPQService</name>
    <target>AdminServer</target>
    <module-type>war</module-type>
    <source-path>C:\Documents and Settings\bchitte\workspace\UpdateWIPQService\UpdateWIPQService.war</source-path>
    <security-dd-model>DDOnly</security-dd-model>
  </app-deployment>
  <jms-server>
    <name>VistakonJMSServer</name>
    <target>AdminServer</target>
    <persistent-store>VistakonFileStore</persistent-store>
  </jms-server>
  <file-store>
    <name>VistakonFileStore</name>
    <target>AdminServer</target>
  </file-store>
  <jms-system-resource>
    <name>VistakonModule</name>
    <target>AdminServer</target>

      <name>sdVistakon</name>
      <target>VistakonJMSServer</target>

    <descriptor-file-name>jms/VistakonModule-jms.xml</descriptor-file-name>
  </jms-system-resource>
  <admin-server-name>AdminServer</admin-server-name>
  <jdbc-system-resource>
    <name>jdbc/MSSQL1</name>
    <target></target>
    <descriptor-file-name>jdbc/jdbc2fMSSQL1-5853-jdbc.xml</descriptor-file-name>
  </jdbc-system-resource>
</domain>


来源: stackexchange

问:
Generic where condition in Entity Framework Core
I'm building a Web API application which use Unit of work design pattern. I've created a repository with search function:

```<code>public IQueryable<User> Search(SearchUserViewModel parameter)
{
    // Find all user from database
    var users = GetAll();

    // Id has been defined.
    if (parameter.Id != null)
        users = users.Where(x => x.Id == parameter.Id.Value);

    // Email has been defined.
    if (parameter.Email != null && !string.IsNullOrWhiteSpace(parameter.Email.Text))
    {
        var emailSearch = parameter.Email;
        switch (emailSearch.Mode)
        {
            case TextSearchMode.ContainIgnoreCase:
                // TODO: Recheck.
                users = users.Where(x => x.Email.Contains(emailSearch.Text));
                break;
            case TextSearchMode.Equal:
                users = users.Where(x => x.Email.Equals(emailSearch.Text));
                break;
            case TextSearchMode.EqualIgnoreCase:
                users = users.Where(x => x.Email.Equals(emailSearch.Text, StringComparison.OrdinalIgnoreCase));
                break;
            default:
                users = users.Where(x => x.Email.Contains(emailSearch.Text));
                break;
        }
    }

    if (parameter.Password != null && !string.IsNullOrWhiteSpace(parameter.Password.Text))
    {
        var passwordSearch = parameter.Password;
        switch (passwordSearch.Mode)
        {
            case TextSearchMode.ContainIgnoreCase:
                // TODO: Recheck.
                users = users.Where(x => x.Email.Contains(passwordSearch.Text));
                break;
            case TextSearchMode.Equal:
                users = users.Where(x => x.Email.Equals(passwordSearch.Text));
                break;
            case TextSearchMode.EqualIgnoreCase:
                users = users.Where(x => x.Email.Equals(passwordSearch.Text, StringComparison.OrdinalIgnoreCase));
                break;
            default:
                users = users.Where(x => x.Email.Contains(passwordSearch.Text));
                break;
        }
    }

    return users;
}
</code>```

With an enumeration:

```<code>public class TextSearch
{
    /// <summary>
    /// Comparision mode.
    /// </summary>
    public TextSearchMode Mode { get; set; }

    /// <summary>
    /// Text which needs searching.
    /// </summary>
    public string Text { get; set; }
}
</code>```

Search function runs fine for now. But I want to reduce my code. I wonder if there is a way to create a function like this one:

```<code>private IQueryable<T> SearchPropertyText(IQueryable<T> records, string propertyName, TextSearchMode mode)
{
    switch (mode)
    {
        case Equal:
            // TODO:
        case EqualIgnoreCase:
            // TODO:
        default:
            // TODO
    }

    return records;
}
</code>```

Then I can use the function like this:

```<code>users = SearchPropertyText(users, user.Email, emailSearch.Mode)
</code>```

As you've seen my code above, I have some mode of text searching listed in the TextSearchMode enumeration, base on mode, I'll search property with Equal, EqualIgnoreCase, Contains, ...

I'm thinking about generic function, but I don't know how to create it for now.

Can anyone help me please ?

答:
Rather than passing user.Email, you need to pass a Func that defines how to get the desired property from any user. Also, rather that passing a TextSearchMode, you should pass a TextSearch object since you also need the Text property to perform the search. Here is a code example:

```<code>private IQueryable<T> SearchPropertyText(IQueryable<T> records, Func<T, string> property, TextSearch search)
{
    switch (search.Mode)
    {
        case TextSearchMode.ContainIgnoreCase:
            records = records.Where(x => property(x).Contains(search.Text));
            break;
        case TextSearchMode.Equal:
            records = records.Where(x => property(x).Equals(search.Text));
            break;
        case TextSearchMode.EqualIgnoreCase:
            records = records.Where(x => property(x).Equals(search.Text, StringComparison.OrdinalIgnoreCase));
            break;
        default:
            records = records.Where(x => property(x).Contains(search.Text));
            break;
    }
    return records;
}
</code>```

Then use it like so:

```<code>users = SearchPropertyText(users, user => user.Email, emailSearch);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm building a Web API application which use Unit of work design pattern. I've created a repository with search function:

public IQueryable<User> Search(SearchUserViewModel parameter)
{
    // Find all user from database
    var users = GetAll();

    // Id has been defined.
    if (parameter.Id != null)
        users = users.Where(x => x.Id == parameter.Id.Value);

    // Email has been defined.
    if (parameter.Email != null && !string.IsNullOrWhiteSpace(parameter.Email.Text))
    {
        var emailSearch = parameter.Email;
        switch (emailSearch.Mode)
        {
            case TextSearchMode.ContainIgnoreCase:
                // TODO: Recheck.
                users = users.Where(x => x.Email.Contains(emailSearch.Text));
                break;
            case TextSearchMode.Equal:
                users = users.Where(x => x.Email.Equals(emailSearch.Text));
                break;
            case TextSearchMode.EqualIgnoreCase:
                users = users.Where(x => x.Email.Equals(emailSearch.Text, StringComparison.OrdinalIgnoreCase));
                break;
            default:
                users = users.Where(x => x.Email.Contains(emailSearch.Text));
                break;
        }
    }

    if (parameter.Password != null && !string.IsNullOrWhiteSpace(parameter.Password.Text))
    {
        var passwordSearch = parameter.Password;
        switch (passwordSearch.Mode)
        {
            case TextSearchMode.ContainIgnoreCase:
                // TODO: Recheck.
                users = users.Where(x => x.Email.Contains(passwordSearch.Text));
                break;
            case TextSearchMode.Equal:
                users = users.Where(x => x.Email.Equals(passwordSearch.Text));
                break;
            case TextSearchMode.EqualIgnoreCase:
                users = users.Where(x => x.Email.Equals(passwordSearch.Text, StringComparison.OrdinalIgnoreCase));
                break;
            default:
                users = users.Where(x => x.Email.Contains(passwordSearch.Text));
                break;
        }
    }

    return users;
}

With an enumeration:

public class TextSearch
{
    ///
    /// Comparision mode.
    ///
    public TextSearchMode Mode { get; set; }

    ///
    /// Text which needs searching.
    ///
    public string Text { get; set; }
}

Search function runs fine for now. But I want to reduce my code. I wonder if there is a way to create a function like this one:

private IQueryable<T> SearchPropertyText(IQueryable<T> records, string propertyName, TextSearchMode mode)
{
    switch (mode)
    {
        case Equal:
            // TODO:
        case EqualIgnoreCase:
            // TODO:
        default:
            // TODO
    }

    return records;
}

Then I can use the function like this:

users = SearchPropertyText(users, user.Email, emailSearch.Mode)

As you've seen my code above, I have some mode of text searching listed in the TextSearchMode enumeration, base on mode, I'll search property with Equal, EqualIgnoreCase, Contains, ...

I'm thinking about generic function, but I don't know how to create it for now.

Can anyone help me please ?

Body:
Rather than passing user.Email, you need to pass a Func that defines how to get the desired property from any user. Also, rather that passing a TextSearchMode, you should pass a TextSearch object since you also need the Text property to perform the search. Here is a code example:

private IQueryable<T> SearchPropertyText(IQueryable<T> records, Func<T, string> property, TextSearch search)
{
    switch (search.Mode)
    {
        case TextSearchMode.ContainIgnoreCase:
            records = records.Where(x => property(x).Contains(search.Text));
            break;
        case TextSearchMode.Equal:
            records = records.Where(x => property(x).Equals(search.Text));
            break;
        case TextSearchMode.EqualIgnoreCase:
            records = records.Where(x => property(x).Equals(search.Text, StringComparison.OrdinalIgnoreCase));
            break;
        default:
            records = records.Where(x => property(x).Contains(search.Text));
            break;
    }
    return records;
}

Then use it like so:

users = SearchPropertyText(users, user => user.Email, emailSearch);


问:
Create a config file to hold values like username password url in python behave
I'm trying to create a config that holds information such as username password etc.

I have created an ini file holding this:

```<code>[DEFAULT]
username: user
password: pass
</code>```

I then have a config map class like:

import configparser

```<code>class ConfigSectionMap:
    def __init__(self):
        my_config_parser = configparser.ConfigParser()
        my_config_parser.read('inilocation')
        print(my_config_parser.default_section)

    def config_map(self, section):
        dict1 = {}
        options = self.my_config_parser.options(section)
        for option in options:
            try:
                dict1[option] = self.my_config_parser.get(section, option)
                if dict1[option] == -1:
                    print("skip: %s" % option)
            except:
                print("exception on %s!" % option)
                dict1[option] = None
        return dict1
</code>```

In my main class where I want to use this I do:

```<code>from config_section_map import ConfigSectionMap

print(ConfigSectionMap.config_map(("DEFAULT")['password']))
</code>```

when running this I receive an error:

TypeError: string indices must be integers

I've been following the docs but it's not working: https://wiki.python.org/moin/ConfigParserExamples

Or if there is an easier way please show me

edit:

changing to this

```<code>print(ConfigSectionMap.config_map("DEFAULT")['password'])
</code>```

shows

```<code>TypeError: config_map() missing 1 required positional argument: 'section'
</code>```

答:
You made an error calling config map. Config map takes a section, like "DEFAULT".

What you are trying is to send ('DEFAULT')['password']. But ('DEFAULT') evaluates to a string, and string indices can only take integers.

Trying to take an index to begin with is just an typing error you made.

There is a problem with how you are working with ConfigSectionMap. As it is now, you are working with attribute refrences, which is legal but not the expected way to work with config_map. config_map() expects two arguments (self, section) when doing a reference to config_map you are only passing one argument.

You either pass along self or you make an instance. By calling ConfigSectionMap() you will get an instance that have initiated the attributes inside self.

Change your code to the following instead, do you see the difference?

```<code>from config_section_map import ConfigSectionMap

conf_object = ConfigSectionMap()

print(conf_object.config_map("DEFAULT")['password'])
</code>```

The ['password'] is now applied to the returned result from config_map instead of the argument to it.

To solve the problem options = self.my_config_parser.options(section) AttributeError: 'ConfigSectionMap' object has no attribute 'my_config_parser'

You have to define the attributes inside self, otherwise it will stay in that local scope of __init__

```<code>class ConfigSectionMap:
    def __init__(self):
        self.my_config_parser = configparser.ConfigParser()
        self.my_config_parser.read('inilocation')
        print(self.my_config_parser.default_section)

    def config_map(self, section):
        dict1 = {}
        options = self.my_config_parser.options(section)
        for option in options:
            try:
                dict1[option] = self.my_config_parser.get(section, option)
                if dict1[option] == -1:
                    print("skip: %s" % option)
            except:
                print("exception on %s!" % option)
                dict1[option] = None
        return dict1
</code>```

As comment from @officialaimm pointed out, there might be a problem naming a section DEFAULT try change config to

```<code>[SomeThingElse]
username: user
password: pass
</code>```

instead

Body:
I'm trying to create a config that holds information such as username password etc.

I have created an ini file holding this:

[DEFAULT]
username: user
password: pass

I then have a config map class like:

import configparser

class ConfigSectionMap:
    def __init__(self):
        my_config_parser = configparser.ConfigParser()
        my_config_parser.read('inilocation')
        print(my_config_parser.default_section)

    def config_map(self, section):
        dict1 = {}
        options = self.my_config_parser.options(section)
        for option in options:
            try:
                dict1[option] = self.my_config_parser.get(section, option)
                if dict1[option] == -1:
                    print("skip: %s" % option)
            except:
                print("exception on %s!" % option)
                dict1[option] = None
        return dict1

In my main class where I want to use this I do:

from config_section_map import ConfigSectionMap

print(ConfigSectionMap.config_map(("DEFAULT")['password']))

when running this I receive an error:

TypeError: string indices must be integers

I've been following the docs but it's not working: https://wiki.python.org/moin/ConfigParserExamples

Or if there is an easier way please show me

edit:

changing to this

print(ConfigSectionMap.config_map("DEFAULT")['password'])

shows

TypeError: config_map() missing 1 required positional argument: 'section'

Body:
You made an error calling config map. Config map takes a section, like "DEFAULT".

What you are trying is to send ('DEFAULT')['password']. But ('DEFAULT') evaluates to a string, and string indices can only take integers.

Trying to take an index to begin with is just an typing error you made.

There is a problem with how you are working with ConfigSectionMap. As it is now, you are working with attribute refrences, which is legal but not the expected way to work with config_map. config_map() expects two arguments (self, section) when doing a reference to config_map you are only passing one argument.

You either pass along self or you make an instance. By calling ConfigSectionMap() you will get an instance that have initiated the attributes inside self.

Change your code to the following instead, do you see the difference?

from config_section_map import ConfigSectionMap

conf_object = ConfigSectionMap()

print(conf_object.config_map("DEFAULT")['password'])

The ['password'] is now applied to the returned result from config_map instead of the argument to it.

To solve the problem options = self.my_config_parser.options(section) AttributeError: 'ConfigSectionMap' object has no attribute 'my_config_parser'

You have to define the attributes inside self, otherwise it will stay in that local scope of __init__

class ConfigSectionMap:
    def __init__(self):
        self.my_config_parser = configparser.ConfigParser()
        self.my_config_parser.read('inilocation')
        print(self.my_config_parser.default_section)

    def config_map(self, section):
        dict1 = {}
        options = self.my_config_parser.options(section)
        for option in options:
            try:
                dict1[option] = self.my_config_parser.get(section, option)
                if dict1[option] == -1:
                    print("skip: %s" % option)
            except:
                print("exception on %s!" % option)
                dict1[option] = None
        return dict1

As comment from @officialaimm pointed out, there might be a problem naming a section DEFAULT try change config to

[SomeThingElse]
username: user
password: pass

instead


问:
How to make Cluster in arangodb?
Hello I'm using arangodb version 3.1.11,
my question is that how to make a cluster in arangodb 3.1.11
here I've done some changes in /etc/arangodb/arangod.conf
whenever i enable cluster mode by adding these two line in configuration file which is given below:

[cluster]

disable-dispatcher-kickstarter = no

disable-dispatcher-frontend = no

after adding these lines my arangodb service is not restarted so what is the solution please help me.

答:
The currently recommendet way to start an arangodb cluster without DC/OS is to use the ArangoDBStarter, which does automatically take care of all those parameters.

You run ArangoDBStarter on the primary node first. You specify the IP its going to be available at.Then on all other nodes telling the instances on those hosts which IP the primary host has - it will output the slave commands so you just need to cut'n'paste them.

If you try a sample setup on a single machine you can invoke ArangoDBStarter multiple times there (At least 3 times in total).

It should get you up and running without any troubles.

Title: How to make Cluster in arangodb?


问:
Unable to start Ensime debugger in Emacs
I am using Emacs 24.5.1 scala 2.11.5 with ensime. Ensime server runs fine with all error suggestion and other IDE feature etc. But when I start debugging code with  M-x ensime-db-attach it prompt with me Hostname and Port. Which port is it asking for? I want to debug my code locally.

答: Executing sbt -jvm-debug 5005 from scala home directory resolved the problem. Also in Emacs M-x ensime-db-attach when prompted let Hostname be localhost and Port be 5005.


问:
How to make a sub use global variable value specifically from another sub (being set different values in other subs)
I have a global variable and its value is being changed constantly depending on what the user does

When my app enters this sub, i want it to use the value from a specific sub elsewhere in the project

Help?

Using VB6

答:
In your SUB or FUNCTION you can add a Optional parameter with default value. I.e.:

' on BAS module

```<code>Public gsMyVar As String
Public Sub MakeSomething(Optional ByVal pMyVar As String = vbNullString)
    If pMyVar = vbNullString Then
        pMyVar = gsMyVar
    End If
    MsgBox "LOCAL MyVar is now: " & pMyVar
End Sub
</code>```

' on FRM module

```<code>Private Sub Command1_Click()
    gsMyVar = "BLA-BLA-BLA"
    MsgBox "Global MyVar is : " & gsMyVar
    MakeSomething "YES"
End Sub
</code>```

Body:
In your SUB or FUNCTION you can add a Optional parameter with default value. I.e.:

' on BAS module

Public gsMyVar As String
Public Sub MakeSomething(Optional ByVal pMyVar As String = vbNullString)
    If pMyVar = vbNullString Then
        pMyVar = gsMyVar
    End If
    MsgBox "LOCAL MyVar is now: " & pMyVar
End Sub

' on FRM module

Private Sub Command1_Click()
    gsMyVar = "BLA-BLA-BLA"
    MsgBox "Global MyVar is : " & gsMyVar
    MakeSomething "YES"
End Sub


问:
Textile: using code and footnotes
Hi I'm using Redmine to write a wiki of my software. I need to put some notes next to a code section like this:

```<code>class.method()[1]
</code>```

Where the "one" is a link to my note at the end of the page.
I've tried to use any method defined in the Textile syntax but it seems that it doesn't work. In fact when you use the code tag '@ @' any other tag stops working.

It's good even if I can use the link tag [[ ]] but only if it is like this google.com

Thanks for any help,

Alessandro

答:
The footnote will only work if there is an alphanumeric character directly before the opening square bracktet:

```<code>this[1], whereas this()[2] or this [3]

fn1. will work

fn2. won't work.

fn3. won't work.
</code>```

At least this is true with Redmine 3.1. See this issue for more information.

Note that you need blank lines between fn1., fn2. and fn3. to get a correct rendering.

Title: Textile: using code and footnotes

Body:
Hi I'm using Redmine to write a wiki of my software. I need to put some notes next to a code section like this:

class.method()[1]

Where the "one" is a link to my note at the end of the page.
I've tried to use any method defined in the Textile syntax but it seems that it doesn't work. In fact when you use the code tag '@ @' any other tag stops working.

It's good even if I can use the link tag [[ ]] but only if it is like this google.com

Thanks for any help,

Alessandro

Body:
The footnote will only work if there is an alphanumeric character directly before the opening square bracktet:

this[1], whereas this()[2] or this [3]

fn1. will work

fn2. won't work.

fn3. won't work.

At least this is true with Redmine 3.1. See this issue for more information.

Note that you need blank lines between fn1., fn2. and fn3. to get a correct rendering.


问:
How to filter JSON data based on multiple criteria in JavaScript?
I am trying to filter out all records that don't contain values from the 5 arrays: ssn, spn, smft, ssl, svtv. The output is not correct because it only works in cases where the lists contain 1 element. The output array becomes empty when they contain multiple elements. I am trying to get records that don't contain one of the values from each list (OR). I think it doesn't work because it checks if each record doesn't contain all values in each list (AND). Any idea how to fix this?

jsonData

```<code>[{"sn": "234234234", "pn": "1014143", "mft": "hello world", "sl": "GG07", "vtv": "Yes"},{"sn": "324234234", "pn": "101423131143", "mft": "hello world 1", "sl": "GG08", "vtv": "Yes"}]
</code>```

query

```<code>ssn: ['T234834U', 'T23423423'],
spn: ['1014114', '21412342'],
smft: ['Sbasdfa', 'asdfaser'],
ssl: ['BB03', 'SFD04'],
svtv: ['Yes']
</code>```

Code

```<code>function getFiltered() {
    var query = {
        sn: ssn,
        pn: spn,
        mft: smft,
        sl: ssl,
        vtv: svtv
    }
    var filtered = find_in_object(jsonData, query)
}

function find_in_object(my_object, my_criteria) {
    return my_object.filter(function(obj) {
        return Object.keys(my_criteria).every(function(c) {
            return JSON.stringify(obj[c]).indexOf(my_criteria[c]) === -1
        })
    })
}
</code>```

答:
Something like this should work

```<code>function find_in_object(data, query) {
  return data.filter(function(record) {
    for(var i in record) {
      if(query[i] && query[i].indexOf(record[i]) !== -1) {
        return false;
      }
    }
    return true;
  });
}
</code>```

However it is not clear whether you want to match a complete key and value pair, or just a single value regardless of it's key. The above will only work if the key AND the value match.

Body:
I am trying to filter out all records that don't contain values from the 5 arrays: ssn, spn, smft, ssl, svtv. The output is not correct because it only works in cases where the lists contain 1 element. The output array becomes empty when they contain multiple elements. I am trying to get records that don't contain one of the values from each list (OR). I think it doesn't work because it checks if each record doesn't contain all values in each list (AND). Any idea how to fix this?

jsonData

[{"sn": "234234234", "pn": "1014143", "mft": "hello world", "sl": "GG07", "vtv": "Yes"},{"sn": "324234234", "pn": "101423131143", "mft": "hello world 1", "sl": "GG08", "vtv": "Yes"}]

query

ssn: ['T234834U', 'T23423423'],
spn: ['1014114', '21412342'],
smft: ['Sbasdfa', 'asdfaser'],
ssl: ['BB03', 'SFD04'],
svtv: ['Yes']

Code

function getFiltered() {
    var query = {
        sn: ssn,
        pn: spn,
        mft: smft,
        sl: ssl,
        vtv: svtv
    }
    var filtered = find_in_object(jsonData, query)
}

function find_in_object(my_object, my_criteria) {
    return my_object.filter(function(obj) {
        return Object.keys(my_criteria).every(function(c) {
            return JSON.stringify(obj[c]).indexOf(my_criteria[c]) === -1
        })
    })
}

Body:
Something like this should work

function find_in_object(data, query) {
  return data.filter(function(record) {
    for(var i in record) {
      if(query[i] && query[i].indexOf(record[i]) !== -1) {
        return false;
      }
    }
    return true;
  });
}

However it is not clear whether you want to match a complete key and value pair, or just a single value regardless of it's key. The above will only work if the key AND the value match.


问:
How to password protect wordpress site?
I need to password protect my wordpress site except home page. I need homepage to be visible to every visitor but if they click on ANY link that could be post/page within the site then user should be redirected to login page. Any help would be appreciated</p>

答:
Just a bit of edit to benhowdle89's code..</p>

```<code><?php
if (is_user_logged_in() || is_home()){
    echo "Welcome, registered user, here are my lovely posts";
}
else {
    header( 'Location: http://www.yoursite.com/wp-login.php' ) ;
};
?>
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to password protect wordpress site?

Body:
Just a bit of edit to benhowdle89's code..

<?php
if (is_user_logged_in() || is_home()){
    echo "Welcome, registered user, here are my lovely posts";
}
else {
    header( 'Location: http://www.yoursite.com/wp-login.php' ) ;
};
?>


问:
Want to route one component to another component
I am new to ReactJS I have Three components App.js ,Login.js,Register.js when the wepapp is launched it first launched App.js in that component i have two buttons "Login" and "Register" ,By clicking on Login button it should goto the LogIn component and on click on Register button it should goto Register component,I am not finding a clean way to achieve that.
Here is my code for App.js

```<code>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

   constructor(props) {
    super(props);
    // This binding is necessary to make `this` work in the callback
    this.gotoLogin = this.gotoLogin.bind(this);
    this.gotoRegister = this.gotoRegister.bind(this);

  }

  gotoLogin() {

    alert("Login");
  }

   gotoRegister() {

      alert("Register");

  }
  render() {
    return (
      <div className="App">
        <div className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h2>Welcome to React</h2>
        </div>
        <button  onClick={this.gotoLogin} class="Button ">Login</button>
        <button  onClick ={this.gotoRegister} class="Button">Register</button>
      </div>
    );
  }
}

export default App;
</code>```

code for index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
</code>```

Respective i have also component class for Login.js and Register.js

答:
If you using router v2 or v3, use this:

```<code>gotoLogin() {
   hashHistory.push("/Login");  or browserHistory.push("/Login");
}

gotoRegister() {
    hashHistory.push("/Register");  or browserHistory.push("/Register");
}
</code>```

Note: Use the same history that you are using with react-router.

If you are using router v4, use this:

```<code>gotoLogin() {
   this.context.router.transitionTo("/Login");
}

gotoRegister() {
    this.context.router.transitionTo("/Register");
}
</code>```

Note: You need to define the contextTypes with you component.

Check this example:

```<code>class App extends React.Component {
  constructor(props, context) {
    super();
    const { router } = this.context;
  }
  ....
}

App.contextTypes = {
  router: React.PropTypes.object
}
</code>```

Now use this: router.transitionTo("/Login");

Check this: https://github.com/ReactTraining/react-router/issues/4129

Body:
I am new to ReactJS I have Three components App.js ,Login.js,Register.js when the wepapp is launched it first launched App.js in that component i have two buttons "Login" and "Register" ,By clicking on Login button it should goto the LogIn component and on click on Register button it should goto Register component,I am not finding a clean way to achieve that.
Here is my code for App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

   constructor(props) {
    super(props);
    // This binding is necessary to make `this` work in the callback
    this.gotoLogin = this.gotoLogin.bind(this);
    this.gotoRegister = this.gotoRegister.bind(this);

  }

  gotoLogin() {

    alert("Login");
  }

   gotoRegister() {

      alert("Register");

  }
  render() {
    return (

Welcome to React

        <button  onClick={this.gotoLogin} class="Button ">Login</button>
        <button  onClick ={this.gotoRegister} class="Button">Register</button>

    );
  }
}

export default App;

code for index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Respective i have also component class for Login.js and Register.js

Body:
If you using router v2 or v3, use this:

gotoLogin() {
   hashHistory.push("/Login");  or browserHistory.push("/Login");
}

gotoRegister() {
    hashHistory.push("/Register");  or browserHistory.push("/Register");
}

Note: Use the same history that you are using with react-router.

If you are using router v4, use this:

gotoLogin() {
   this.context.router.transitionTo("/Login");
}

gotoRegister() {
    this.context.router.transitionTo("/Register");
}

Note: You need to define the contextTypes with you component.

Check this example:

class App extends React.Component {
  constructor(props, context) {
    super();
    const { router } = this.context;
  }
  ....
}

App.contextTypes = {
  router: React.PropTypes.object
}

Now use this: router.transitionTo("/Login");

Check this: https://github.com/ReactTraining/react-router/issues/4129


问:
how to create simple SQLite database in android with cursor adaptor?
Hi I am newby in android programming I want sqlite database in android application for handling some database related stuff . I am developing application like it will scan some wifi devices from home get there vendor id should display in listview upon pressing any item from list it should send some udp massage to that respected device upon getting response to udp massage it should create again one listview for that response . I have implemented Udp related stuff and scanning wifi devices related stuff also but only this is remaining is upon getting devices i need to store that device for further udp related stuff and maintaining database can anyone have best suggestion .

lass IP_Channal_DB extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "note.db";
    private static final String Table_NAME = "Ip_channal_Table";
    private static final String Col_1 = "ID";
    private static final String Col_2 = "IP_Address";
    private static final String Col_3 = "Flag";
    private static final String Col_4 = "Channal_1";
    private static final String Col_5 = "Channal_2";
    private static final String Col_6 = "Channal_3";
    private static final String Col_7 = "Channal_4";

    private static final int SCHEMA_VERSION = 1;

    private static final String DATABASE_CREATE = "CREATE TABLE " + Table_NAME + " (" + Col_1 + " integer PRIMARY KEY autoincrement," + Col_2 + "TEXT," + Col_3 + "TEXT," + Col_4 + "TEXT," + Col_5 + "TEXT," + Col_6 + "TEXT," + Col_7 + "TEXT,)";

    public IP_Channal_DB(Context context) {

        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.v("MainActivity","creating table");
        db.execSQL(DATABASE_CREATE);
        //db.execSQL("CREATE TABLE "+Table_NAME+"("+Col_1+" INTEGER PRIMARY KEY AUTOINCREMENT,"+Col_2+" TEXT,"+Col_3+"INTEGER,"+Col_4+" TEXT,"+Col_5+" TEXT,"+Col_6+" TEXT,"+Col_7+" TEXT);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
   /* public Cursor getAll_IP()
    {
        return (getReadableDatabase().rawQuery("SELECT "+Col_1+", "+Col_2+" FROM "+Table_NAME,null));
    }*/
   public Cursor getAll_IP()
    {
        SQLiteDatabase db=this.getReadableDatabase();
        Cursor cur=db.rawQuery("SELECT "+Col_1+" as _id, "+Col_2+" from "+Table_NAME,new String [] {});

        return cur;
    }

}```
</div>
</div>
</p>

<p>and logcat window is </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>03-31 14:39:36.547 1681-1681/com.example.admin.myhome E/SQLiteLog: (1) no such table: Ip_channal_Table
03-31 14:39:36.557 1681-1681/com.example.admin.myhome E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: com.example.admin.myhome, PID: 1681
                                                                        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.admin.myhome/com.example.admin.myhome.MainActivity}: android.database.sqlite.SQLiteException: no such table: Ip_channal_Table (code 1): , while compiling: SELECT ID as _id, IP_Address from Ip_channal_Table
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2348)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2410)
                                                                            at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4019)
                                                                            at android.app.ActivityThread.access$900(ActivityThread.java:151)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1319)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:135)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5345)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:947)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:742)
                                                                         Caused by: android.database.sqlite.SQLiteException: no such table: Ip_channal_Table (code 1): , while compiling: SELECT ID as _id, IP_Address from Ip_channal_Table
                                                                            at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                            at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                            at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                            at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                            at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                            at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
                                                                            at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                                                                            at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
                                                                            at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
                                                                            at com.example.admin.myhome.IP_Channal_DB.getAll_IP(NoteHolder.java:52)
                                                                            at com.example.admin.myhome.MainActivity$override.onCreate(MainActivity.java:131)
                                                                            at com.example.admin.myhome.MainActivity$override.access$dispatch(MainActivity.java)
                                                                            at com.example.admin.myhome.MainActivity.onCreate(MainActivity.java:0)
                                                                            at android.app.Activity.performCreate(Activity.java:6012)
                                                                            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2410)
                                                                            at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4019)
                                                                            at android.app.ActivityThread.access$900(ActivityThread.java:151)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1319)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:135)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5345)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:947)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:742) </code>```

答:
I developed a sample project which i used in my main application. I hope that helps you too.

DataBaseHandler.java

```<code>import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;

public class DataBaseHandler extends SQLiteOpenHelper {

    public String BooksTable="Books";
    public String Book_Id="id";
    public String BookAuther="BookAuther";
    public String BookTitle="BookTitle";

    private  final int DB_Version=1;
    public DataBaseHandler(Context context,String DBName,int DBVersion){
        super(context, DBName,null,DBVersion);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("Create Table " + BooksTable + "(" + Book_Id + " INTEGER PRIMARY KEY, " + BookAuther + " Text, " + BookTitle + " Text);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
    public void addBook(Book book){
        SQLiteDatabase db=this.getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put(Book_Id,book.getId());
        cv.put(BookAuther,book.getAuthor());
        cv.put(BookTitle,book.getTitle());

        db.insert(BooksTable, null, cv);
        db.close();
    }

    public ArrayList<Book> fetchAllBooks(){
        ArrayList<Book> booksList = new ArrayList<Book>();
        SQLiteDatabase db=this.getReadableDatabase();
        Cursor c= db.query(BooksTable, null, null, null, null, null, null);
        c.moveToFirst();
        while (!c.isAfterLast()){
            Book book = new Book();
            book.setId(c.getInt(0));
            book.setAuthor(c.getString(1));
            book.setTitle(c.getString(2));
            booksList.add(book);
            c.moveToNext();
        }
        db.close();
        return booksList;
    }
}
</code>```

Book.java

```<code>public class Book {
private int id;
private String author;
private String title;

public void setId(int id) {
    this.id = id;
}

public void setAuthor(String author) {
    this.author = author;
}

public void setTitle(String title) {
    this.title = title;
}

public int getId() {
    return id;
}

public String getAuthor() {
    return author;
}

public String getTitle() {
      return title;
    }
}
</code>```

MainActivity.java

```<code>DataBaseHandler db=new DataBaseHandler(getApplicationContext(),"DB_Name",1);
Book book=new Book();
book.setId(1);
book.setTitle("My Title");
book.setAuthor("Name of Author");
db.addBook(book);
</code>```

Body:
Hi I am newby in android programming I want sqlite database in android application for handling some database related stuff . I am developing application like it will scan some wifi devices from home get there vendor id should display in listview upon pressing any item from list it should send some udp massage to that respected device upon getting response to udp massage it should create again one listview for that response . I have implemented Udp related stuff and scanning wifi devices related stuff also but only this is remaining is upon getting devices i need to store that device for further udp related stuff and maintaining database can anyone have best suggestion .

lass IP_Channal_DB extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "note.db";
    private static final String Table_NAME = "Ip_channal_Table";
    private static final String Col_1 = "ID";
    private static final String Col_2 = "IP_Address";
    private static final String Col_3 = "Flag";
    private static final String Col_4 = "Channal_1";
    private static final String Col_5 = "Channal_2";
    private static final String Col_6 = "Channal_3";
    private static final String Col_7 = "Channal_4";

    private static final int SCHEMA_VERSION = 1;

    private static final String DATABASE_CREATE = "CREATE TABLE " + Table_NAME + " (" + Col_1 + " integer PRIMARY KEY autoincrement," + Col_2 + "TEXT," + Col_3 + "TEXT," + Col_4 + "TEXT," + Col_5 + "TEXT," + Col_6 + "TEXT," + Col_7 + "TEXT,)";

    public IP_Channal_DB(Context context) {

        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.v("MainActivity","creating table");
        db.execSQL(DATABASE_CREATE);
        //db.execSQL("CREATE TABLE "+Table_NAME+"("+Col_1+" INTEGER PRIMARY KEY AUTOINCREMENT,"+Col_2+" TEXT,"+Col_3+"INTEGER,"+Col_4+" TEXT,"+Col_5+" TEXT,"+Col_6+" TEXT,"+Col_7+" TEXT);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
   /* public Cursor getAll_IP()
    {
        return (getReadableDatabase().rawQuery("SELECT "+Col_1+", "+Col_2+" FROM "+Table_NAME,null));
    }*/
   public Cursor getAll_IP()
    {
        SQLiteDatabase db=this.getReadableDatabase();
        Cursor cur=db.rawQuery("SELECT "+Col_1+" as _id, "+Col_2+" from "+Table_NAME,new String [] {});

        return cur;
    }

}

and logcat window is

03-31 14:39:36.547 1681-1681/com.example.admin.myhome E/SQLiteLog: (1) no such table: Ip_channal_Table
03-31 14:39:36.557 1681-1681/com.example.admin.myhome E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: com.example.admin.myhome, PID: 1681
                                                                        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.admin.myhome/com.example.admin.myhome.MainActivity}: android.database.sqlite.SQLiteException: no such table: Ip_channal_Table (code 1): , while compiling: SELECT ID as _id, IP_Address from Ip_channal_Table
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2348)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2410)
                                                                            at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4019)
                                                                            at android.app.ActivityThread.access$900(ActivityThread.java:151)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1319)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:135)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5345)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:947)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:742)
                                                                         Caused by: android.database.sqlite.SQLiteException: no such table: Ip_channal_Table (code 1): , while compiling: SELECT ID as _id, IP_Address from Ip_channal_Table
                                                                            at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                            at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                            at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                            at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                            at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                            at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
                                                                            at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                                                                            at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
                                                                            at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
                                                                            at com.example.admin.myhome.IP_Channal_DB.getAll_IP(NoteHolder.java:52)
                                                                            at com.example.admin.myhome.MainActivity$override.onCreate(MainActivity.java:131)
                                                                            at com.example.admin.myhome.MainActivity$override.access$dispatch(MainActivity.java)
                                                                            at com.example.admin.myhome.MainActivity.onCreate(MainActivity.java:0)
                                                                            at android.app.Activity.performCreate(Activity.java:6012)
                                                                            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2410)
                                                                            at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4019)
                                                                            at android.app.ActivityThread.access$900(ActivityThread.java:151)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1319)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:135)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5345)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:372)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:947)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:742)

Body:
I developed a sample project which i used in my main application. I hope that helps you too.

DataBaseHandler.java

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;

public class DataBaseHandler extends SQLiteOpenHelper {

    public String BooksTable="Books";
    public String Book_Id="id";
    public String BookAuther="BookAuther";
    public String BookTitle="BookTitle";

    private  final int DB_Version=1;
    public DataBaseHandler(Context context,String DBName,int DBVersion){
        super(context, DBName,null,DBVersion);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("Create Table " + BooksTable + "(" + Book_Id + " INTEGER PRIMARY KEY, " + BookAuther + " Text, " + BookTitle + " Text);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
    public void addBook(Book book){
        SQLiteDatabase db=this.getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put(Book_Id,book.getId());
        cv.put(BookAuther,book.getAuthor());
        cv.put(BookTitle,book.getTitle());

        db.insert(BooksTable, null, cv);
        db.close();
    }

    public ArrayList<Book> fetchAllBooks(){
        ArrayList<Book> booksList = new ArrayList<Book>();
        SQLiteDatabase db=this.getReadableDatabase();
        Cursor c= db.query(BooksTable, null, null, null, null, null, null);
        c.moveToFirst();
        while (!c.isAfterLast()){
            Book book = new Book();
            book.setId(c.getInt(0));
            book.setAuthor(c.getString(1));
            book.setTitle(c.getString(2));
            booksList.add(book);
            c.moveToNext();
        }
        db.close();
        return booksList;
    }
}

Book.java

public class Book {
private int id;
private String author;
private String title;

public void setId(int id) {
    this.id = id;
}

public void setAuthor(String author) {
    this.author = author;
}

public void setTitle(String title) {
    this.title = title;
}

public int getId() {
    return id;
}

public String getAuthor() {
    return author;
}

public String getTitle() {
      return title;
    }
}

MainActivity.java

DataBaseHandler db=new DataBaseHandler(getApplicationContext(),"DB_Name",1);
Book book=new Book();
book.setId(1);
book.setTitle("My Title");
book.setAuthor("Name of Author");
db.addBook(book);


问:
JpaRepository findAll() returns empty result
JpaRepository findAll() method returns empty result. I am trying to implement rest service by using Spring-boot, h2 database and jpa.

Here is my schema.sql

```<code>CREATE TABLE IF NOT EXISTS `City` (
  `city_id` bigint(20) NOT NULL auto_increment,
  `city_name` varchar(200) NOT NULL,
PRIMARY KEY (`city_id`));
</code>```

My data.sql file includes :

```<code>INSERT INTO City (city_id,city_name) VALUES(1,'EDE');
INSERT INTO City (city_id,city_name) VALUES(2,'DRUTEN');
INSERT INTO City (city_id,city_name) VALUES(3,'DELFT');
</code>```

The City entity :

```<code>import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "City")
public class City {

  @Id
  @GeneratedValue
  @Column(name = "city_id")
  private Long cityId;

  @Column(name = "city_name")
  private String cityName;

  public Long getCityId() {
    return cityId;
  }

  public void setCityId(Long cityId) {
    this.cityId = cityId;
  }

  public String getCityName() {
    return cityName;
  }

  public void setCityName(String cityName) {
    this.cityName = cityName;
  }

}
</code>```

The JpaRepository interface:

```<code>import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CityRepository extends JpaRepository<City, Long> {

    @Override
    List<City> findAll();
}
</code>```

And here is my Contoller class

```<code>@RestController
@RequestMapping("/city")
public class CityController {
    @Autowired
    private CityRepository cityRepository;

    @RequestMapping(method = RequestMethod.GET, value = "/all")
    public List<City> getAllCityList(){
        return cityRepository.findAll();
    }
}
</code>```

What am I doing wrong here? The reference documentation : Spring doc

答:
As far as i understood, you want to execute sql scripts on application startup and after that use Hibernate? Well, you have to use one of the options mentioned here, and set spring.jpa.hibernate.ddl-auto=none.The explanation is given there.

Good luck

Body:
JpaRepository findAll() method returns empty result. I am trying to implement rest service by using Spring-boot, h2 database and jpa.

Here is my schema.sql

CREATE TABLE IF NOT EXISTS `City` (
  `city_id` bigint(20) NOT NULL auto_increment,
  `city_name` varchar(200) NOT NULL,
PRIMARY KEY (`city_id`));

My data.sql file includes :

INSERT INTO City (city_id,city_name) VALUES(1,'EDE');
INSERT INTO City (city_id,city_name) VALUES(2,'DRUTEN');
INSERT INTO City (city_id,city_name) VALUES(3,'DELFT');

The City entity :

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "City")
public class City {

  @Id
  @GeneratedValue
  @Column(name = "city_id")
  private Long cityId;

  @Column(name = "city_name")
  private String cityName;

  public Long getCityId() {
    return cityId;
  }

  public void setCityId(Long cityId) {
    this.cityId = cityId;
  }

  public String getCityName() {
    return cityName;
  }

  public void setCityName(String cityName) {
    this.cityName = cityName;
  }

}

The JpaRepository interface:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CityRepository extends JpaRepository<City, Long> {

    @Override
    List<City> findAll();
}

And here is my Contoller class

@RestController
@RequestMapping("/city")
public class CityController {
    @Autowired
    private CityRepository cityRepository;

    @RequestMapping(method = RequestMethod.GET, value = "/all")
    public List<City> getAllCityList(){
        return cityRepository.findAll();
    }
}

What am I doing wrong here? The reference documentation : Spring doc


问:
Can I replace this interpolate function with the one offered by opencv?
I'm have this function taken from here:

```<code>bool interpolate(const Mat &im, float ofsx, float ofsy, float a11, float a12, float a21, float a22, Mat &res)
{
   bool ret = false;
   // input size (-1 for the safe bilinear interpolation)
   const int width = im.cols-1;
   const int height = im.rows-1;
   // output size
   const int halfWidth  = res.cols >> 1;
   const int halfHeight = res.rows >> 1;
   int dim = res.rows * res.cols;
   float *out = res.ptr<float>(0);
   for (int j=-halfHeight; j<=halfHeight; ++j)
   {
      const float rx = ofsx + j * a12;
      const float ry = ofsy + j * a22;
      #pragma omp simd
      for(int i=-halfWidth; i<=halfWidth; ++i)
      {
         float wx = rx + i * a11;
         float wy = ry + i * a21;
         const int x = (int) floor(wx);
         const int y = (int) floor(wy);
         if (x >= 0 && y >= 0 && x < width && y < height)
         {
            // compute weights
            wx -= x; wy -= y;
            // bilinear interpolation
            *out++ =
               (1.0f - wy) * ((1.0f - wx) * im.at<float>(y,x)   + wx * im.at<float>(y,x+1)) +
               (       wy) * ((1.0f - wx) * im.at<float>(y+1,x) + wx * im.at<float>(y+1,x+1));
         } else {
            *out++ = 0;
            ret =  true; // touching boundary of the input
         }
      }
   }
   return ret;
}
</code>```

I don't know what interpolation is in details, but looking at this opencv page, it seems that it's a bilinear interpolation using INTER_LINEAR. The point is that I don't know how to call an equivalent opencv function for the code above.

This function is called in two different points here.

答:
You can't solely apply simple an interpolation using openCV,
it has to be part of image processing operation, e.g warp or resize operation.

I think you are trying to vectorize a warp affine, the easiest way and most efficient code on Intel platform would be to use IPP.
Otherwise, I'd let Opencv Warp affine do the job.

Body:
I'm have this function taken from here:

bool interpolate(const Mat &im, float ofsx, float ofsy, float a11, float a12, float a21, float a22, Mat &res)
{
   bool ret = false;
   // input size (-1 for the safe bilinear interpolation)
   const int width = im.cols-1;
   const int height = im.rows-1;
   // output size
   const int halfWidth  = res.cols >> 1;
   const int halfHeight = res.rows >> 1;
   int dim = res.rows * res.cols;
   float *out = res.ptr<float>(0);
   for (int j=-halfHeight; j<=halfHeight; ++j)
   {
      const float rx = ofsx + j * a12;
      const float ry = ofsy + j * a22;
      #pragma omp simd
      for(int i=-halfWidth; i<=halfWidth; ++i)
      {
         float wx = rx + i * a11;
         float wy = ry + i * a21;
         const int x = (int) floor(wx);
         const int y = (int) floor(wy);
         if (x >= 0 && y >= 0 && x < width && y < height)
         {
            // compute weights
            wx -= x; wy -= y;
            // bilinear interpolation
            *out++ =
               (1.0f - wy) * ((1.0f - wx) * im.at<float>(y,x)   + wx * im.at<float>(y,x+1)) +
               (       wy) * ((1.0f - wx) * im.at<float>(y+1,x) + wx * im.at<float>(y+1,x+1));
         } else {
            *out++ = 0;
            ret =  true; // touching boundary of the input
         }
      }
   }
   return ret;
}

I don't know what interpolation is in details, but looking at this opencv page, it seems that it's a bilinear interpolation using INTER_LINEAR. The point is that I don't know how to call an equivalent opencv function for the code above.

This function is called in two different points here.


问:
What's the difference between "_" and "__" in Objective-C?
I've read that _ (underscore) is only used to tell that the variable/method/class is for the API use only and should not be used by other programmers.

What about __ (double underscore)?

In this example __block BOOL found = NO;

From the Apple Docs about Block Objects.

Also, can anyone help me understand the concept of pointer-to-pointers?
**var
I've read some answers about it but didn't really get it. When and how should I use it?

答:
Single underscore is traditionally used for private API (methods and sometimes ivars). Their main purpose is to prevent name collisions.

__block is a keyword for the new blocks API. In general, double underscore keywords are for the compiler.

For pointers to pointers the NSError is a good example: When a method wants to return a new NSError object as part of its parameters (not return value), you need a pointer to a variable of type NSError *, so that you can assign it. With a simple pointer you could only access the object, but not (re-)assign it.


问:
How to use substring in VBA ? (Convert a String to a decimal with substring)
I tried to pull a String from a cell in an Excel table and convert it into a Double. Afterwards, I wanted to format the Double as a currency and remove the currency sign.

Unfortunately, I am always getting the error

Run-time error 424: Object Required

```<code>Dim price_right_str As String
Dim price_right As Double

price_right_str = ActiveSheet.Cells(a, b_new).Value
price_right = CDbl(Val(price_right_str))
price_right_str = FormatCurrency(price_right, 2)
price_right_str = price.Substring(1, (Len(price_right_str) - 1))
</code>```

I'd appreciate any proposal for a better solution. All I need is an output which is (theoretically) a price without the currency symbol.

答:
VBA does not have String function called SubString(). Instead use Right(str), Mid(str) or Left(str).

As @YowE3K mentioned in the comments, this is the answer:
price_right_str = Mid(price_right_str, 2) or price_right_str = Left(price_right_str, Len(price_right_str) - 1)

ContentLicense: CC BY-SA 4.0

Body:
I tried to pull a String from a cell in an Excel table and convert it into a Double. Afterwards, I wanted to format the Double as a currency and remove the currency sign.

Unfortunately, I am always getting the error

Run-time error 424: Object Required

Dim price_right_str As String
Dim price_right As Double

price_right_str = ActiveSheet.Cells(a, b_new).Value
price_right = CDbl(Val(price_right_str))
price_right_str = FormatCurrency(price_right, 2)
price_right_str = price.Substring(1, (Len(price_right_str) - 1))

I'd appreciate any proposal for a better solution. All I need is an output which is (theoretically) a price without the currency symbol.


问:
can't find an easy way to display ion-radio icon to the left
In the ion-icon directive, the icon for the selected item is displayed at the right by defualt, there is an easy way to displayed at the left instead? thank you</p>

```<code> <ion-list>
        <ion-radio ng-model="choice" icon="icon ion-android-pin" ng-value="'A'">Bogotá</ion-radio>
        <ion-radio ng-model="choice" icon="icon ion-android-pin" ng-value="'B'">Cali</ion-radio>
        <ion-radio ng-model="choice" icon="icon ion-android-pin" ng-value="'C'">Medellin</ion-radio>
        <ion-radio ng-model="choice" icon="icon ion-android-pin" ng-value="'D'">Bucaramanga</ion-radio>
        <ion-radio ng-model="choice" icon="icon ion-android-pin" ng-value="'E'">Cartagena</ion-radio>
        <ion-radio ng-model="choice" icon="icon ion-android-pin" ng-value="'F'">San Andres</ion-radio>
</ion-list>
</code>```

答: put an item-left attribute to <ion-radio> element. </p>

Body:
In the ion-icon directive, the icon for the selected item is displayed at the right by defualt, there is an easy way to displayed at the left instead? thank you

 <ion-list>
        <ion-radio ng-model="choice" icon="icon ion-android-pin" ng-value="'A'">Bogotá</ion-radio>
        <ion-radio ng-model="choice" icon="icon ion-android-pin" ng-value="'B'">Cali</ion-radio>
        <ion-radio ng-model="choice" icon="icon ion-android-pin" ng-value="'C'">Medellin</ion-radio>
        <ion-radio ng-model="choice" icon="icon ion-android-pin" ng-value="'D'">Bucaramanga</ion-radio>
        <ion-radio ng-model="choice" icon="icon ion-android-pin" ng-value="'E'">Cartagena</ion-radio>
        <ion-radio ng-model="choice" icon="icon ion-android-pin" ng-value="'F'">San Andres</ion-radio>
</ion-list>


问:
Sorting points clockwise given triangulated mesh
Given a triangulated mesh (no self intersection, no holes, possibly concave) represented as an unordered list of triangles (list of 3 vertices) or rectangles (list of 4 vertices), i.e.

```<code>[
    [[x1, y1], [x2, y2], [x3, y3]],
    [[x4, y4], [x5, y5], [x6, y6], [x7, y7],
    ....
]
</code>```

How can I sort the vertices in a clockwise order?

答:
You can sort by angle.

There are different implementations, like you can use atan2() in C++ to calculate the angle of each vertex and sort them along.

In case they have same angle, you can sort them by distance to the origin to break tie.

Body:
Given a triangulated mesh (no self intersection, no holes, possibly concave) represented as an unordered list of triangles (list of 3 vertices) or rectangles (list of 4 vertices), i.e.

[
    [[x1, y1], [x2, y2], [x3, y3]],
    [[x4, y4], [x5, y5], [x6, y6], [x7, y7],
    ....
]

How can I sort the vertices in a clockwise order?


问:
I have two tables Table1 and Table2 :I want to swap name column value From Table1 to Table2 and Table2 to Table1
[Below are two tables Table1 and Table2][1]

Table1:Column names id,name
Table2:Column names id,name

After the swap ,the name column data of Table1 will reflect in Table2 and name of Table2 will reflect in Table1.

I tried to resolve the issue using below query:

```<code>update table1 t set t.name=replace(t.name,(select name from T1 where T1.id=t.id),(select name from T2 where T2.id = t.id));
update table2 t set t.name=replace(t.name,(select name from T2 where T2.id=t.id),(select name from T1 where T1.id = t.id));
</code>```

But,it is not giving correct result.

答:
You can't do this in a single pass, as you are overwriting the values you want to move in the next step.  Here's a solution using a temporary table:</p>

```<code>SELECT * INTO #temp FROM table1;
UPDATE t1 SET name = t2.name FROM table1 t1 INNER JOIN table2 t2 ON t2.id = t1.id;
UPDATE t2 SET name = t1.name FROM #temp t1 INNER JOIN table2 t2 ON t2.id = t1.id;
DROP TABLE #temp;
</code>```

Body:
[Below are two tables Table1 and Table2][1]

Table1:Column names id,name
Table2:Column names id,name

After the swap ,the name column data of Table1 will reflect in Table2 and name of Table2 will reflect in Table1.

I tried to resolve the issue using below query:

update table1 t set t.name=replace(t.name,(select name from T1 where T1.id=t.id),(select name from T2 where T2.id = t.id));
update table2 t set t.name=replace(t.name,(select name from T2 where T2.id=t.id),(select name from T1 where T1.id = t.id));

But,it is not giving correct result.

Body:
You can't do this in a single pass, as you are overwriting the values you want to move in the next step.  Here's a solution using a temporary table:

SELECT * INTO #temp FROM table1;
UPDATE t1 SET name = t2.name FROM table1 t1 INNER JOIN table2 t2 ON t2.id = t1.id;
UPDATE t2 SET name = t1.name FROM #temp t1 INNER JOIN table2 t2 ON t2.id = t1.id;
DROP TABLE #temp;


问:
Saving data to a file vs. saving it to MySQL DB
Using a PHP script I need to update a number every 5 seconds while somebody is on my page. So let's say I have 300 visitors, each one spending about 1 minute on the page and every 5 seconds they stay on the page the number will be changed...which is a total of 3600 changes per minute. I would prefer to update the number in my MySQL database, except I'm not sure if it's not too inefficient to have so many MySQL connections (just for the one number change), when I could just change the number in a file.

P.S.: I have no idea weather 3600 connections/minute is a high number or not, but what about this case in general, considering an even higher number of visitors. What is the most efficient way to do this?

答:
Don't even think about trying to handle this with files - its just not going to work unless you build a lock queue manager - and if you're going to all that trouble you might as well use the daemon to manage the value rather than just queue locks.

Using a DBMS is the simplest approach.

For a more efficient but massively more esoteric approach, write a single-threaded socket server daemon and have the clients connect to that. (there's a lib here for doing the socket handling, and there's a PEAR class for running PHP as a daemon)


问:
Need Help! Angular 2 File/Image upload via API
I'm stack around uploading image/file using Angular2. I don't like to add any plugins to upload file in angular2. Is there any simple way to upload image via API using Angular2 without any third party extension ?

NB: i am using laravel as server

答:
Here's what needs to be done/considered when uploading Images (or files) from Angular 2 to a server.

Create an Image upload component using the following elements.
The template:

      {{buttonCaption}}
      <input
        type="file"
        accept="image/*"
        (change)="fileChange(input.files)"
        #input>

{{dropBoxMessage}}

Please upload a file less than 2 MB.

```
</div>
</div>
</p>

<ol start="2">
<li>Your component class, which needs to be exported. </li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component, Input, Output, EventEmitter } from '@angular/core';
import { ImageService, Header } from "../../../services/content/image.service";

export class FileHolder {
    public serverResponse: any;
    public pending: boolean = false;
    constructor(public src: string, public file: File) { }
}

@Component({
    selector: 'image-upload',
    templateUrl: "app/components/controls/image-upload/image-upload.component.html",
    styles: [
        `
.image-upload {
  --common-radius: 3px;
  --active-color: #33CC99;
  position: relative;
  border-radius: var(--common-radius);
  border: #d0d0d0 dashed 1px;
  font-family: sans-serif;
}

.file-is-over {
  border-color: var(--active-color);
  border-style: solid;
}

.hr-inline-group:after {
  display: table;
  clear: both;
  content: "";
}

.file-upload {
  padding: 16px;
  background-color: #f8f8f8;
}

.drag-box-message {
  float: left;
  display: inline-block;
  margin-left: 12px;
  padding-top: 14px;
  color: #9b9b9b;
  font-weight: 600;
}

label.upload-button input[type=file] {
  display: none;
  position: fixed;
  top: -99999px;
}

.upload-button {
  cursor: pointer;
  background-color: var(--active-color);
  padding: 10px;
  color: white;
  font-size: 1.25em;
  font-weight: 500;
  text-transform: uppercase;
  display: inline-block;
  float: left;

  -webkit-box-shadow: 2px 2px 4px 0px rgba(148,148,148,0.6);
  -moz-box-shadow: 2px 2px 4px 0px rgba(148,148,148,0.6);
  box-shadow: 2px 2px 4px 0px rgba(148,148,148,0.6);
}

.upload-button:active span{
  position: relative;
  display: block;
  top: 1px;
}

.image-container {
  background-color: #fdfdfd;
  padding: 0 10px 0 10px;
}

.image {
  float: left;
  display: inline-block;
  margin: 6px;
  width: 86px;
  height: 86px;
  background: center center no-repeat;
  background-size: contain;
  position: relative;
}

.x-mark {
  width: 20px;
  height: 20px;
  text-align: center;
  cursor: pointer;
  border-radius: 2px;
  float: right;
  background-color: black;
  opacity: .7;
  color: white;
  margin: 2px;
}

.close {
  width: 20px;
  height: 20px;
  opacity: .7;
  position: relative;
  padding-right: 3px;
}
.x-mark:hover .close {
  opacity: 1;
}
.close:before, .close:after {
  border-radius: 2px;
  position: absolute;
  content: '';
  height: 16px;
  width: 2px;
  top: 2px;
  background-color: #FFFFFF;
}

.close:before {
  transform: rotate(45deg);
}

.close:after {
  transform: rotate(-45deg);
}

.loading-overlay {
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
  background-color: black;
  opacity: .7;
}

.spinningCircle {
  height: 30px;
  width: 30px;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
  border-radius: 50%;
  border: 3px solid rgba(255, 255, 255, 0);
  border-top: 3px solid white;
  border-right: 3px solid white;
  -webkit-animation: spinner 2s infinite cubic-bezier(0.085, 0.625, 0.855, 0.360);
  animation: spinner 2s infinite cubic-bezier(0.085, 0.625, 0.855, 0.360);
}

@-webkit-keyframes spinner {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

@keyframes spinner {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);

  }
}
`
    ]
})
export class ImageUploadComponent {
    @Input() max: number = 100;
    @Input() url: string;
    @Input() headers: Header[];
    @Input() preview: boolean = true;

    @Output()
    isPending: EventEmitter<boolean> = new EventEmitter<boolean>();
    @Output()
    onFileUploadFinish: EventEmitter<FileHolder> = new EventEmitter<FileHolder>();
    @Output()
    onRemove: EventEmitter<FileHolder> = new EventEmitter<FileHolder>();

    private files: FileHolder[] = [];

    private fileCounter: number = 0;
    private pendingFilesCounter: number = 0;
    private fileSizeExceeded: boolean = false;

    private isFileOver: boolean = false;

    @Input()
    buttonCaption: string = "Select Images";
    @Input()
    dropBoxMessage: string = "Drop your images here!";

    constructor(private imageService: ImageService) { }

    ngOnInit() {
        this.imageService.setUrl(this.url);
    }

    fileChange(files) {
        let remainingSlots = this.countRemainingSlots();
        let filesToUploadNum = files.length > remainingSlots ? remainingSlots : files.length;

        if (this.url && filesToUploadNum != 0) {
            this.isPending.emit(true);
        }

        this.fileCounter += filesToUploadNum;

        this.uploadFiles(files, filesToUploadNum);
    }

    private uploadFiles(files, filesToUploadNum) {
        for (let i = 0; i < filesToUploadNum; i++) {
            let file = files[i];

            console.log('FILE SIZE: ', file.size);

            if (file.size > 3000000) {
                this.fileSizeExceeded = true;
                return;
            }

            let img = document.createElement('img');
            img.src = window.URL.createObjectURL(file);

            let reader = new FileReader();
            reader.addEventListener('load', (event: any) => {
                let fileHolder: FileHolder = new FileHolder(event.target.result, file);

                fileHolder.serverResponse = `good boy: ${i}`;

                this.uploadSingleFile(fileHolder);

                this.files.push(fileHolder);

            }, false);

            reader.readAsDataURL(file);
        }
    }

    private uploadSingleFile(fileHolder: FileHolder) {
        if (this.url) {
            this.pendingFilesCounter++;
            fileHolder.pending = true;

            this.imageService.postImage(fileHolder.file, this.headers).subscribe(response => {
                fileHolder.serverResponse = response;
                this.onFileUploadFinish.emit(fileHolder);
                fileHolder.pending = false;
                if (--this.pendingFilesCounter == 0) {
                    this.isPending.emit(false);
                }
            });

        } else {
            this.onFileUploadFinish.emit(fileHolder);
        }
    }

    private deleteFile(file: FileHolder): void {
        let index = this.files.indexOf(file);
        this.files.splice(index, 1);
        this.fileCounter--;

        this.onRemove.emit(file);
    }

    fileOver(isOver) {
        this.isFileOver = isOver;
    }

    private countRemainingSlots() {
        return this.max - this.fileCounter;
    }
}</code>```

Import it into your App module, and include it as part of the declarations.

Now this component can be used anywhere to upload an image.

This component takes care of adding request headers that can contain authentication tokens that will be used by the server.

Hope that helps.

Body:
Here's what needs to be done/considered when uploading Images (or files) from Angular 2 to a server.

Create an Image upload component using the following elements.
The template:

<div class="image-upload"
     fileDrop
     [accept]="['image/*']"
     (isFileOver)="fileOver($event)"
     (fileDrop)="fileChange($event)"
     [ngClass]="{'file-is-over': isFileOver}"
>
  <div class="file-upload hr-inline-group">
    <label class="upload-button">
      <span>{{buttonCaption}}</span>
      <input
        type="file"
        accept="image/*"
        (change)="fileChange(input.files)"
        #input>
    </label>

    <div class="drag-box-message">{{dropBoxMessage}}</div>
  </div>
    <div *ngIf="fileSizeExceeded" class="drag-box-message">
        <p>Please upload a file less than 2 MB.</p>
    </div>

  <div *ngIf="preview" class="image-container hr-inline-group">
    <div
      class="image"
      *ngFor="let file of files"
      [ngStyle]="{'background-image': 'url('+ file.src +')'}"
    >
      <div *ngIf="file.pending" class="loading-overlay">
        <div class="spinningCircle"></div>
      </div>
      <div *ngIf="!file.pending" class="x-mark" (click)="deleteFile(file)">
        <span class="close"></span>
      </div>
    </div>
  </div>
</div>

Your component class, which needs to be exported.

import { Component, Input, Output, EventEmitter } from '@angular/core';
import { ImageService, Header } from "../../../services/content/image.service";

export class FileHolder {
    public serverResponse: any;
    public pending: boolean = false;
    constructor(public src: string, public file: File) { }
}

@Component({
    selector: 'image-upload',
    templateUrl: "app/components/controls/image-upload/image-upload.component.html",
    styles: [
        `
.image-upload {
  --common-radius: 3px;
  --active-color: #33CC99;
  position: relative;
  border-radius: var(--common-radius);
  border: #d0d0d0 dashed 1px;
  font-family: sans-serif;
}

.file-is-over {
  border-color: var(--active-color);
  border-style: solid;
}

.hr-inline-group:after {
  display: table;
  clear: both;
  content: "";
}

.file-upload {
  padding: 16px;
  background-color: #f8f8f8;
}

.drag-box-message {
  float: left;
  display: inline-block;
  margin-left: 12px;
  padding-top: 14px;
  color: #9b9b9b;
  font-weight: 600;
}

label.upload-button input[type=file] {
  display: none;
  position: fixed;
  top: -99999px;
}

.upload-button {
  cursor: pointer;
  background-color: var(--active-color);
  padding: 10px;
  color: white;
  font-size: 1.25em;
  font-weight: 500;
  text-transform: uppercase;
  display: inline-block;
  float: left;

  -webkit-box-shadow: 2px 2px 4px 0px rgba(148,148,148,0.6);
  -moz-box-shadow: 2px 2px 4px 0px rgba(148,148,148,0.6);
  box-shadow: 2px 2px 4px 0px rgba(148,148,148,0.6);
}

.upload-button:active span{
  position: relative;
  display: block;
  top: 1px;
}

.image-container {
  background-color: #fdfdfd;
  padding: 0 10px 0 10px;
}

.image {
  float: left;
  display: inline-block;
  margin: 6px;
  width: 86px;
  height: 86px;
  background: center center no-repeat;
  background-size: contain;
  position: relative;
}

.x-mark {
  width: 20px;
  height: 20px;
  text-align: center;
  cursor: pointer;
  border-radius: 2px;
  float: right;
  background-color: black;
  opacity: .7;
  color: white;
  margin: 2px;
}

.close {
  width: 20px;
  height: 20px;
  opacity: .7;
  position: relative;
  padding-right: 3px;
}
.x-mark:hover .close {
  opacity: 1;
}
.close:before, .close:after {
  border-radius: 2px;
  position: absolute;
  content: '';
  height: 16px;
  width: 2px;
  top: 2px;
  background-color: #FFFFFF;
}

.close:before {
  transform: rotate(45deg);
}

.close:after {
  transform: rotate(-45deg);
}

.loading-overlay {
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
  background-color: black;
  opacity: .7;
}

.spinningCircle {
  height: 30px;
  width: 30px;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
  border-radius: 50%;
  border: 3px solid rgba(255, 255, 255, 0);
  border-top: 3px solid white;
  border-right: 3px solid white;
  -webkit-animation: spinner 2s infinite cubic-bezier(0.085, 0.625, 0.855, 0.360);
  animation: spinner 2s infinite cubic-bezier(0.085, 0.625, 0.855, 0.360);
}

@-webkit-keyframes spinner {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

@keyframes spinner {
  0% {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);

  }
}
`
    ]
})
export class ImageUploadComponent {
    @Input() max: number = 100;
    @Input() url: string;
    @Input() headers: Header[];
    @Input() preview: boolean = true;

    @Output()
    isPending: EventEmitter<boolean> = new EventEmitter<boolean>();
    @Output()
    onFileUploadFinish: EventEmitter<FileHolder> = new EventEmitter<FileHolder>();
    @Output()
    onRemove: EventEmitter<FileHolder> = new EventEmitter<FileHolder>();

    private files: FileHolder[] = [];

    private fileCounter: number = 0;
    private pendingFilesCounter: number = 0;
    private fileSizeExceeded: boolean = false;

    private isFileOver: boolean = false;

    @Input()
    buttonCaption: string = "Select Images";
    @Input()
    dropBoxMessage: string = "Drop your images here!";

    constructor(private imageService: ImageService) { }

    ngOnInit() {
        this.imageService.setUrl(this.url);
    }

    fileChange(files) {
        let remainingSlots = this.countRemainingSlots();
        let filesToUploadNum = files.length > remainingSlots ? remainingSlots : files.length;

        if (this.url && filesToUploadNum != 0) {
            this.isPending.emit(true);
        }

        this.fileCounter += filesToUploadNum;

        this.uploadFiles(files, filesToUploadNum);
    }

    private uploadFiles(files, filesToUploadNum) {
        for (let i = 0; i < filesToUploadNum; i++) {
            let file = files[i];

            console.log('FILE SIZE: ', file.size);

            if (file.size > 3000000) {
                this.fileSizeExceeded = true;
                return;
            }

            let img = document.createElement('img');
            img.src = window.URL.createObjectURL(file);

            let reader = new FileReader();
            reader.addEventListener('load', (event: any) => {
                let fileHolder: FileHolder = new FileHolder(event.target.result, file);

                fileHolder.serverResponse = `good boy: ${i}`;

                this.uploadSingleFile(fileHolder);

                this.files.push(fileHolder);

            }, false);

            reader.readAsDataURL(file);
        }
    }

    private uploadSingleFile(fileHolder: FileHolder) {
        if (this.url) {
            this.pendingFilesCounter++;
            fileHolder.pending = true;

            this.imageService.postImage(fileHolder.file, this.headers).subscribe(response => {
                fileHolder.serverResponse = response;
                this.onFileUploadFinish.emit(fileHolder);
                fileHolder.pending = false;
                if (--this.pendingFilesCounter == 0) {
                    this.isPending.emit(false);
                }
            });

        } else {
            this.onFileUploadFinish.emit(fileHolder);
        }
    }

    private deleteFile(file: FileHolder): void {
        let index = this.files.indexOf(file);
        this.files.splice(index, 1);
        this.fileCounter--;

        this.onRemove.emit(file);
    }

    fileOver(isOver) {
        this.isFileOver = isOver;
    }

    private countRemainingSlots() {
        return this.max - this.fileCounter;
    }
}

Import it into your App module, and include it as part of the declarations.

Now this component can be used anywhere to upload an image.

This component takes care of adding request headers that can contain authentication tokens that will be used by the server.

Hope that helps.


问:
Dot at start and end using regex
Hello I am trying to validate an input using regex in Javascript, what my requirement is that I can have at most one dot ('.') in the string and that can't be at the start and end.
I got a solution in

```<code>/^[^\.].*[^\.]$/;
</code>```

But the issue is input "x" is considered as invalid
valid inputs are like
"x", "x.x", "xx.x" , "x.xx" like so
invalid like ".x" and "x."

Title: Dot at start and end using regex

Body:
Hello I am trying to validate an input using regex in Javascript, what my requirement is that I can have at most one dot ('.') in the string and that can't be at the start and end.
I got a solution in

/^[^\.].*[^\.]$/;

But the issue is input "x" is considered as invalid
valid inputs are like
"x", "x.x", "xx.x" , "x.xx" like so
invalid like ".x" and "x."

Body:
How about

/^(?!\.)[^\.]*\.?[^\.]*(?!\.).$/