问:
Export pandas Dataframe or numpy array to MySQL
I'm using python to export a large matrixs (shape around 3000 * 3000) into MySQL.

Right now I'm using MySQLdb to insert those values but it's too troublesome and too inefficient. Here is my code:

```<code># -*- coding:utf-8 -*-

import MySQLdb
import numpy as np
import pandas as pd
import time

def feature_to_sql_format(df):
    df = df.fillna(value='')
    columns = list(df.columns)
    index = list(df.index)
    index_sort = np.reshape([[int(i)] * len(columns) for i in index], (-1)).tolist()
    columns_sort = (columns * len(index))
    values_sort = df.values.reshape(-1).tolist()
    return str(zip(index_sort, columns_sort, values_sort))[1: -1].replace("'NULL'", 'NULL')

if __name__ == '__main__':
    t1 = time.clock()
    df = pd.read_csv('C:\\test.csv', header=0, index_col=0)
    output_string = feature_to_sql_format(df)
    sql_CreateTable = 'USE derivative_pool;DROP TABLE IF exists test1;' \
                      'CREATE TABLE test1(date INT NOT NULL, code VARCHAR(12) NOT NULL, value FLOAT NULL);'
    sql_Insert = 'INSERT INTO test (date,code,value) VALUES ' + output_string + ';'
    con = MySQLdb.connect(......)
    cur = con.cursor()
    cur.execute(sql_CreateTable)
    cur.close()
    cur = con.cursor()
    cur.execute(sql_Insert)
    cur.close()
    con.commit()
    con.close()
    t2 = time.clock()
    print t2 - t1
</code>```

And it consumes around 274 seconds totally.

I was wondering if there is a simplier way to do this, I thought of export the matrix to csv and then use LOAD DATA INFILE to import, but it's also too complicated.

I noticed that in pandas documentation pandas dataframe has a function to_sql, and in version 0.14 you can set the 'flavor' to 'mysql', that is:

```<code>df.to_sql(con=con, name=name, flavor='mysql')
</code>```

But now my pandas version is 0.19.2 and the flavor is reduced to only 'sqlite'...... And I still tried to use

```<code>df.to_sql(con=con, name=name, flavor='sqlite')
</code>```

and it gives me an error.

Is there any convinient way to do this?

答:
Later pandas versions support SQLalchemy connectors instead of flavor = "mysql"

First, install dependencies:

```<code>pip install mysql-connector-python-rf==2.2.2
pip install MySQL-python==1.2.5
pip install SQLAlchemy==1.1.1
</code>```

Then create the engine:

```<code>from sqlalchemy import create_engine
connection_string= "mysql+mysqlconnector://root:@localhost/MyDatabase"
engine = create_engine(connection_string)
</code>```

Then you can use df.to_sql(...):

```<code>df.to_sql('MyTable', engine)
</code>```

Here are some things you can do in MYSQL to speed up your data load:

```<code>SET FOREIGN_KEY_CHECKS = 0;
SET UNIQUE_CHECKS = 0;
SET SESSION tx_isolation='READ-UNCOMMITTED';
SET sql_log_bin = 0;
#LOAD DATA LOCAL INFILE....
SET UNIQUE_CHECKS = 1;
SET FOREIGN_KEY_CHECKS = 1;
SET SESSION tx_isolation='READ-REPEATABLE';
</code>```

Body:
I'm using python to export a large matrixs (shape around 3000 * 3000) into MySQL.

Right now I'm using MySQLdb to insert those values but it's too troublesome and too inefficient. Here is my code:

# -*- coding:utf-8 -*-

import MySQLdb
import numpy as np
import pandas as pd
import time

def feature_to_sql_format(df):
    df = df.fillna(value='')
    columns = list(df.columns)
    index = list(df.index)
    index_sort = np.reshape([[int(i)] * len(columns) for i in index], (-1)).tolist()
    columns_sort = (columns * len(index))
    values_sort = df.values.reshape(-1).tolist()
    return str(zip(index_sort, columns_sort, values_sort))[1: -1].replace("'NULL'", 'NULL')

if __name__ == '__main__':
    t1 = time.clock()
    df = pd.read_csv('C:\\test.csv', header=0, index_col=0)
    output_string = feature_to_sql_format(df)
    sql_CreateTable = 'USE derivative_pool;DROP TABLE IF exists test1;' \
                      'CREATE TABLE test1(date INT NOT NULL, code VARCHAR(12) NOT NULL, value FLOAT NULL);'
    sql_Insert = 'INSERT INTO test (date,code,value) VALUES ' + output_string + ';'
    con = MySQLdb.connect(......)
    cur = con.cursor()
    cur.execute(sql_CreateTable)
    cur.close()
    cur = con.cursor()
    cur.execute(sql_Insert)
    cur.close()
    con.commit()
    con.close()
    t2 = time.clock()
    print t2 - t1

And it consumes around 274 seconds totally.

I was wondering if there is a simplier way to do this, I thought of export the matrix to csv and then use LOAD DATA INFILE to import, but it's also too complicated.

I noticed that in pandas documentation pandas dataframe has a function to_sql, and in version 0.14 you can set the 'flavor' to 'mysql', that is:

df.to_sql(con=con, name=name, flavor='mysql')

But now my pandas version is 0.19.2 and the flavor is reduced to only 'sqlite'...... And I still tried to use

df.to_sql(con=con, name=name, flavor='sqlite')

and it gives me an error.

Is there any convinient way to do this?

Body:
Later pandas versions support SQLalchemy connectors instead of flavor = "mysql"

First, install dependencies:

pip install mysql-connector-python-rf==2.2.2
pip install MySQL-python==1.2.5
pip install SQLAlchemy==1.1.1

Then create the engine:

from sqlalchemy import create_engine
connection_string= "mysql+mysqlconnector://root:@localhost/MyDatabase"
engine = create_engine(connection_string)

Then you can use df.to_sql(...):

df.to_sql('MyTable', engine)

Here are some things you can do in MYSQL to speed up your data load:

SET FOREIGN_KEY_CHECKS = 0;
SET UNIQUE_CHECKS = 0;
SET SESSION tx_isolation='READ-UNCOMMITTED';
SET sql_log_bin = 0;
#LOAD DATA LOCAL INFILE....
SET UNIQUE_CHECKS = 1;
SET FOREIGN_KEY_CHECKS = 1;
SET SESSION tx_isolation='READ-REPEATABLE';


来源: stackexchange

问:
CoreServices.h file not found in portaudio build on macOS 10.11 Xcode 8.0
This is called though cocoa.h and foundation.h, then NSURLError.h.  Not sure why this compiler error just came up when I added portaudio and some other needed frameworks.  The error first comes from some existing code.  Indeed, there is no CoreServices/CoreServices.h anywhere on the whole system.  Do I need to update Xcode?

I found an Apple help answer that said "Those are not makefile directives. How are you trying to build it? Most projects like this come with "configure" scripts that you just need to run from the command line. The only thing you need from Xcode are the Command Line Tools."  I don't know what this means or how to do this.

I did run the port audio/configure terminal script, but saw nothing about CoreServices.h being generated.  Where does this need to come from?

Thanks.

I further note that in the CoreServices frameworks directory associated with the Xcode project, there is a terminal file called "CoreServices" that when run, generates the error "CoreServices.framework/Versions/A/CoreServices: cannot execute binary file"  .  What could it be missing?

答:
It's hard to answer your question in this specific case but:

I believe that CoreServices.h can be found at /System/Library/Frameworks/CoreServices.framework/Versions/A/Headers/CoreServices.h, is it not the case on your machine? If not, you might have to re-install Xcode

To install PortAudio, you can also use brew with the command brew install portaudio and then link your project with its headers and libs (/usr/local/Cellar/portaudio/19.6.0/include and /usr/local/Cellar/portaudio/19.6.0/lib) in your Xcode project (under the tab Build Phases > Link Binary with Libraries). That might be the easiest option.

ContentLicense: CC BY-SA 3.0


问:
How to change the font of a string in gui and then change it back again to normal
Hello fellow programmers across the world I am currently having a problem with one of my frames in my GUI. I have managed to change the font of my messeges to itallic and the color to grey and i have set my textfield to editable(true). The problem is that when I delete the string in gray and italic and try to write something useful in the textfield, rather that plain font and a color of black for the string it always comes out italic and gray. Is there any way that a string in a text message can change font and color and then then next string you write to have the normal font and black color? Would appreciate any sugggestions at this point. Here is my code:</p>

```<code>void makeSecondFrame(){
       frame2 = new JFrame("Step one!Vertification!");
       Container contentPane2 = frame2.getContentPane();
       JLabel label2 = new JLabel("Welcome to step 1 of our algorithm, Verification!" + "To varify yourself of owning an account please enter the following:");
       JLabel label3 = new JLabel("First Name:");
       JLabel label4 = new JLabel("Middle Name:");
       JLabel label5 = new JLabel("Surname:");
       JLabel label6 = new JLabel("Account Number:");
       JLabel label7 = new JLabel ("Registration Number:");
       firstName = new TextField("Enter your name here");
       firstName.setForeground(Color.gray);
       firstName.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
       firstName.setEditable(true);
       middleName = new TextField("Enter your middle name here");
       middleName.setForeground(Color.gray);
       middleName.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
       middleName.setEditable(true);
       surname = new TextField("Enter your surname here");
       surname.setForeground(Color.gray);
       surname.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
       surname.setEditable(true);
       accountNumber = new TextField("Enter your main account number");
       accountNumber.setForeground(Color.gray);
       accountNumber.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
       accountNumber.setEditable(true);
       registrationNumber = new TextField("Enter your registration number");
       registrationNumber.setForeground(Color.gray);
       registrationNumber.setFont(new java.awt.Font("Arail", Font.ITALIC, 12));
       registrationNumber.setEditable(true);
       JPanel p2 = new JPanel(new GridLayout(1,1));
       p2.add(label2);
       contentPane2.add(p2, BorderLayout.NORTH);
       JPanel p3 = new JPanel(new GridLayout(10,1));
       p3.add(label3);
       p3.add(firstName);
       p3.add(label4);
       p3.add(middleName);
       p3.add(label5);
       p3.add(surname);
       p3.add(label7);
       p3.add(registrationNumber);
       p3.add(label6);
       p3.add(accountNumber);
       contentPane2.add(p3, BorderLayout.WEST);
       JButton next = new JButton("Next!");
       next.addActionListener(this);
       JButton cancel = new JButton("Cancel");
       cancel.addActionListener(this);
       JPanel p4 = new JPanel(new GridLayout(1,1));
       p4.add(next);
       p4.add(cancel);
       contentPane2.add(p4, BorderLayout.SOUTH);
       frame2.pack();
       frame2.setVisible(true);
   }
</code>```

答:
You need to act on an appropriate action on the JTextField. The best I can think of is the FocusListener.focusGained():

```<code>   firstName = new TextField("Enter your name here");
   firstName.setForeground(Color.gray);
   firstName.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
   firstName.setEditable(true);
   firstName.addFocuListener(new FocusAdapter(){
      @Overwrite
      public void focusGained(FocusEvent e){
         firstName.setText("");// remove help message, will also remove previously entered text!
         firstName.setFont(new JTextField().getFont()); // reset to default
      }
   }
</code>```

Well that did remove the helper message – Христо Петков

as I mentioned...

and I want to keep it – Христо Петков

Then you might want to use the other method in the FocusListener interface too:

```<code>      @Overwrite
      public void focusLost(FocusEvent e){
         if(userDidNotEnterTextIn(firstName){ // hopefully you know how to find out...
            firstName.setText("Enter your name here");
         // do formatting again
         }
      }
</code>```

Body:
Hello fellow programmers across the world I am currently having a problem with one of my frames in my GUI. I have managed to change the font of my messeges to itallic and the color to grey and i have set my textfield to editable(true). The problem is that when I delete the string in gray and italic and try to write something useful in the textfield, rather that plain font and a color of black for the string it always comes out italic and gray. Is there any way that a string in a text message can change font and color and then then next string you write to have the normal font and black color? Would appreciate any sugggestions at this point. Here is my code:

void makeSecondFrame(){
       frame2 = new JFrame("Step one!Vertification!");
       Container contentPane2 = frame2.getContentPane();
       JLabel label2 = new JLabel("Welcome to step 1 of our algorithm, Verification!" + "To varify yourself of owning an account please enter the following:");
       JLabel label3 = new JLabel("First Name:");
       JLabel label4 = new JLabel("Middle Name:");
       JLabel label5 = new JLabel("Surname:");
       JLabel label6 = new JLabel("Account Number:");
       JLabel label7 = new JLabel ("Registration Number:");
       firstName = new TextField("Enter your name here");
       firstName.setForeground(Color.gray);
       firstName.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
       firstName.setEditable(true);
       middleName = new TextField("Enter your middle name here");
       middleName.setForeground(Color.gray);
       middleName.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
       middleName.setEditable(true);
       surname = new TextField("Enter your surname here");
       surname.setForeground(Color.gray);
       surname.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
       surname.setEditable(true);
       accountNumber = new TextField("Enter your main account number");
       accountNumber.setForeground(Color.gray);
       accountNumber.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
       accountNumber.setEditable(true);
       registrationNumber = new TextField("Enter your registration number");
       registrationNumber.setForeground(Color.gray);
       registrationNumber.setFont(new java.awt.Font("Arail", Font.ITALIC, 12));
       registrationNumber.setEditable(true);
       JPanel p2 = new JPanel(new GridLayout(1,1));
       p2.add(label2);
       contentPane2.add(p2, BorderLayout.NORTH);
       JPanel p3 = new JPanel(new GridLayout(10,1));
       p3.add(label3);
       p3.add(firstName);
       p3.add(label4);
       p3.add(middleName);
       p3.add(label5);
       p3.add(surname);
       p3.add(label7);
       p3.add(registrationNumber);
       p3.add(label6);
       p3.add(accountNumber);
       contentPane2.add(p3, BorderLayout.WEST);
       JButton next = new JButton("Next!");
       next.addActionListener(this);
       JButton cancel = new JButton("Cancel");
       cancel.addActionListener(this);
       JPanel p4 = new JPanel(new GridLayout(1,1));
       p4.add(next);
       p4.add(cancel);
       contentPane2.add(p4, BorderLayout.SOUTH);
       frame2.pack();
       frame2.setVisible(true);
   }

Body:
You need to act on an appropriate action on the JTextField. The best I can think of is the FocusListener.focusGained():

   firstName = new TextField("Enter your name here");
   firstName.setForeground(Color.gray);
   firstName.setFont(new java.awt.Font("Arial", Font.ITALIC, 12));
   firstName.setEditable(true);
   firstName.addFocuListener(new FocusAdapter(){
      @Overwrite
      public void focusGained(FocusEvent e){
         firstName.setText("");// remove help message, will also remove previously entered text!
         firstName.setFont(new JTextField().getFont()); // reset to default
      }
   }

Well that did remove the helper message – Христо Петков

as I mentioned...

and I want to keep it – Христо Петков

Then you might want to use the other method in the FocusListener interface too:

      @Overwrite
      public void focusLost(FocusEvent e){
         if(userDidNotEnterTextIn(firstName){ // hopefully you know how to find out...
            firstName.setText("Enter your name here");
         // do formatting again
         }
      }


问:
FRDM-K64F OpenSDA mbed firmware install - files to big
I am learning how to use the FRDM-K64F in the context of evaluating Orange France "IoT Soft box" starter kit.

I am using a Macintosh, but tried also on a Windows PC and had the same problem. I keep the board reset button pressed and then plug it into the USB port & release reset, the board shows up as "BOOTLOADER" USB drive. I did compile the "blinky" example on developer.mbed.com and copied that into the BOOTLOADER USB drive - and it works.

Unfortunately, almost everything else I try to do fails:

Whenever I try to install bigger fields I compiled (in particular the very first example provided by Orange in their kit (https://github.com/Orange-OpenSource/LiveObjects-iotSoftbox-mqtt-mbed/blob/master/docs/liveobjects_starterkit_mbedOS_v1.2.pdf) I get an error message saying that there is not enough free space on the drive.

```<code>$ sudo mount -u -w -o sync /Volumes/BOOTLOADER ; cp -X Downloads/liveobjects-iotsoftbox-greenhouseK64F.bin /Volumes/BOOTLOADER/
cp: /Volumes/BOOTLOADER/liveobjects-iotsoftbox-greenhouseK64F.bin: No space left on device
</code>```

but also the SDA fimrware upgrade from the mbed guide https://developer.mbed.org/handbook/Firmware-FRDM-K64F

I keep getting an error message telling me that there is "not enough free space on the drive."

Several questions:
- Could this be related to me having maybe installed a wrong firmware or bootloader on the board?
- How can I verify what bootloader/firmware is installed?
- How can I know if the board is using OpenSDA mode?
- What types of files are automatically installed when they are drag-and-drop / copied into the USB BOOTLOADER filesystem - is this working only with ".bin" or also with ".zip" and others ?

Thanks

答:
The FRDM board is already set in "BOOTLOADER" mode.
So you crushed the bootloader firmware when you downloaded the 'blinkly' program. Now you have to reload the bootloader firmware on your board.

Find how to do it here:

https://developer.mbed.org/handbook/Firmware-FRDM-K64F

```<code>sudo mount -u -w -o sync /Volumes/BOOTLOADER ; cp -X <bootloader firmware > /Volumes/BOOTLOADER/
</code>```

You can find the bootloader on the NXP website:

http://www.nxp.com/products/software-and-tools/run-time-software/kinetis-software-and-tools/ides-for-kinetis-mcus/opensda-serial-and-debug-adapter:OPENSDA?tid=vanOpenSDA#FRDM-K64F

Then restart your board in "NORMAL" mode. It must appear as MBED (instead of BOOTLOADER)

After what you can load your .bin file by using "drag and drop" on your board. You can also launch a hyperterminal on the COM port of the FRDM board to follow step by step your program.

Body:
I am learning how to use the FRDM-K64F in the context of evaluating Orange France "IoT Soft box" starter kit.

I am using a Macintosh, but tried also on a Windows PC and had the same problem. I keep the board reset button pressed and then plug it into the USB port & release reset, the board shows up as "BOOTLOADER" USB drive. I did compile the "blinky" example on developer.mbed.com and copied that into the BOOTLOADER USB drive - and it works.

Unfortunately, almost everything else I try to do fails:

Whenever I try to install bigger fields I compiled (in particular the very first example provided by Orange in their kit (https://github.com/Orange-OpenSource/LiveObjects-iotSoftbox-mqtt-mbed/blob/master/docs/liveobjects_starterkit_mbedOS_v1.2.pdf) I get an error message saying that there is not enough free space on the drive.

$ sudo mount -u -w -o sync /Volumes/BOOTLOADER ; cp -X Downloads/liveobjects-iotsoftbox-greenhouseK64F.bin /Volumes/BOOTLOADER/
cp: /Volumes/BOOTLOADER/liveobjects-iotsoftbox-greenhouseK64F.bin: No space left on device

but also the SDA fimrware upgrade from the mbed guide https://developer.mbed.org/handbook/Firmware-FRDM-K64F

I keep getting an error message telling me that there is "not enough free space on the drive."

Several questions:
- Could this be related to me having maybe installed a wrong firmware or bootloader on the board?
- How can I verify what bootloader/firmware is installed?
- How can I know if the board is using OpenSDA mode?
- What types of files are automatically installed when they are drag-and-drop / copied into the USB BOOTLOADER filesystem - is this working only with ".bin" or also with ".zip" and others ?

Thanks

Body:
The FRDM board is already set in "BOOTLOADER" mode.
So you crushed the bootloader firmware when you downloaded the 'blinkly' program. Now you have to reload the bootloader firmware on your board.

Find how to do it here:

https://developer.mbed.org/handbook/Firmware-FRDM-K64F

sudo mount -u -w -o sync /Volumes/BOOTLOADER ; cp -X <bootloader firmware > /Volumes/BOOTLOADER/

You can find the bootloader on the NXP website:

http://www.nxp.com/products/software-and-tools/run-time-software/kinetis-software-and-tools/ides-for-kinetis-mcus/opensda-serial-and-debug-adapter:OPENSDA?tid=vanOpenSDA#FRDM-K64F

Then restart your board in "NORMAL" mode. It must appear as MBED (instead of BOOTLOADER)

After what you can load your .bin file by using "drag and drop" on your board. You can also launch a hyperterminal on the COM port of the FRDM board to follow step by step your program.


问:
Method not found on runtime
I have an ASP.Net c# project trying to access methods in a class in another project. It's working for first half of methods in the class but not for the other half of the methods in the class which I recently added. They compile, but they throw a method not found exception at run-time.

Does anyone have any ideas I could try? I've tried:

recreating the .sln file

Subbing in another class library project, which I know works. It appears that the error is in my main project that calls the method in the other project.

答:
My case was a little variation of the other ones here ; but it might help someone.
I just added an optional argument in a library and got that message from the GUI using the library.

The problem was caused by the GUI and one of its libraries referencing the same library but one was not up to date.

I have

GUI referencing LibA and LibZ

LibA referencing LibZ

So I just removed all "bin" and "obj" folders of both LibA and GUI, made sure to have the updated DLL of LibZ in both, and everything worked again.

Title: Method not found on runtime


问:
magento customize onepage checkout process
I want to customize the onepage checkout process in magento in such a way that step 1 consists of shopping cart if user logged in otherwise login form and after login cart should be there. now in 2nd step; there should be input form of billing information, shipping information, payment methods options and shipping options. now in 3rd step, order review and 4th would be payment and last one would be Receipt and place order.</p>

答: You're basically rewriting the onepage checkout at this point. The controlling JS opcheckout.js is written pretty tightly for the existing process, so don't count on being able to reuse it in any sane manner. That said, if you take a look at the actual model/block classes (Mage_Checkout_Model_Type_Onepage and Mage_Checkout_Block_Onepage, respectively) they're actually pretty cleanly written, so you should be able to steal them for your version.

ContentLicense: CC BY-SA 2.5


问:
Problems adding multiple KafkaListenerContainerFactories
Hi I'm currently dabbling in Spring Kafka and succeeded in adding a single KafkaListenerContainerFactory to my listener. Now I'd like to add multiple KafkaListenerContainerFactorys (One for a topic that will have messages in json, another one for strings). See code below:

```<code>@EnableKafka
@Configuration
public class KafkaConsumersConfig {

    private final KafkaConfiguration kafkaConfiguration;

    @Autowired
    public KafkaConsumersConfig(KafkaConfiguration kafkaConfiguration) {
        this.kafkaConfiguration = kafkaConfiguration;
    }

    @Bean
    public KafkaListenerContainerFactory<?> kafkaJsonListenerContainerFactory(){
        ConcurrentKafkaListenerContainerFactory<String,Record> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(jsonConsumerFactory());
        factory.setConcurrency(3);
        factory.setAutoStartup(true);
        return factory;
    }

    @Bean
    public ConsumerFactory<String,Record> jsonConsumerFactory(){
        JsonDeserializer<Record> jsonDeserializer = new JsonDeserializer<>(Record.class);
        return new DefaultKafkaConsumerFactory<>(jsonConsumerConfigs(),new StringDeserializer(), jsonDeserializer);
    }

    @Bean
    public Map<String,Object> jsonConsumerConfigs(){
        Map<String,Object> propsMap = new HashMap<>();
        propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,  kafkaConfiguration.getBrokerAddress());
        propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaConfiguration.getJsonGroupId());
        propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, kafkaConfiguration.getAutoCommit());
        propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, kafkaConfiguration.getAutoCommitInterval());
        propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, kafkaConfiguration.getSessionTimeout());
        return propsMap;
    }
    @Bean
    public KafkaListenerContainerFactory<?> kafkaFileListenerContainerFactory(){
        ConcurrentKafkaListenerContainerFactory<String,String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(fileConsumerFactory());
        factory.setConcurrency(3);
        factory.setAutoStartup(true);
        return factory;
    }

    @Bean
    public ConsumerFactory<String,String> fileConsumerFactory(){
        return new DefaultKafkaConsumerFactory<>(fileConsumerConfigs());
    }

    @Bean
    public Map<String,Object> fileConsumerConfigs(){
        Map<String,Object> propsMap = new HashMap<>();
        propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,  kafkaConfiguration.getBrokerAddress());
        propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaConfiguration.getFileGroupId());
        propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, kafkaConfiguration.getAutoCommit());
        propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, kafkaConfiguration.getAutoCommitInterval());
        propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, kafkaConfiguration.getSessionTimeout());
        return propsMap;
    }
}
</code>```

Running this gives me the following error:

```<code>Description:

Parameter 1 of method kafkaListenerContainerFactory in org.springframework.boot.autoconfigure.kafka.KafkaAnnotationDrivenConfiguration required a bean of type 'org.springframework.kafka.core.ConsumerFactory' that could not be found.
    - Bean method 'kafkaConsumerFactory' in 'KafkaAutoConfiguration' not loaded because @ConditionalOnMissingBean (types: org.springframework.kafka.core.ConsumerFactory; SearchStrategy: all) found beans 'jsonConsumerFactory', 'fileConsumerFactory'

Action:

Consider revisiting the conditions above or defining a bean of type 'org.springframework.kafka.core.ConsumerFactory' in your configuration.
</code>```

What am I doing wrong?

答:
Looks like you are not going to rely on the Spring Boot's Kafka Auto Configuration.

Spring Boot provides in the KafkaAutoConfiguration:

```<code>@Bean
@ConditionalOnMissingBean(ConsumerFactory.class)
public ConsumerFactory<?, ?> kafkaConsumerFactory() {
</code>```

Since you have jsonConsumerFactory and fileConsumerFactory, they override that one provided by the auto-config.

But on the other hand, in the KafkaAnnotationDrivenConfiguration, non of your factories can be applied:

```<code>@Bean
@ConditionalOnMissingBean(name = "kafkaListenerContainerFactory")
public ConcurrentKafkaListenerContainerFactory<?, ?> kafkaListenerContainerFactory(
        ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
        ConsumerFactory<Object, Object> kafkaConsumerFactory) {
</code>```

Because your ConsumerFactory beans are not of ConsumerFactory<Object, Object> type.

So:

Just exclude KafkaAutoConfiguration from the Spring Boot auto configuration by adding the following to the application properties file:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration

or rename one of your KafkaListenerContainerFactory beans to the kafkaListenerContainerFactory to override it in the Boot

or make one of the ConsumerFactory beans as a ConsumerFactory<Object, Object> type.

Body:
Hi I'm currently dabbling in Spring Kafka and succeeded in adding a single KafkaListenerContainerFactory to my listener. Now I'd like to add multiple KafkaListenerContainerFactorys (One for a topic that will have messages in json, another one for strings). See code below:

@EnableKafka
@Configuration
public class KafkaConsumersConfig {

    private final KafkaConfiguration kafkaConfiguration;

    @Autowired
    public KafkaConsumersConfig(KafkaConfiguration kafkaConfiguration) {
        this.kafkaConfiguration = kafkaConfiguration;
    }

    @Bean
    public KafkaListenerContainerFactory<?> kafkaJsonListenerContainerFactory(){
        ConcurrentKafkaListenerContainerFactory<String,Record> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(jsonConsumerFactory());
        factory.setConcurrency(3);
        factory.setAutoStartup(true);
        return factory;
    }

    @Bean
    public ConsumerFactory<String,Record> jsonConsumerFactory(){
        JsonDeserializer<Record> jsonDeserializer = new JsonDeserializer<>(Record.class);
        return new DefaultKafkaConsumerFactory<>(jsonConsumerConfigs(),new StringDeserializer(), jsonDeserializer);
    }

    @Bean
    public Map<String,Object> jsonConsumerConfigs(){
        Map<String,Object> propsMap = new HashMap<>();
        propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,  kafkaConfiguration.getBrokerAddress());
        propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaConfiguration.getJsonGroupId());
        propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, kafkaConfiguration.getAutoCommit());
        propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, kafkaConfiguration.getAutoCommitInterval());
        propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, kafkaConfiguration.getSessionTimeout());
        return propsMap;
    }
    @Bean
    public KafkaListenerContainerFactory<?> kafkaFileListenerContainerFactory(){
        ConcurrentKafkaListenerContainerFactory<String,String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(fileConsumerFactory());
        factory.setConcurrency(3);
        factory.setAutoStartup(true);
        return factory;
    }

    @Bean
    public ConsumerFactory<String,String> fileConsumerFactory(){
        return new DefaultKafkaConsumerFactory<>(fileConsumerConfigs());
    }

    @Bean
    public Map<String,Object> fileConsumerConfigs(){
        Map<String,Object> propsMap = new HashMap<>();
        propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,  kafkaConfiguration.getBrokerAddress());
        propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, kafkaConfiguration.getFileGroupId());
        propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, kafkaConfiguration.getAutoCommit());
        propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, kafkaConfiguration.getAutoCommitInterval());
        propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, kafkaConfiguration.getSessionTimeout());
        return propsMap;
    }
}

Running this gives me the following error:

Description:

Parameter 1 of method kafkaListenerContainerFactory in org.springframework.boot.autoconfigure.kafka.KafkaAnnotationDrivenConfiguration required a bean of type 'org.springframework.kafka.core.ConsumerFactory' that could not be found.
    - Bean method 'kafkaConsumerFactory' in 'KafkaAutoConfiguration' not loaded because @ConditionalOnMissingBean (types: org.springframework.kafka.core.ConsumerFactory; SearchStrategy: all) found beans 'jsonConsumerFactory', 'fileConsumerFactory'

Action:

Consider revisiting the conditions above or defining a bean of type 'org.springframework.kafka.core.ConsumerFactory' in your configuration.

What am I doing wrong?

Body:
Looks like you are not going to rely on the Spring Boot's Kafka Auto Configuration.

Spring Boot provides in the KafkaAutoConfiguration:

@Bean
@ConditionalOnMissingBean(ConsumerFactory.class)
public ConsumerFactory<?, ?> kafkaConsumerFactory() {

Since you have jsonConsumerFactory and fileConsumerFactory, they override that one provided by the auto-config.

But on the other hand, in the KafkaAnnotationDrivenConfiguration, non of your factories can be applied:

@Bean
@ConditionalOnMissingBean(name = "kafkaListenerContainerFactory")
public ConcurrentKafkaListenerContainerFactory<?, ?> kafkaListenerContainerFactory(
        ConcurrentKafkaListenerContainerFactoryConfigurer configurer,
        ConsumerFactory<Object, Object> kafkaConsumerFactory) {

Because your ConsumerFactory beans are not of ConsumerFactory<Object, Object> type.

So:

Just exclude KafkaAutoConfiguration from the Spring Boot auto configuration by adding the following to the application properties file:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration

or rename one of your KafkaListenerContainerFactory beans to the kafkaListenerContainerFactory to override it in the Boot

or make one of the ConsumerFactory beans as a ConsumerFactory<Object, Object> type.


问:
Discarding Returned Variables
I am only interested in one of the things returned by a Python method. I recall reading that there is a convention for how to indicate throw-away variables, but now I can't find any reference to it. Basically, I want to do the following:

-, var, - = three_things()

where three_things() returns a list of three objects, and var gets the only one of them that I want to keep. What is the "right" way to indicate throw-away variables?

答:
The convention is to give throwaways the name _.

```<code>>>> _, x, _ = [1,2,3]
>>> x
2
</code>```

(Somewhat) more realistic example:

```<code>>>> lst = [(1,2,'a'), (3,4,'b')]
>>> for num1, num2, _ in lst:
...     num1 + num2
...
3
7
</code>```

(In an interactive interpreter session, _ also stores the last eval'd value.)

Title: Discarding Returned Variables

Body:
The convention is to give throwaways the name _.

>>> _, x, _ = [1,2,3]
>>> x
2

(Somewhat) more realistic example:

>>> lst = [(1,2,'a'), (3,4,'b')]
>>> for num1, num2, _ in lst:
...     num1 + num2
...
3
7

(In an interactive interpreter session, _ also stores the last eval'd value.)


问:
Jboss eap 7.0 - How to do JNDI lookup for jms in jboss 7
We are migrating application from Jboss 5 to jboss 7. In this we need to change JNDI lookup of JMS.

In Jboss 5 it is done by -

```<code>     InitialContext ic = new InitialContext();
    Object obj = ic.lookup(listenerName);
    // listenerName has our destination queue name
</code>```

In Jboss 7 we are trying as -

```<code>        Properties jndiProps = new Properties();
        jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
        jndiProps.put(Context.PROVIDER_URL,"http-remoting://localhost:8080");
        jndiProps.put("jboss.naming.client.ejb.context", new Boolean(true));
        InitialContext ic = new InitialContext(jndiProps);
        Object obj = ic.lookup("jms/queue/" + listenerName);
</code>```

In Standalone-full.xml we added destination queue -

```<code><jms-queue name="CORESERVICES.DEMO_QUEUE" entries="java:/jms/queue/CORESERVICES.DEMO_QUEUE"/>
</code>```

We are getting these errors -

```<code>2017-03-31 15:44:04,056 INFO  [com.praval.services.core.msg.MessageRouterMDB] (Thread-16 (ActiveMQ-client-global-threads-1938238098)) PRAVAL jmsQueueName is CORESERVICES.DEMO_QUEUE
2017-03-31 15:44:04,195 INFO  [org.jboss.ejb.client.remoting] (Remoting "config-based-naming-client-endpoint" task-6) EJBCLIENT000017: Received server version 2 and marshalling strategies [river]
2017-03-31 15:44:04,203 INFO  [org.jboss.ejb.client.remoting] (Thread-16 (ActiveMQ-client-global-threads-1938238098)) EJBCLIENT000013: Successful version handshake completed for receiver context EJBReceiverContext{clientContext=org.jboss.ejb.client.EJBClientContext@13279398, receiver=Remoting connection EJB receiver [connection=Remoting connection <3a06c684>,channel=jboss.ejb,nodename=pravalsharma]} on channel Channel ID 45654a55 (outbound) of Remoting connection 12baae23 to localhost/127.0.0.1:8080
2017-03-31 15:44:04,302 WARNING [com.praval.services.core.msg.MessageRouterMDB] (Thread-16 (ActiveMQ-client-global-threads-1938238098)) javax.naming.NameNotFoundException: jms/queue/CORESERVICES.DEMO_QUEUE -- service jboss.naming.context.java.jboss.exported.jms.queue."CORESERVICES.DEMO_QUEUE"
at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBasedNamingStore.java:106)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:207)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:184)
at org.jboss.naming.remote.protocol.v1.Protocol$1.handleServerMessage(Protocol.java:127)
at org.jboss.naming.remote.protocol.v1.RemoteNamingServerV1$MessageReciever$1.run(RemoteNamingServerV1.java:73)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code>```

答:
If the JMS is on the jboss that is running the code then you can use the following code in CDI

```<code>@Singleton
@Transactional(value = TxType.REQUIRES_NEW)
public class ServiceLayer implements IServiceLayer {
    @Resource(mappedName = "ConnectionFactory")
    public ConnectionFactory localQueueFactory;

    @Resource(mappedName = "jms/queue/CORESERVICES.DEMO_QUEUE")
    public Queue queue;

    public void sendMessage2(String msge) throws Exception {
        MessageProducer qsender = null;
        Session qsession = null;
        Connection qcon = null;
        try {
            qcon = this.localQueueFactory.createConnection();
            qsession = qcon.createSession(true, QueueSession.AUTO_ACKNOWLEDGE);
            qsender = qsession.createProducer(queue);
            int i = 1;
            for (int j = 0; j < i; j++) {
                TextMessage tm = qsession.createTextMessage(msge);
                qsender.send(tm);
                System.out.println("Message [" + tm.getText() + "] sent to Queue: " + queue.getQueueName());
            }

        } catch (Exception e) {
            System.out.println("Exception : " + e.getMessage());
            e.printStackTrace();
        } finally {
            qcon.close();
        }
    }
}
</code>```

If you are not using CDI or EJBs then you dont have to provide environment variables for the context, you can just do the following

```<code>public final static String QUEUE = "jms/queue/CORESERVICES.DEMO_QUEUE";
public void sendMessage() throws Exception {

            // Define queue
            QueueSender qsender = null;
            QueueSession qsession = null;
            QueueConnection qcon = null;
            try {
                InitialContext ctx = new InitialContext();//It will take the initial context of the container on which the code is deployed.

                QueueConnectionFactory qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
                qcon = qconFactory.createQueueConnection();

                qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                Queue queue = (Queue) ctx.lookup(QUEUE);

                TextMessage msg = qsession.createTextMessage();
                msg.setText("<xml>textMessage" + "</xml>");

                qsender = qsession.createSender(queue);
                qsender.send(msg);

                System.out.println("Message [" + msg.getText() + "] sent to Queue: " + QUEUE);
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                if (qsender != null)
                    qsender.close();
                if (qsession != null)
                    qsession.close();
                if (qcon != null)
                    qcon.close();
            }
        }
</code>```

Body:
We are migrating application from Jboss 5 to jboss 7. In this we need to change JNDI lookup of JMS.

In Jboss 5 it is done by -

     InitialContext ic = new InitialContext();
    Object obj = ic.lookup(listenerName);
    // listenerName has our destination queue name

In Jboss 7 we are trying as -

        Properties jndiProps = new Properties();
        jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
        jndiProps.put(Context.PROVIDER_URL,"http-remoting://localhost:8080");
        jndiProps.put("jboss.naming.client.ejb.context", new Boolean(true));
        InitialContext ic = new InitialContext(jndiProps);
        Object obj = ic.lookup("jms/queue/" + listenerName);

In Standalone-full.xml we added destination queue -

<jms-queue name="CORESERVICES.DEMO_QUEUE" entries="java:/jms/queue/CORESERVICES.DEMO_QUEUE"/>

We are getting these errors -

2017-03-31 15:44:04,056 INFO  [com.praval.services.core.msg.MessageRouterMDB] (Thread-16 (ActiveMQ-client-global-threads-1938238098)) PRAVAL jmsQueueName is CORESERVICES.DEMO_QUEUE
2017-03-31 15:44:04,195 INFO  [org.jboss.ejb.client.remoting] (Remoting "config-based-naming-client-endpoint" task-6) EJBCLIENT000017: Received server version 2 and marshalling strategies [river]
2017-03-31 15:44:04,203 INFO  [org.jboss.ejb.client.remoting] (Thread-16 (ActiveMQ-client-global-threads-1938238098)) EJBCLIENT000013: Successful version handshake completed for receiver context EJBReceiverContext{clientContext=org.jboss.ejb.client.EJBClientContext@13279398, receiver=Remoting connection EJB receiver [connection=Remoting connection <3a06c684>,channel=jboss.ejb,nodename=pravalsharma]} on channel Channel ID 45654a55 (outbound) of Remoting connection 12baae23 to localhost/127.0.0.1:8080
2017-03-31 15:44:04,302 WARNING [com.praval.services.core.msg.MessageRouterMDB] (Thread-16 (ActiveMQ-client-global-threads-1938238098)) javax.naming.NameNotFoundException: jms/queue/CORESERVICES.DEMO_QUEUE -- service jboss.naming.context.java.jboss.exported.jms.queue."CORESERVICES.DEMO_QUEUE"
at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBasedNamingStore.java:106)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:207)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:184)
at org.jboss.naming.remote.protocol.v1.Protocol$1.handleServerMessage(Protocol.java:127)
at org.jboss.naming.remote.protocol.v1.RemoteNamingServerV1$MessageReciever$1.run(RemoteNamingServerV1.java:73)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Body:
If the JMS is on the jboss that is running the code then you can use the following code in CDI

@Singleton
@Transactional(value = TxType.REQUIRES_NEW)
public class ServiceLayer implements IServiceLayer {
    @Resource(mappedName = "ConnectionFactory")
    public ConnectionFactory localQueueFactory;

    @Resource(mappedName = "jms/queue/CORESERVICES.DEMO_QUEUE")
    public Queue queue;

    public void sendMessage2(String msge) throws Exception {
        MessageProducer qsender = null;
        Session qsession = null;
        Connection qcon = null;
        try {
            qcon = this.localQueueFactory.createConnection();
            qsession = qcon.createSession(true, QueueSession.AUTO_ACKNOWLEDGE);
            qsender = qsession.createProducer(queue);
            int i = 1;
            for (int j = 0; j < i; j++) {
                TextMessage tm = qsession.createTextMessage(msge);
                qsender.send(tm);
                System.out.println("Message [" + tm.getText() + "] sent to Queue: " + queue.getQueueName());
            }

        } catch (Exception e) {
            System.out.println("Exception : " + e.getMessage());
            e.printStackTrace();
        } finally {
            qcon.close();
        }
    }
}

If you are not using CDI or EJBs then you dont have to provide environment variables for the context, you can just do the following

public final static String QUEUE = "jms/queue/CORESERVICES.DEMO_QUEUE";
public void sendMessage() throws Exception {

            // Define queue
            QueueSender qsender = null;
            QueueSession qsession = null;
            QueueConnection qcon = null;
            try {
                InitialContext ctx = new InitialContext();//It will take the initial context of the container on which the code is deployed.

                QueueConnectionFactory qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
                qcon = qconFactory.createQueueConnection();

                qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                Queue queue = (Queue) ctx.lookup(QUEUE);

                TextMessage msg = qsession.createTextMessage();
                msg.setText("<xml>textMessage" + "</xml>");

                qsender = qsession.createSender(queue);
                qsender.send(msg);

                System.out.println("Message [" + msg.getText() + "] sent to Queue: " + QUEUE);
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                if (qsender != null)
                    qsender.close();
                if (qsession != null)
                    qsession.close();
                if (qcon != null)
                    qcon.close();
            }
        }


问:
TYPO3 FAL translation fails in Extbase Extension
I'm using TYPO3 7.6.14 and my Website is bilingual 'english' and 'japanese'. My editors translate all english content, also FAL-Metadata for images, like 'description', 'alt-text' and 'title', s. screenshot.

The whole page is translated, only the FAL-data from images fails (s. screenshot). I don't know why? Do anyone see my fault?
I am grateful for any help because I simply do not know what it is ...  Thanks.

Here's the TCA

```<code>...
'additional_information' => array(
            'exclude' => 1,
            'label' => 'LLL:EXT:products/Resources/Private/Language/locallang_db.xlf:tx_products_domain_model_product.additional_information',
            'config' => \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::getFileFieldTCAConfig(
                'additional_information',
                array(
                    'appearance' => array(
                        'createNewRelationLinkTitle' => 'LLL:EXT:cms/locallang_ttc.xlf:images.addFileReference'
                    ),
                    'foreign_types' => array(
                        '0' => array(
                            'showitem' => '
                            --palette--;LLL:EXT:lang/locallang_tca.xlf:sys_file_reference.imageoverlayPalette;imageoverlayPalette,
                            --palette--;;filePalette'
                        ),
                        \TYPO3\CMS\Core\Resource\File::FILETYPE_IMAGE => array(
                            'showitem' => '
                            --palette--;LLL:EXT:lang/locallang_tca.xlf:sys_file_reference.imageoverlayPalette;imageoverlayPalette,
                            --palette--;;filePalette'
                        )
                    ),
                    'maxitems' => 10
                ),
                $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext']
            ),
        ),
...
</code>```

and the Fluid-Template (s. caption: photo.originalResource.properties.description)

```<code><f:for each="{product.additionalInformation}" as="photo" iteration="iterator">
          <div class="column">
          <a class="lightbox2" href="{f:uri.image(src: photo.originalResource.publicUrl, width: 1024)}" data-lightbox="{product.uid}" title="{photo.originalResource.properties.description}">
          <f:image src="{photo.originalResource.originalFile.uid}" alt="" />
            <span class="caption">                                            {photo.originalResource.properties.description}</span>
             </a>
       </div>
</f:for>
</code>```

Frontend Output:

答:
Try to replace <f:image src="{photo.originalResource.originalFile.uid}" alt="" /> with <f:image image="{photo}" alt="" />.

It can be that FAL translations a not properly supported. Please have a look at the news extension from Georg Ringer. If it is not working there, then it is not working at all.

Body:
I'm using TYPO3 7.6.14 and my Website is bilingual 'english' and 'japanese'. My editors translate all english content, also FAL-Metadata for images, like 'description', 'alt-text' and 'title', s. screenshot.

The whole page is translated, only the FAL-data from images fails (s. screenshot). I don't know why? Do anyone see my fault?
I am grateful for any help because I simply do not know what it is ...  Thanks.

Here's the TCA

...
'additional_information' => array(
            'exclude' => 1,
            'label' => 'LLL:EXT:products/Resources/Private/Language/locallang_db.xlf:tx_products_domain_model_product.additional_information',
            'config' => \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::getFileFieldTCAConfig(
                'additional_information',
                array(
                    'appearance' => array(
                        'createNewRelationLinkTitle' => 'LLL:EXT:cms/locallang_ttc.xlf:images.addFileReference'
                    ),
                    'foreign_types' => array(
                        '0' => array(
                            'showitem' => '
                            --palette--;LLL:EXT:lang/locallang_tca.xlf:sys_file_reference.imageoverlayPalette;imageoverlayPalette,
                            --palette--;;filePalette'
                        ),
                        \TYPO3\CMS\Core\Resource\File::FILETYPE_IMAGE => array(
                            'showitem' => '
                            --palette--;LLL:EXT:lang/locallang_tca.xlf:sys_file_reference.imageoverlayPalette;imageoverlayPalette,
                            --palette--;;filePalette'
                        )
                    ),
                    'maxitems' => 10
                ),
                $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext']
            ),
        ),
...

and the Fluid-Template (s. caption: photo.originalResource.properties.description)

<f:for each="{product.additionalInformation}" as="photo" iteration="iterator">

          <f:image src="{photo.originalResource.originalFile.uid}" alt="" />
                                                        {photo.originalResource.properties.description}

</f:for>

Frontend Output:


问:
Compile PHP 5.4.10 with JPEG for GD
I'm trying to make this for for hours now.
PHP won't compile against libjpeg.

This is what .configure says:

```<code>checking for the location of libvpx... no
checking for the location of libjpeg... /usr
checking for the location of libpng... yes
checking for the location of libXpm... no
</code>```

So no yes, no no.

jpeglib.h is located in /usr/include/jpeglib.h
libjpeg.so is located in /usr/lib/libjpeg.so

I read through the .configure script bout could't find a quick solution.
I'm running Ubuntu 8.04

Any hints on this?

EDIT: The same seems to happen with the freetype libraries.

答:
On a CentOS 5 system (with both jpeglib.h and libjpeg.so also located in /usr/include/jpeglib.h and /usr/lib/libjpeg.so, respectively), I had to include the following options when running the configure script:

--with-gd --with-jpeg-dir=/usr --with-freetype-dir=/usr

This provides GD support for both JPEG and Freetype (I didn’t have to do anything special for GD to support PNG or GIF).

Note: if you’ve already compiled PHP before noticing that GD doesn’t include support for these libraries, you have to run make clean after re-running the configure script.

Title: Compile PHP 5.4.10 with JPEG for GD

Body:
I'm trying to make this for for hours now.
PHP won't compile against libjpeg.

This is what .configure says:

checking for the location of libvpx... no
checking for the location of libjpeg... /usr
checking for the location of libpng... yes
checking for the location of libXpm... no

So no yes, no no.

jpeglib.h is located in /usr/include/jpeglib.h
libjpeg.so is located in /usr/lib/libjpeg.so

I read through the .configure script bout could't find a quick solution.
I'm running Ubuntu 8.04

Any hints on this?

EDIT: The same seems to happen with the freetype libraries.


问:
AWS Athena data input location
According to the docs, when you create a table in Athena, you need to specify the location of the input data file in the s3 bucket. You can only specify the s3 location containing that file, but not the file to be used. For example I have many files like type1.log.gz, type2.log.gz, type3.log.gz of different format at a location my-bucket/logs/.

Currently the location given is 's3://my-bucket/logs/'

So is it possible to specify which file(say type2.log.gz) to be used.
Or do I have to copy the file(type2.log.gz) to another location having no other files and specify its path?

答:
No it is not possible. You are obliged to copy the file in an external bucket

Ref : Confirmed by AWS

Title: AWS Athena data input location


问:
Cannot compile C code on Mac
I downloaded GlimmerHMM from ftp://ftp.cbcb.umd.edu/pub/software/glimmerhmm
However, I'd like to run it on Mac OSX, so in /sources folder in terminal I ran

```<code>gcc -o glimmerhmm glimmerhmm.c
</code>```

Could anybody please give me a hand how to make it work? Thanks in advance!

All it does right now is generate lots of errors:

```<code>In file included from glimmerhmm.c:1:
./delcher.h:41:1: error: unknown type name 'template'
template <class DT>

^
./delcher.h:41:10: error: expected identifier or '('
template <class DT>
         ^

./delcher.h:43:1: error: unknown type name 'template'
template <class DT>

^
./delcher.h:43:10: error: expected identifier or '('
template <class DT>
         ^
./delcher.h:48:1: error: unknown type name 'template'
template <class DT>
^
./delcher.h:48:10: error: expected identifier or '('
template <class DT>
         ^
./delcher.h:55:1: error: unknown type name 'template'
template <class DT>
^
./delcher.h:55:10: error: expected identifier or '('
template <class DT>
         ^
./delcher.h:69:1: error: unknown type name 'template'
template <class DT>
^
./delcher.h:69:10: error: expected identifier or '('
template <class DT>
         ^
./delcher.h:82:1: error: unknown type name 'template'
template <class DT>
^
./delcher.h:82:10: error: expected identifier or '('
template <class DT>
         ^
In file included from glimmerhmm.c:2:
./graph.h:37:1: error: must use 'struct' tag to refer to type 'Site'
Site **graph (char *PData,long int PData_Len,char *TRAIN_DIR, long int *splicesiteno, char *ProtDomFi...
^
struct
In file included from glimmerhmm.c:3:
./gene.h:18:35: error: expected ')'
int  Read_String  (FILE *, char * &, long int &, char [], int);
                                  ^
./gene.h:18:19: note: to match this '('
int  Read_String  (FILE *, char * &, long int &, char [], int);
                  ^
./gene.h:19:41: error: expected ')'
int  Read_Multi_String  (FILE *, char * &, long int &, char [], int,int);
                                        ^
./gene.h:19:25: note: to match this '('
int  Read_Multi_String  (FILE *, char * &, long int &, char [], int,int);
                        ^
glimmerhmm.c:11:3: error: must use 'struct' tag to refer to type 'exon'
  exon *predexon;
  ^
  struct
glimmerhmm.c:12:3: error: must use 'struct' tag to refer to type 'List'
  List *link;
  ^
  struct
glimmerhmm.c:16:15: error: must use 'struct' tag to refer to type 'List'
void freeList(List *L);
              ^
              struct
glimmerhmm.c:18:21: error: must use 'struct' tag to refer to type 'Site'
long int printgenes(Site **Sites, long int ssno,int start, int stop, int ignore,int offset,int *offge...
                    ^
                    struct
fatal error: too many errors emitted, stopping now [-ferror-limit=]
20 errors generated.
</code>```

答:
here is the result of running the supplied makefile

```<code>~/Downloads/Glimmerhmm/GlimmerHMM/sources$ make -f makefile
g++ -g -c glimmerhmm.c
glimmerhmm.c: In function ‘int main(int, char**)’:
glimmerhmm.c:128:42: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long int’ [-Wformat=]
     fprintf(stderr,"Done %d bp\n",proclen);
                                          ^
glimmerhmm.c: In function ‘long int printexon(List*, int*, int*, int*, long int, long int, long int, int*, long int, FILE*, char*, int, int*)’:
glimmerhmm.c:645:146: warning: format ‘%d’ expects argument of type ‘int’, but argument 7 has type ‘long int’ [-Wformat=]
 nno,curexon->start+offset,curexon->stop+offset,curexon->stop-curexon->start+1);
                                                                              ^
glimmerhmm.c:664:146: warning: format ‘%d’ expects argument of type ‘int’, but argument 7 has type ‘long int’ [-Wformat=]
 nno,curexon->start+offset,curexon->stop+offset,curexon->stop-curexon->start+1);
                                                                              ^
glimmerhmm.c:683:148: warning: format ‘%d’ expects argument of type ‘int’, but argument 7 has type ‘long int’ [-Wformat=]
 nno,curexon->start+offset,curexon->stop+offset,curexon->stop-curexon->start+1);
                                                                              ^
glimmerhmm.c:703:148: warning: format ‘%d’ expects argument of type ‘int’, but argument 7 has type ‘long int’ [-Wformat=]
 nno,curexon->start+offset,curexon->stop+offset,curexon->stop-curexon->start+1);
                                                                              ^
glimmerhmm.c:722:148: warning: format ‘%d’ expects argument of type ‘int’, but argument 7 has type ‘long int’ [-Wformat=]
 nno,curexon->start+offset,curexon->stop+offset,curexon->stop-curexon->start+1);
                                                                              ^
glimmerhmm.c:743:146: warning: format ‘%d’ expects argument of type ‘int’, but argument 7 has type ‘long int’ [-Wformat=]
 nno,curexon->start+offset,curexon->stop+offset,curexon->stop-curexon->start+1);
                                                                              ^
glimmerhmm.c:763:146: warning: format ‘%d’ expects argument of type ‘int’, but argument 7 has type ‘long int’ [-Wformat=]
 nno,curexon->start+offset,curexon->stop+offset,curexon->stop-curexon->start+1);
                                                                              ^
glimmerhmm.c:781:148: warning: format ‘%d’ expects argument of type ‘int’, but argument 7 has type ‘long int’ [-Wformat=]
 nno,curexon->start+offset,curexon->stop+offset,curexon->stop-curexon->start+1);
                                                                              ^
g++ -g -c graph.c
graph.c: In function ‘Site** graph(char*, long int, char*, long int*, char*, long int, int, char*, int, int)’:
graph.c:1051:63: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long int’ [-Wformat=]
  fprintf(stderr,"Memory allocation for coding %d failure.\n",i);
                                                               ^
graph.c:1062:63: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long int’ [-Wformat=]
  fprintf(stderr,"Memory allocation for coding %d failure.\n",i);
                                                               ^
graph.c:1089:65: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long int’ [-Wformat=]
    fprintf(stderr,"Memory allocation for coding %d failure.\n",i);
                                                                 ^
graph.c:1233:93: warning: format ‘%d’ expects argument of type ‘int*’, but argument 4 has type ‘long int*’ [-Wformat=]
 ne,"%s %d %d %*s %*d %*d %f %e %*s",File_Name,&begdom,&enddom,&bitscore,&eval);
                                                                              ^
graph.c:1233:93: warning: format ‘%d’ expects argument of type ‘int*’, but argument 5 has type ‘long int*’ [-Wformat=]
graph.c:1233:93: warning: format ‘%e’ expects argument of type ‘float*’, but argument 7 has type ‘double*’ [-Wformat=]
graph.c:2085:63: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long int’ [-Wformat=]
  fprintf(stderr,"Memory allocation for coding %d failure.\n",i);
                                                               ^
g++ -g -c sites.c
g++ -g -c tree_util_prob.c
tree_util_prob.c: In function ‘tree_node* read_tree(char*)’:
tree_util_prob.c:64:51: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
     error ("Decision Tree file can not be opened.");
                                                   ^
tree_util_prob.c:67:42: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
     error("Decision tree invalid/absent.");
                                          ^
tree_util_prob.c:70:42: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
     error("Decision tree invalid/absent.");
                                          ^
tree_util_prob.c: In function ‘tree_node* read_hp(FILE*)’:
tree_util_prob.c:192:45: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
  error("Invalid/Absent hyperplane equation.");
                                             ^
tree_util_prob.c:196:51: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
      error("Read-Hp: Invalid hyperplane equation.");
                                                   ^
tree_util_prob.c:198:66: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
      error("Read_Hp: Invalid coefficient index in decision tree.");
                                                                  ^
g++ -g -c util.c
util.c: In function ‘int* ivector(int, int)’:
util.c:84:60: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
   if (v==NULL) error("Ivector : Memory allocation failure.");
                                                            ^
util.c: In function ‘float* vector(int, int)’:
util.c:101:59: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
   if (v==NULL) error("Vector : Memory allocation failure.");
                                                           ^
util.c: In function ‘double* dvector(int, int)’:
util.c:118:60: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
   if (v==NULL) error("Dvector : Memory allocation failure.");
                                                            ^
g++ -g -o glimmerhmm glimmerhmm.o graph.o sites.o tree_util_prob.o util.o  -lm
</code>```

So, even when moved to the MAC, this code will take a lot of modification to obtain a successful compile/link

Title: Cannot compile C code on Mac

Body:
I downloaded GlimmerHMM from ftp://ftp.cbcb.umd.edu/pub/software/glimmerhmm
However, I'd like to run it on Mac OSX, so in /sources folder in terminal I ran

gcc -o glimmerhmm glimmerhmm.c

Could anybody please give me a hand how to make it work? Thanks in advance!

All it does right now is generate lots of errors:

In file included from glimmerhmm.c:1:
./delcher.h:41:1: error: unknown type name 'template'
template <class DT>

^
./delcher.h:41:10: error: expected identifier or '('
template <class DT>
         ^

./delcher.h:43:1: error: unknown type name 'template'
template <class DT>

^
./delcher.h:43:10: error: expected identifier or '('
template <class DT>
         ^
./delcher.h:48:1: error: unknown type name 'template'
template <class DT>
^
./delcher.h:48:10: error: expected identifier or '('
template <class DT>
         ^
./delcher.h:55:1: error: unknown type name 'template'
template <class DT>
^
./delcher.h:55:10: error: expected identifier or '('
template <class DT>
         ^
./delcher.h:69:1: error: unknown type name 'template'
template <class DT>
^
./delcher.h:69:10: error: expected identifier or '('
template <class DT>
         ^
./delcher.h:82:1: error: unknown type name 'template'
template <class DT>
^
./delcher.h:82:10: error: expected identifier or '('
template <class DT>
         ^
In file included from glimmerhmm.c:2:
./graph.h:37:1: error: must use 'struct' tag to refer to type 'Site'
Site **graph (char *PData,long int PData_Len,char *TRAIN_DIR, long int *splicesiteno, char *ProtDomFi...
^
struct
In file included from glimmerhmm.c:3:
./gene.h:18:35: error: expected ')'
int  Read_String  (FILE *, char * &, long int &, char [], int);
                                  ^
./gene.h:18:19: note: to match this '('
int  Read_String  (FILE *, char * &, long int &, char [], int);
                  ^
./gene.h:19:41: error: expected ')'
int  Read_Multi_String  (FILE *, char * &, long int &, char [], int,int);
                                        ^
./gene.h:19:25: note: to match this '('
int  Read_Multi_String  (FILE *, char * &, long int &, char [], int,int);
                        ^
glimmerhmm.c:11:3: error: must use 'struct' tag to refer to type 'exon'
  exon *predexon;
  ^
  struct
glimmerhmm.c:12:3: error: must use 'struct' tag to refer to type 'List'
  List *link;
  ^
  struct
glimmerhmm.c:16:15: error: must use 'struct' tag to refer to type 'List'
void freeList(List *L);
              ^
              struct
glimmerhmm.c:18:21: error: must use 'struct' tag to refer to type 'Site'
long int printgenes(Site **Sites, long int ssno,int start, int stop, int ignore,int offset,int *offge...
                    ^
                    struct
fatal error: too many errors emitted, stopping now [-ferror-limit=]
20 errors generated.

Body:
here is the result of running the supplied makefile

~/Downloads/Glimmerhmm/GlimmerHMM/sources$ make -f makefile
g++ -g -c glimmerhmm.c
glimmerhmm.c: In function ‘int main(int, char**)’:
glimmerhmm.c:128:42: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long int’ [-Wformat=]
     fprintf(stderr,"Done %d bp\n",proclen);
                                          ^
glimmerhmm.c: In function ‘long int printexon(List*, int*, int*, int*, long int, long int, long int, int*, long int, FILE*, char*, int, int*)’:
glimmerhmm.c:645:146: warning: format ‘%d’ expects argument of type ‘int’, but argument 7 has type ‘long int’ [-Wformat=]
 nno,curexon->start+offset,curexon->stop+offset,curexon->stop-curexon->start+1);
                                                                              ^
glimmerhmm.c:664:146: warning: format ‘%d’ expects argument of type ‘int’, but argument 7 has type ‘long int’ [-Wformat=]
 nno,curexon->start+offset,curexon->stop+offset,curexon->stop-curexon->start+1);
                                                                              ^
glimmerhmm.c:683:148: warning: format ‘%d’ expects argument of type ‘int’, but argument 7 has type ‘long int’ [-Wformat=]
 nno,curexon->start+offset,curexon->stop+offset,curexon->stop-curexon->start+1);
                                                                              ^
glimmerhmm.c:703:148: warning: format ‘%d’ expects argument of type ‘int’, but argument 7 has type ‘long int’ [-Wformat=]
 nno,curexon->start+offset,curexon->stop+offset,curexon->stop-curexon->start+1);
                                                                              ^
glimmerhmm.c:722:148: warning: format ‘%d’ expects argument of type ‘int’, but argument 7 has type ‘long int’ [-Wformat=]
 nno,curexon->start+offset,curexon->stop+offset,curexon->stop-curexon->start+1);
                                                                              ^
glimmerhmm.c:743:146: warning: format ‘%d’ expects argument of type ‘int’, but argument 7 has type ‘long int’ [-Wformat=]
 nno,curexon->start+offset,curexon->stop+offset,curexon->stop-curexon->start+1);
                                                                              ^
glimmerhmm.c:763:146: warning: format ‘%d’ expects argument of type ‘int’, but argument 7 has type ‘long int’ [-Wformat=]
 nno,curexon->start+offset,curexon->stop+offset,curexon->stop-curexon->start+1);
                                                                              ^
glimmerhmm.c:781:148: warning: format ‘%d’ expects argument of type ‘int’, but argument 7 has type ‘long int’ [-Wformat=]
 nno,curexon->start+offset,curexon->stop+offset,curexon->stop-curexon->start+1);
                                                                              ^
g++ -g -c graph.c
graph.c: In function ‘Site** graph(char*, long int, char*, long int*, char*, long int, int, char*, int, int)’:
graph.c:1051:63: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long int’ [-Wformat=]
  fprintf(stderr,"Memory allocation for coding %d failure.\n",i);
                                                               ^
graph.c:1062:63: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long int’ [-Wformat=]
  fprintf(stderr,"Memory allocation for coding %d failure.\n",i);
                                                               ^
graph.c:1089:65: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long int’ [-Wformat=]
    fprintf(stderr,"Memory allocation for coding %d failure.\n",i);
                                                                 ^
graph.c:1233:93: warning: format ‘%d’ expects argument of type ‘int*’, but argument 4 has type ‘long int*’ [-Wformat=]
 ne,"%s %d %d %*s %*d %*d %f %e %*s",File_Name,&begdom,&enddom,&bitscore,&eval);
                                                                              ^
graph.c:1233:93: warning: format ‘%d’ expects argument of type ‘int*’, but argument 5 has type ‘long int*’ [-Wformat=]
graph.c:1233:93: warning: format ‘%e’ expects argument of type ‘float*’, but argument 7 has type ‘double*’ [-Wformat=]
graph.c:2085:63: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘long int’ [-Wformat=]
  fprintf(stderr,"Memory allocation for coding %d failure.\n",i);
                                                               ^
g++ -g -c sites.c
g++ -g -c tree_util_prob.c
tree_util_prob.c: In function ‘tree_node* read_tree(char*)’:
tree_util_prob.c:64:51: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
     error ("Decision Tree file can not be opened.");
                                                   ^
tree_util_prob.c:67:42: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
     error("Decision tree invalid/absent.");
                                          ^
tree_util_prob.c:70:42: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
     error("Decision tree invalid/absent.");
                                          ^
tree_util_prob.c: In function ‘tree_node* read_hp(FILE*)’:
tree_util_prob.c:192:45: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
  error("Invalid/Absent hyperplane equation.");
                                             ^
tree_util_prob.c:196:51: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
      error("Read-Hp: Invalid hyperplane equation.");
                                                   ^
tree_util_prob.c:198:66: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
      error("Read_Hp: Invalid coefficient index in decision tree.");
                                                                  ^
g++ -g -c util.c
util.c: In function ‘int* ivector(int, int)’:
util.c:84:60: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
   if (v==NULL) error("Ivector : Memory allocation failure.");
                                                            ^
util.c: In function ‘float* vector(int, int)’:
util.c:101:59: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
   if (v==NULL) error("Vector : Memory allocation failure.");
                                                           ^
util.c: In function ‘double* dvector(int, int)’:
util.c:118:60: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
   if (v==NULL) error("Dvector : Memory allocation failure.");
                                                            ^
g++ -g -o glimmerhmm glimmerhmm.o graph.o sites.o tree_util_prob.o util.o  -lm

So, even when moved to the MAC, this code will take a lot of modification to obtain a successful compile/link


问:
SQL Case Statement - how to do it
I have the below statement which works nicely in Tableau.

However, I'd like to turn this into SQL and save all the results into a temporary column name.

Does anyone know how I might do this?

Essentially, the below removes the .com/.net etc... from the domain name.

I then have another script that removes the subdomain (everything from the first . to the left of the resulting value).

If anyone can help me with these, that would be incredible as I'm not sure how to do this in SQL

```<code>IF CONTAINS([domain], ".co.uk") then LEFT([domain],LEN([domain])-6)
elseif  CONTAINS([domain], ".com") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".net") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".org") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".biz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".edu") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".ac") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".gov") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".biz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".co") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ca") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".io") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".in") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".it") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".uk") then LEFT([domain],LEN([domain])- 3)
elseif  CONTAINS([domain], ".ru") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ie") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".tv") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".info") then LEFT([domain],LEN([domain])-5)
elseif  CONTAINS([domain], ".fr") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".es") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".pl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".is") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".hu") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".xxx") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".nl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ro") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".xyz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".no") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".eu") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".me") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".cz") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".fi") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".nl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".al") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".am") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".af") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".st") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".cn") then LEFT([domain],LEN([domain])-3)
else [domain]
end
</code>```

答:
If SQL Server, perhaps something like this

```<code>Declare @YourTable table (domain varchar(100))
Insert Into @YourTable values
('somedomain.org'),
('somedomain.net'),
('anotherdomain.az'),
('nodomain'),
('somedomain.com?Param=1')

Select A.*
      ,NoDomain = left(domain,len(domain)-charindex('.',reverse(domain)))
 From  @YourTable A
</code>```

Returns

```<code>domain                  NoDomain
somedomain.org          somedomain
somedomain.net          somedomain
anotherdomain.az        anotherdomain
nodomain                nodomain
somedomain.com?Param=1  somedomain
</code>```

Title: SQL Case Statement - how to do it

Body:
I have the below statement which works nicely in Tableau.

However, I'd like to turn this into SQL and save all the results into a temporary column name.

Does anyone know how I might do this?

Essentially, the below removes the .com/.net etc... from the domain name.

I then have another script that removes the subdomain (everything from the first . to the left of the resulting value).

If anyone can help me with these, that would be incredible as I'm not sure how to do this in SQL

IF CONTAINS([domain], ".co.uk") then LEFT([domain],LEN([domain])-6)
elseif  CONTAINS([domain], ".com") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".net") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".org") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".biz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".edu") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".ac") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".gov") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".biz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".co") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ca") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".io") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".in") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".it") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".uk") then LEFT([domain],LEN([domain])- 3)
elseif  CONTAINS([domain], ".ru") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ie") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".tv") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".info") then LEFT([domain],LEN([domain])-5)
elseif  CONTAINS([domain], ".fr") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".es") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".pl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".is") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".hu") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".xxx") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".nl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ro") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".xyz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".no") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".eu") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".me") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".cz") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".fi") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".nl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".al") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".am") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".af") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".st") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".cn") then LEFT([domain],LEN([domain])-3)
else [domain]
end

Body:
If SQL Server, perhaps something like this

Declare @YourTable table (domain varchar(100))
Insert Into @YourTable values
('somedomain.org'),
('somedomain.net'),
('anotherdomain.az'),
('nodomain'),
('somedomain.com?Param=1')

Select A.*
      ,NoDomain = left(domain,len(domain)-charindex('.',reverse(domain)))
 From  @YourTable A

Returns

domain                  NoDomain
somedomain.org          somedomain
somedomain.net          somedomain
anotherdomain.az        anotherdomain
nodomain                nodomain
somedomain.com?Param=1  somedomain


问:
How to change icon colors in android studio
I downloaded some icons from material.io but they only offer the icons in black.  I saw a youtube video where they use to allow you to choose the color.  Anyway, I am trying to change the colors of the icons to white.  I am not having any luck.  I tried to change the fill color in android studio  but it doesn't work.  Any assistance would be appreciated such as exact code and files to add the code to.  Thanks.</p>

答:
You can directly download these images in Android Studio.

res > right click > New > Image Asset and select

Icon Type : Action Bar and Tab Icones

Asset Type : Clip Art

Theme : CUSTOM

And you can select any clip art that you want, select the color, padding, etc ...


问:
How to override/replace the related field from base in odoo 9
Existing Field(base addons):

```<code>journal_id = fields.Many2one('account.journal', related='statement_id.journal_id', string='Journal', store=True, readonly=True)

New Field(custom addons):

journal_id = fields.Many2one('account.journal',string='Journal')
</code>```

I want to change the existing field into new field like above example.

答:
Try this code...</p>

```<code>journal_id = fields.Many2one('account.journal',

related='statement_id.journal_id', string='Journal', store=True, readonly=True)

New Field(custom addons):

journal_id = fields.Many2one('account.journal',string='Journal',related=False,store=False, readonly=False)
</code>```

Body:
Existing Field(base addons):

journal_id = fields.Many2one('account.journal', related='statement_id.journal_id', string='Journal', store=True, readonly=True)

New Field(custom addons):

journal_id = fields.Many2one('account.journal',string='Journal')

I want to change the existing field into new field like above example.

Body:
Try this code...

journal_id = fields.Many2one('account.journal',

related='statement_id.journal_id', string='Journal', store=True, readonly=True)

New Field(custom addons):

journal_id = fields.Many2one('account.journal',string='Journal',related=False,store=False, readonly=False)


问:
How to create fishnet in arcgis engine?
I found createfishnet method in arcobject, but it doesn't work.Where is my mistake?

```<code>Geoprocessor gp = new Geoprocessor();
            gp.OverwriteOutput = true;
            ESRI.ArcGIS.DataManagementTools.CreateFishnet fishnet = new ESRI.ArcGIS.DataManagementTools.CreateFishnet();
            fishnet.template = buffer_out;
            //txtOutputPath2.Text="E:\\program\\shenzhen_science_committee\\sc\\landuse_subway\\shenzhen_subway\\23_net.shp"

            fishnet.out_feature_class = txtOutputPath2.Text;
            IFeatureCursor cursor1=buffer_out.Search(null,true);
            IFeature buffer=cursor1.NextFeature();
            IPoint centerPoint =new ESRI.ArcGIS.Geometry.Point();
            IArea pArea = buffer.Shape as IArea;
            pArea.QueryCentroid(centerPoint);
            fishnet.origin_coord = centerPoint;
            double height=0;
            double width=0;
            fishnet.cell_height = 0.1;
            fishnet.cell_width = 0.1;
            fishnet.number_columns = 50;
            fishnet.number_rows = 50;

            IGeoProcessorResult results = (IGeoProcessorResult)gp.Execute(fishnet, null);
</code>```

The result shows wrong HRESULT E_FAIL.

答:
I have tried this in ArcObjects with Java. What I found was that the fishnet could not be generated for area within a particular polygon, as in the ArcMap application. You would have to intersect or use spatial filter on the fishnet output.
Also, try giving all the parameters, even the optional ones like set corner coordinate. If you are using data in a particular projection system, that can be set to the output by setting the template (and this takes only Envelope).

Below is the code that I have used. I wanted the fishnet label as well, so I have enabled it. Make sure you use a space between the x and y coordinate of a point, entered as a String, which is probably the issue here.

```<code>GeoProcessor gp = new GeoProcessor();
gp.setOverwriteOutput(true);

IEnvelope aoi = buffer_out.getEnvelope();
CreateFishnet createFishnet = new CreateFishnet();
createFishnet.setOutFeatureClass(tempDir+"/"+fishnetOutput+".shp");
createFishnet.setTemplate(aoi);
createFishnet.setOriginCoord(aoi.getXMin()+" "+aoi.getYMin());
createFishnet.setYAxisCoord(aoi.getXMin()+" "+aoi.getYMax());
createFishnet.setCornerCoord(aoi.getXMax()+" "+aoi.getYMax());
createFishnet.setCellHeight(30.0);
createFishnet.setCellWidth(30.0);
createFishnet.setNumberRows(0);
createFishnet.setNumberColumns(0);
createFishnet.setLabels("LABELS");
createFishnet.setGeometryType("POLYLINE");

gp.execute(createFishnet, null);
</code>```

I hope you can use this example and apply it to your code.

Title: How to create fishnet in arcgis engine?

Body:
I found createfishnet method in arcobject, but it doesn't work.Where is my mistake?

Geoprocessor gp = new Geoprocessor();
            gp.OverwriteOutput = true;
            ESRI.ArcGIS.DataManagementTools.CreateFishnet fishnet = new ESRI.ArcGIS.DataManagementTools.CreateFishnet();
            fishnet.template = buffer_out;
            //txtOutputPath2.Text="E:\\program\\shenzhen_science_committee\\sc\\landuse_subway\\shenzhen_subway\\23_net.shp"

            fishnet.out_feature_class = txtOutputPath2.Text;
            IFeatureCursor cursor1=buffer_out.Search(null,true);
            IFeature buffer=cursor1.NextFeature();
            IPoint centerPoint =new ESRI.ArcGIS.Geometry.Point();
            IArea pArea = buffer.Shape as IArea;
            pArea.QueryCentroid(centerPoint);
            fishnet.origin_coord = centerPoint;
            double height=0;
            double width=0;
            fishnet.cell_height = 0.1;
            fishnet.cell_width = 0.1;
            fishnet.number_columns = 50;
            fishnet.number_rows = 50;

            IGeoProcessorResult results = (IGeoProcessorResult)gp.Execute(fishnet, null);

The result shows wrong HRESULT E_FAIL.

Body:
I have tried this in ArcObjects with Java. What I found was that the fishnet could not be generated for area within a particular polygon, as in the ArcMap application. You would have to intersect or use spatial filter on the fishnet output.
Also, try giving all the parameters, even the optional ones like set corner coordinate. If you are using data in a particular projection system, that can be set to the output by setting the template (and this takes only Envelope).

Below is the code that I have used. I wanted the fishnet label as well, so I have enabled it. Make sure you use a space between the x and y coordinate of a point, entered as a String, which is probably the issue here.

GeoProcessor gp = new GeoProcessor();
gp.setOverwriteOutput(true);

IEnvelope aoi = buffer_out.getEnvelope();
CreateFishnet createFishnet = new CreateFishnet();
createFishnet.setOutFeatureClass(tempDir+"/"+fishnetOutput+".shp");
createFishnet.setTemplate(aoi);
createFishnet.setOriginCoord(aoi.getXMin()+" "+aoi.getYMin());
createFishnet.setYAxisCoord(aoi.getXMin()+" "+aoi.getYMax());
createFishnet.setCornerCoord(aoi.getXMax()+" "+aoi.getYMax());
createFishnet.setCellHeight(30.0);
createFishnet.setCellWidth(30.0);
createFishnet.setNumberRows(0);
createFishnet.setNumberColumns(0);
createFishnet.setLabels("LABELS");
createFishnet.setGeometryType("POLYLINE");

gp.execute(createFishnet, null);

I hope you can use this example and apply it to your code.


问:
How to display EnumSet in JSP file in custom order?
I have an java.util.EnumSet containing a lot of elements that is being displayed as a drop down list (JSP). Now, by default they're sorted by ID:

```<code>1 Toyota
2 Honda
3 Audi
4 BMW
</code>```

What I want to achieve is the list in alphabetic order:

```<code>3 Audi
4 BMW
2 Honda
1 Toyota
</code>```

Can I change the order of displaying the enums on the drop down list without changing their IDs?

答:
You can create an ordered Collection from the EnumSet and then use that in JSP. However then you won't be getting benefits of EnumSet, in that case there's no need to use it in the first place.

Check following sample for creating desired ordered List

```<code>import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;

public class TestEnumSet {
    public static void main(String[] args) {
        System.out.println("Started\n");

        EnumSet<Cars> set = EnumSet.of(Cars.Toyata, Cars.Audi, Cars.Honda, Cars.BMW);

        List<Cars> list = Arrays.asList(set.toArray(new Cars[]{}));
        list.sort((a, b) -> a.toString().compareTo(b.toString()));

        list.stream().forEach(a -> System.out.println(a.id + " : " + a.toString()));

        System.out.println("\nFnished");
    }

    public static enum Cars {
        Toyata(1), Audi(2), Honda(3), BMW(4);

        int id;
        Cars(int id ) {
            this.id = id;
        }
    }
}
</code>```

Output

```<code>Started

2 : Audi
4 : BMW
3 : Honda
1 : Toyata

Fnished
</code>```

Body:
I have an java.util.EnumSet containing a lot of elements that is being displayed as a drop down list (JSP). Now, by default they're sorted by ID:

1 Toyota
2 Honda
3 Audi
4 BMW

What I want to achieve is the list in alphabetic order:

3 Audi
4 BMW
2 Honda
1 Toyota

Can I change the order of displaying the enums on the drop down list without changing their IDs?

Body:
You can create an ordered Collection from the EnumSet and then use that in JSP. However then you won't be getting benefits of EnumSet, in that case there's no need to use it in the first place.

Check following sample for creating desired ordered List

import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;

public class TestEnumSet {
    public static void main(String[] args) {
        System.out.println("Started\n");

        EnumSet<Cars> set = EnumSet.of(Cars.Toyata, Cars.Audi, Cars.Honda, Cars.BMW);

        List<Cars> list = Arrays.asList(set.toArray(new Cars[]{}));
        list.sort((a, b) -> a.toString().compareTo(b.toString()));

        list.stream().forEach(a -> System.out.println(a.id + " : " + a.toString()));

        System.out.println("\nFnished");
    }

    public static enum Cars {
        Toyata(1), Audi(2), Honda(3), BMW(4);

        int id;
        Cars(int id ) {
            this.id = id;
        }
    }
}

Output

Started

2 : Audi
4 : BMW
3 : Honda
1 : Toyata

Fnished


问:
How to split CamelCase variable names on case change
How do I split a CamelCase variable name in the output?

According to this SAS Blog article,

When you print data, [CamelCase] variable names are automatically split in
  your output at the next uppercase letter. (Note: this depends on the
  length of the data field.)

However, when I try

```<code>data test1;
  input ThisIsALongNameThatIHopeSplits $;
  datalines;
Hello,
World!
;
run;

proc print data = test1;
run;
</code>```

the variable name does not split.

The article does say that splitting depends on the length of the data field.  However, if I modify my data set,

```<code>data test2;
  length ThisIsALongNameThatIHopeSplits $ 250;
  input ThisIsALongNameThatIHopeSplits $ &;
  datalines;
Hello, World! It's been a long time since we last saw one another. It was nice knowing you. Goodbye, cruel world!
;
run;

proc print data = test2;
run;
</code>```

the result is the same.

The SAS Community Wiki states

If the
  ODS system ever has to split a name over two or more lines to stack
  the column heading for a more pleasing vertical layout, she will
  prefer to split at a caseTransition, and so your multi word variable
  names have a better chance of splitting at "pleasing" boundaries.

So, I try outputting it to a .rtf.

```<code>ods rtf file = "C:\Users\&SYSUSERID\Documents\tests.rtf";
proc print data = test1;
run;
proc print data = test2;
run;
ods rtf close;
</code>```

Nothing. (Except a warning regarding the data itself and not the variable name.)  The variable name remains unsplit.

```<code>WARNING: Data too long for column "ThisIsALongNameThatIHopeSplits"; truncated to 98 characters to fit.
</code>```

I would call jiggery-pokery if the claims weren't coming from such reputable sources.  Is there an option or something I'm missing?

答:
It doesn't seem to work for HTML output (the default in 9.3) but it DOES work for listing output, which is probably what those community sources are referring to.

Try the following:

```<code>ods html close;
ods listing;
data test2;
  length ThisIsALongNameThatIHopeSplits
    ThisIsALongNameThatIHopeSplits2
    ThisIsALongNameThatIHopeSplits3
    ThisIsALongNameThatIHopeSplits4
      $ 250;
  input ThisIsALongNameThatIHopeSplits $ &;
  ThisIsALongNameThatIHopeSplits2=ThisIsALongNameThatIHopeSplits;
    ThisIsALongNameThatIHopeSplits3=ThisIsALongNameThatIHopeSplits;
    ThisIsALongNameThatIHopeSplits4=ThisIsALongNameThatIHopeSplits;
  datalines;
Goodbye, cruel world!
;
run;

proc print data = test2;
run;
</code>```

Which gives:

Body:
How do I split a CamelCase variable name in the output?

According to this SAS Blog article,

When you print data, [CamelCase] variable names are automatically split in
  your output at the next uppercase letter. (Note: this depends on the
  length of the data field.)

However, when I try

data test1;
  input ThisIsALongNameThatIHopeSplits $;
  datalines;
Hello,
World!
;
run;

proc print data = test1;
run;

the variable name does not split.

The article does say that splitting depends on the length of the data field.  However, if I modify my data set,

data test2;
  length ThisIsALongNameThatIHopeSplits $ 250;
  input ThisIsALongNameThatIHopeSplits $ &;
  datalines;
Hello, World! It's been a long time since we last saw one another. It was nice knowing you. Goodbye, cruel world!
;
run;

proc print data = test2;
run;

the result is the same.

The SAS Community Wiki states

If the
  ODS system ever has to split a name over two or more lines to stack
  the column heading for a more pleasing vertical layout, she will
  prefer to split at a caseTransition, and so your multi word variable
  names have a better chance of splitting at "pleasing" boundaries.

So, I try outputting it to a .rtf.

ods rtf file = "C:\Users\&SYSUSERID\Documents\tests.rtf";
proc print data = test1;
run;
proc print data = test2;
run;
ods rtf close;

Nothing. (Except a warning regarding the data itself and not the variable name.)  The variable name remains unsplit.

WARNING: Data too long for column "ThisIsALongNameThatIHopeSplits"; truncated to 98 characters to fit.

I would call jiggery-pokery if the claims weren't coming from such reputable sources.  Is there an option or something I'm missing?

Body:
It doesn't seem to work for HTML output (the default in 9.3) but it DOES work for listing output, which is probably what those community sources are referring to.

Try the following:

ods html close;
ods listing;
data test2;
  length ThisIsALongNameThatIHopeSplits
    ThisIsALongNameThatIHopeSplits2
    ThisIsALongNameThatIHopeSplits3
    ThisIsALongNameThatIHopeSplits4
      $ 250;
  input ThisIsALongNameThatIHopeSplits $ &;
  ThisIsALongNameThatIHopeSplits2=ThisIsALongNameThatIHopeSplits;
    ThisIsALongNameThatIHopeSplits3=ThisIsALongNameThatIHopeSplits;
    ThisIsALongNameThatIHopeSplits4=ThisIsALongNameThatIHopeSplits;
  datalines;
Goodbye, cruel world!
;
run;

proc print data = test2;
run;

Which gives:


问:
Why are there so many loopback addresses?
I saw there are 16.581.375 loopback addresses, but nearly every program only uses 127.0.0.1. So why are there so many unused addresses.

IPv4 has many address problems, so why are people wasting so many ip addresses? Is there a reakson for it?

答:
In IPv4 the range 127.0.0.0 – 127.255.255.255 is reserved for loopback, i.e. a Host’s self-address. These loopback IP addresses are managed entirely by and within the operating system and enable testing of communications in client-server architecture systems on a single machine. When a process creates a packet with a destination address as loopback address, the operating system loops it back to itself directly without having to go through any NIC.

You might also use it for things like: Simulating a large number of different computers in a fast network (simply bring up more interfaces and bind services to them) without using virtual machines. This might be helpful if you wanted to have a number of different web servers running locally on port 80 for some reason. Or Permitting more locally running services than the 64k TCP would permit (though it seems unlikely that you would hit that limit rationally).

Historically, the first implementation of TCP/IP didn't support the use of Masks, which meant network nodes used the first number to distinguish network size and host ID.
More info: https://www.experts-exchange.com/questions/20814842/why-loopback-testing-having-so-long-range.html