问:
Read from file or from command line arguments haskell
I am designing the IO for a program I have written in Haskell.  I would like to be able to read some arguments from file using -f or from the command line by default.  The command line arguments get split up into convenient chunks meaning I do not need to parse them.  However this does not happen when reading from file.  So I wrote a simple little parser to do what I wanted.

```<code>parseFile :: String -> [String]
parseFile [] = [""]
parseFile ('"':xs) = parseString xs '"'
parseFile ('\'':xs) = parseString xs '\''
parseFile (' ':xs) = "":parseFile xs
parseFile ('\t':xs) = "":parseFile xs
parseFile ('\n':xs) = "":parseFile xs
parseFile (s:xs) = (\(a:xa)->(a++[s]):xa)$ parseFile xs

parseString :: String -> Char -> [String]
parseString (s:xs) a
 | s == a = "":parseFile xs
 | otherwise = (\(a:xa)->(a++[s]):xa)$ parseString xs a
</code>```

I thought this would be pretty simple I would do something like

```<code>let myInput = if (flagDetected) then (parseFile $ readFile $ last args) else (args)
</code>```

However the result of readFile is an IO action and not a string thus I cannot parse it.  I've tried a number of configurations all which have fails, mostly for typing reasons.  I've tried assigning the results before parsing, which resulted in a type mismatch between args which is a [[Char]] ( it is the result of using getArgs from the System.Environment module) and the result of readFile which is still an IO String.
 I tried wrapping args with a return which of course doesn't fix this problem because of a type mismatch.  I'm really at a loss of ideas now.  I feel like this is probably a problem with the way I am thinking about the issue.

How can I get the behavior I desire?

Here's a related question I asked earlier.  The root of the problem is the same but the answers on the last one were far to specific to help me here. It seems this is a frequent problem for me.

答:
You need to do an inversion of control in the flow of your data.. Haskell's IO datatypes are there to manage the effects of i/o operations. Read string from a file is not a fact, the file couldn't exist, can be empty or so on. Many possibilities could happend. So for that reason main function use to be based on IO. The way you can use to "extract" wrapped value from a IO is using do-return block

```<code>inputIO = if flagDetected then
             do
               cnt <- (readFile path)
               return (parseFile cnt)
          else return args
main = do
      input <- inputIO
      return yourProgram input
</code>```

Look here

Body:
I am designing the IO for a program I have written in Haskell.  I would like to be able to read some arguments from file using -f or from the command line by default.  The command line arguments get split up into convenient chunks meaning I do not need to parse them.  However this does not happen when reading from file.  So I wrote a simple little parser to do what I wanted.

parseFile :: String -> [String]
parseFile [] = [""]
parseFile ('"':xs) = parseString xs '"'
parseFile ('\'':xs) = parseString xs '\''
parseFile (' ':xs) = "":parseFile xs
parseFile ('\t':xs) = "":parseFile xs
parseFile ('\n':xs) = "":parseFile xs
parseFile (s:xs) = (\(a:xa)->(a++[s]):xa)$ parseFile xs

parseString :: String -> Char -> [String]
parseString (s:xs) a
 | s == a = "":parseFile xs
 | otherwise = (\(a:xa)->(a++[s]):xa)$ parseString xs a

I thought this would be pretty simple I would do something like

let myInput = if (flagDetected) then (parseFile $ readFile $ last args) else (args)

However the result of readFile is an IO action and not a string thus I cannot parse it.  I've tried a number of configurations all which have fails, mostly for typing reasons.  I've tried assigning the results before parsing, which resulted in a type mismatch between args which is a [[Char]] ( it is the result of using getArgs from the System.Environment module) and the result of readFile which is still an IO String.
 I tried wrapping args with a return which of course doesn't fix this problem because of a type mismatch.  I'm really at a loss of ideas now.  I feel like this is probably a problem with the way I am thinking about the issue.

How can I get the behavior I desire?

Here's a related question I asked earlier.  The root of the problem is the same but the answers on the last one were far to specific to help me here. It seems this is a frequent problem for me.

Body:
You need to do an inversion of control in the flow of your data.. Haskell's IO datatypes are there to manage the effects of i/o operations. Read string from a file is not a fact, the file couldn't exist, can be empty or so on. Many possibilities could happend. So for that reason main function use to be based on IO. The way you can use to "extract" wrapped value from a IO is using do-return block

inputIO = if flagDetected then
             do
               cnt <- (readFile path)
               return (parseFile cnt)
          else return args
main = do
      input <- inputIO
      return yourProgram input

Look here


来源: stackexchange

问:
Puppet, cp: cannot stat `/tmp/kitchen/hiera/*': No such file or directory
I am trying to create a puppet deployment using kitchen-puppet.

Here is what my kitchen file looks like:

```<code>---
driver:
  name: vagrant

provisioner:
  name: puppet_apply
  manifests_path: /repository/puppet_repo/manifests
  modules_path: /repository/puppet_repo/modules-mycompany
  hiera_data_path: /repository/puppet_repo/hieradata

platforms:
- name: centos-6.8
- name: centos-7.2
- name: debian-7.8
- name: ubuntu-12.04
- name: ubuntu-14.04
- name: ubuntu-16.04

suites:
  - name: default
</code>```

When I attempt to use it I get the following error message:

```<code>$ bundle exec kitchen converge default-centos-68
-----> Starting Kitchen (v1.16.0)
-----> Converging <default-centos-68>...
       Preparing files for transfer
       Preparing modules
       Nothing to do for modules
       Preparing manifests
       Preparing files
       nothing to do for files
       Preparing hiera data
       Finished Preparing files for transfer
       Installing puppet from yum on centos
       Install busser on centos
       Transferring files to <default-centos-68>
       cp: cannot stat `/tmp/kitchen/hiera/*': No such file or directory
>>>>>> ------Exception-------
>>>>>> Class: Kitchen::ActionFailed
>>>>>> Message: 1 actions failed.
>>>>>>     Converge failed on instance <default-centos-68>.  Please see .kitchen/logs/default-centos-68.log for more details
>>>>>> ----------------------
>>>>>> Please see .kitchen/logs/kitchen.log for more details
>>>>>> Also try running `kitchen diagnose --all` for configuration
</code>```

I have the same issue when using the guide listed on the readme for kitchen-puppet.

Whenever I attempt to run kitchen converge I continue to get the error message:

```<code>cp: cannot stat `/tmp/kitchen/hiera/*': No such file or directory
</code>```

The issue could be that I am running this though bundler (version 1.14.6) and I also set my puppet version to the same one as the guide gem "puppet", "~> 4.10.4" to get around librarian-puppet issues.  Here is the full output of my converge:

```<code>$ bundle exec kitchen converge
-----> Starting Kitchen (v1.16.0)
-----> Converging <default-nocm-ubuntu-1204>...
       Preparing files for transfer
       Preparing modules
       Resolving module dependencies with Librarian-Puppet 2.2.3...
       Preparing manifests
       Preparing files
       nothing to do for files
       Preparing hiera data
       Finished Preparing files for transfer
       Installing puppet, will try to determine platform os
       Install busser on nocm_ubuntu
       Transferring files to <default-nocm-ubuntu-1204>
       cp: cannot stat `/tmp/kitchen/hiera/*': No such file or directory
-----> Converging <default-centos-65>...
       Preparing files for transfer
       Preparing modules
       Resolving module dependencies with Librarian-Puppet 2.2.3...
       Preparing manifests
       Preparing files
       nothing to do for files
       Preparing hiera data
       Finished Preparing files for transfer
       Installing puppet from yum on centos
       Install busser on centos
       Transferring files to <default-centos-65>
       cp: cannot stat `/tmp/kitchen/hiera/*': No such file or directory
>>>>>> ------Exception-------
>>>>>> Class: Kitchen::ActionFailed
>>>>>> Message: 2 actions failed.
>>>>>>     Converge failed on instance <default-nocm-ubuntu-1204>.  Please see .kitchen/logs/default-nocm-ubuntu-1204.log for more details
>>>>>>     Converge failed on instance <default-centos-65>.  Please see .kitchen/logs/default-centos-65.log for more details
>>>>>> ----------------------
>>>>>> Please see .kitchen/logs/kitchen.log for more details
>>>>>> Also try running `kitchen diagnose --all` for configuration
</code>```

How can I debug this issue?

答:
So the issue was caused by a missing hieradata file structure. This example was a big help and details a full kitchen-puppet file structure:

https://github.com/neillturner/puppet_vagrant_repo

In the main directory of my project I needed to create the following empty files:

```<code>hieradata/
├── common.yaml
└── roles
    └── default.yaml
</code>```

Then change provisioner in .kitchen.yml to specify this path:

```<code>provisioner:
  name: puppet_apply
  manifests_path: manifests
  modules_path: modules
  hiera_data_path: hieradata
</code>```

Last I needed to set driver_plugin: vagrant in all my platforms.

This is my new .kitchen.yml for the example in the guide I mentioned:

```<code>---
driver:
  name: vagrant

provisioner:
  name: puppet_apply
  manifests_path: manifests
  modules_path: modules
  hiera_data_path: hieradata

platforms:
  - name: nocm_ubuntu-12.04
    driver_plugin: vagrant
    driver_config:
      box: nocm_ubuntu-12.04
      box_url: http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-server-12042-x64-vbox4210-nocm.box
  - name: centos-6.5
    driver_plugin: vagrant
    driver_config:
      box: nocm_centos-6.5
      box_url: http://puppet-vagrant-boxes.puppetlabs.com/centos-65-x64-virtualbox-nocm.box

suites:
  - name: default
    manifest: site.pp
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a puppet deployment using kitchen-puppet.

Here is what my kitchen file looks like:

---
driver:
  name: vagrant

provisioner:
  name: puppet_apply
  manifests_path: /repository/puppet_repo/manifests
  modules_path: /repository/puppet_repo/modules-mycompany
  hiera_data_path: /repository/puppet_repo/hieradata

platforms:
- name: centos-6.8
- name: centos-7.2
- name: debian-7.8
- name: ubuntu-12.04
- name: ubuntu-14.04
- name: ubuntu-16.04

suites:
  - name: default

When I attempt to use it I get the following error message:

$ bundle exec kitchen converge default-centos-68
-----> Starting Kitchen (v1.16.0)
-----> Converging <default-centos-68>...
       Preparing files for transfer
       Preparing modules
       Nothing to do for modules
       Preparing manifests
       Preparing files
       nothing to do for files
       Preparing hiera data
       Finished Preparing files for transfer
       Installing puppet from yum on centos
       Install busser on centos
       Transferring files to <default-centos-68>
       cp: cannot stat `/tmp/kitchen/hiera/*': No such file or directory
>>>>>> ------Exception-------
>>>>>> Class: Kitchen::ActionFailed
>>>>>> Message: 1 actions failed.
>>>>>>     Converge failed on instance <default-centos-68>.  Please see .kitchen/logs/default-centos-68.log for more details
>>>>>> ----------------------
>>>>>> Please see .kitchen/logs/kitchen.log for more details
>>>>>> Also try running `kitchen diagnose --all` for configuration

I have the same issue when using the guide listed on the readme for kitchen-puppet.

Whenever I attempt to run kitchen converge I continue to get the error message:

cp: cannot stat `/tmp/kitchen/hiera/*': No such file or directory

The issue could be that I am running this though bundler (version 1.14.6) and I also set my puppet version to the same one as the guide gem "puppet", "~> 4.10.4" to get around librarian-puppet issues.  Here is the full output of my converge:

$ bundle exec kitchen converge
-----> Starting Kitchen (v1.16.0)
-----> Converging <default-nocm-ubuntu-1204>...
       Preparing files for transfer
       Preparing modules
       Resolving module dependencies with Librarian-Puppet 2.2.3...
       Preparing manifests
       Preparing files
       nothing to do for files
       Preparing hiera data
       Finished Preparing files for transfer
       Installing puppet, will try to determine platform os
       Install busser on nocm_ubuntu
       Transferring files to <default-nocm-ubuntu-1204>
       cp: cannot stat `/tmp/kitchen/hiera/*': No such file or directory
-----> Converging <default-centos-65>...
       Preparing files for transfer
       Preparing modules
       Resolving module dependencies with Librarian-Puppet 2.2.3...
       Preparing manifests
       Preparing files
       nothing to do for files
       Preparing hiera data
       Finished Preparing files for transfer
       Installing puppet from yum on centos
       Install busser on centos
       Transferring files to <default-centos-65>
       cp: cannot stat `/tmp/kitchen/hiera/*': No such file or directory
>>>>>> ------Exception-------
>>>>>> Class: Kitchen::ActionFailed
>>>>>> Message: 2 actions failed.
>>>>>>     Converge failed on instance <default-nocm-ubuntu-1204>.  Please see .kitchen/logs/default-nocm-ubuntu-1204.log for more details
>>>>>>     Converge failed on instance <default-centos-65>.  Please see .kitchen/logs/default-centos-65.log for more details
>>>>>> ----------------------
>>>>>> Please see .kitchen/logs/kitchen.log for more details
>>>>>> Also try running `kitchen diagnose --all` for configuration

How can I debug this issue?

Body:
So the issue was caused by a missing hieradata file structure. This example was a big help and details a full kitchen-puppet file structure:

https://github.com/neillturner/puppet_vagrant_repo

In the main directory of my project I needed to create the following empty files:

hieradata/
├── common.yaml
└── roles
    └── default.yaml

Then change provisioner in .kitchen.yml to specify this path:

provisioner:
  name: puppet_apply
  manifests_path: manifests
  modules_path: modules
  hiera_data_path: hieradata

Last I needed to set driver_plugin: vagrant in all my platforms.

This is my new .kitchen.yml for the example in the guide I mentioned:

---
driver:
  name: vagrant

provisioner:
  name: puppet_apply
  manifests_path: manifests
  modules_path: modules
  hiera_data_path: hieradata

platforms:
  - name: nocm_ubuntu-12.04
    driver_plugin: vagrant
    driver_config:
      box: nocm_ubuntu-12.04
      box_url: http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-server-12042-x64-vbox4210-nocm.box
  - name: centos-6.5
    driver_plugin: vagrant
    driver_config:
      box: nocm_centos-6.5
      box_url: http://puppet-vagrant-boxes.puppetlabs.com/centos-65-x64-virtualbox-nocm.box

suites:
  - name: default
    manifest: site.pp


问:
PL SQL - Convert timestamp to datetime/date
```<code>select
to_timestamp(SCHEDULED_TIME,'YYYY-MM-DD HH24:MI:SS.FF') as SCHEDULED_TIME,
TRUNC(to_date(to_timestamp(SCHEDULED_TIME,'YYYY-MM-DD HH24:MI:SS.FF'),'YYYY-MM-DD HH24:MI:SS'))
from S_TIDAL_STATUS
</code>```

The error was:
ORA-01830: date format picture ends before converting entire input string
01830. 00000 -  "date format picture ends before converting entire input string"

The goal is to return something like

2017-07-91 23:14:00
(without the content after the dot).

Here's what the SCHEDULED_TIME (timestamp) looked like:

答:
The problem in your attempt is the function TO_DATE() applied to a timestamp. TO_DATE() takes a VARCHAR2 (string) input, not a timestamp. So Oracle converts the timestamp to a string first, implicitly, using your NLS_TIMESTAMP_FORMAT parameter, and then attempts to convert this string to a date. Depending on your NLS_TIMESTAMP_FORMAT, you may get different errors.

The way to convert a timestamp to a date (datetime) - while truncating off the fractions of a second - is with the CAST function. Example:

```<code>select systimestamp,
       cast (systimestamp as date) as ts_cast_to_date
from   dual
;
</code>```

Alternatively, if all your strings are EXACTLY in that format, you can truncate the strings first and apply TO_DATE directly:

```<code>to_date(substr(scheduled_time, 1, 19), 'yyyy-mm-dd hh24:mi:ss')
</code>```

Body:
select
to_timestamp(SCHEDULED_TIME,'YYYY-MM-DD HH24:MI:SS.FF') as SCHEDULED_TIME,
TRUNC(to_date(to_timestamp(SCHEDULED_TIME,'YYYY-MM-DD HH24:MI:SS.FF'),'YYYY-MM-DD HH24:MI:SS'))
from S_TIDAL_STATUS

The error was:
ORA-01830: date format picture ends before converting entire input string
01830. 00000 -  "date format picture ends before converting entire input string"

The goal is to return something like

2017-07-91 23:14:00
(without the content after the dot).

Here's what the SCHEDULED_TIME (timestamp) looked like:

Body:
The problem in your attempt is the function TO_DATE() applied to a timestamp. TO_DATE() takes a VARCHAR2 (string) input, not a timestamp. So Oracle converts the timestamp to a string first, implicitly, using your NLS_TIMESTAMP_FORMAT parameter, and then attempts to convert this string to a date. Depending on your NLS_TIMESTAMP_FORMAT, you may get different errors.

The way to convert a timestamp to a date (datetime) - while truncating off the fractions of a second - is with the CAST function. Example:

select systimestamp,
       cast (systimestamp as date) as ts_cast_to_date
from   dual
;

Alternatively, if all your strings are EXACTLY in that format, you can truncate the strings first and apply TO_DATE directly:

to_date(substr(scheduled_time, 1, 19), 'yyyy-mm-dd hh24:mi:ss')


问:
How to represent nested one to many relationship in android room?
Here are sample POJO:

```<code>@Entity
public class User {
  @PrimaryKey
  public String id;
}

@Entity
public class Pet {
  @PrimaryKey
  public String id;
  public String userId;
  public String petName;
}

@Entity
public class Category {
  @PrimaryKey
  public String id;
  public String petId;
  public String categoryName;
}
</code>```

Here is my UsersWithPets class to fetch all the users along with pets.

```<code>public class UserWithPets {
  @Embedded
  public User user;
  @Relation(parentColumn = "id", entityColumn = "userId", entity =   Pet.class)
  public List<Pet> pets;
}
</code>```

My user Dao

```<code>@Dao
public interface UserDao {
  @Query("SELECT * FROM User")
  List<UserWithPets> loadUsersWithPets();
}
</code>```

and userdb

```<code>@Database(entities = {User.class, Pet.class, Category.class}, version = 1)
@TypeConverters(DateConverter.class)
public abstract class UsersDb extends RoomDatabase {

  private static UsersDb INSTANCE;

  public abstract UserDao userDao();

  public static UsersDb getInstance(Context context) {
      if (INSTANCE == null) {
          synchronized (UsersDb.class) {
              if (INSTANCE == null) {
                  INSTANCE = Room.databaseBuilder(context.getApplicationContext(), UsersDb.class,
                          "User.db")
                          .build();
              }
          }
      }
      return INSTANCE;
  }
}
</code>```

The "UserWithPets" embeds user object and relates with its associated list of "Pet", but how do I fetch list of "Category" if my "Pet" POJO can have 1-many relationship with "Category".

Also the user DAO only returns all the "User" along with its "List<Pet>" by mapping the id between user.id and pet.userId, if my "Pet" POJO can have many "Category"(List of Category), how do I create my DAO and abstract database class such that querying for a particular "User" id will return me the "User" object along with its "List of Pets" and individual "Pet" containing a "List of Category" and querying for all will return all the "List of Users" wherein each User contains a "List of Pet" and each Pet contains a "List of Category"

答:
Probably it would be easier to start additional database requests after you finished the first one. I don't see any way to realize that via @Relation or with inner joins as this is not a single value you want to return. You could use left join, but that would give you multiple pets, only with different category objects. </p>

```<code>List<UserWithPets> list = userDao.loadUsersWithPets();
for(UserWithPets user : list) {
   for(Pet pet : user.pets) {
      pet.categories = categorieDao.getCategoriesByPetId(pet.id);
      //pet.categories should have the @Ignore annotation
   }
}

...

@Dao
public interface CategoryDao {

   @Query("SELECT * FROM Category WHERE petId = :petId")
   List<Categories> getCategoriesByPetId(int petId);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here are sample POJO:

@Entity
public class User {
  @PrimaryKey
  public String id;
}

@Entity
public class Pet {
  @PrimaryKey
  public String id;
  public String userId;
  public String petName;
}

@Entity
public class Category {
  @PrimaryKey
  public String id;
  public String petId;
  public String categoryName;
}

Here is my UsersWithPets class to fetch all the users along with pets.

public class UserWithPets {
  @Embedded
  public User user;
  @Relation(parentColumn = "id", entityColumn = "userId", entity =   Pet.class)
  public List<Pet> pets;
}

My user Dao

@Dao
public interface UserDao {
  @Query("SELECT * FROM User")
  List<UserWithPets> loadUsersWithPets();
}

and userdb

@Database(entities = {User.class, Pet.class, Category.class}, version = 1)
@TypeConverters(DateConverter.class)
public abstract class UsersDb extends RoomDatabase {

  private static UsersDb INSTANCE;

  public abstract UserDao userDao();

  public static UsersDb getInstance(Context context) {
      if (INSTANCE == null) {
          synchronized (UsersDb.class) {
              if (INSTANCE == null) {
                  INSTANCE = Room.databaseBuilder(context.getApplicationContext(), UsersDb.class,
                          "User.db")
                          .build();
              }
          }
      }
      return INSTANCE;
  }
}

The "UserWithPets" embeds user object and relates with its associated list of "Pet", but how do I fetch list of "Category" if my "Pet" POJO can have 1-many relationship with "Category".

Also the user DAO only returns all the "User" along with its "List<Pet>" by mapping the id between user.id and pet.userId, if my "Pet" POJO can have many "Category"(List of Category), how do I create my DAO and abstract database class such that querying for a particular "User" id will return me the "User" object along with its "List of Pets" and individual "Pet" containing a "List of Category" and querying for all will return all the "List of Users" wherein each User contains a "List of Pet" and each Pet contains a "List of Category"

Body:
Probably it would be easier to start additional database requests after you finished the first one. I don't see any way to realize that via @Relation or with inner joins as this is not a single value you want to return. You could use left join, but that would give you multiple pets, only with different category objects.

List<UserWithPets> list = userDao.loadUsersWithPets();
for(UserWithPets user : list) {
   for(Pet pet : user.pets) {
      pet.categories = categorieDao.getCategoriesByPetId(pet.id);
      //pet.categories should have the @Ignore annotation
   }
}

...

@Dao
public interface CategoryDao {

   @Query("SELECT * FROM Category WHERE petId = :petId")
   List<Categories> getCategoriesByPetId(int petId);
}


问:
Access Protected Excel File with ExcelDataReader and Epplus
title pretty much says it all. Looking for a way to access a password protected excel file with ExcelDataReader and Epplus, can't find a proper answer.

If using ExcelDataReader, my code looks like

```<code>                excelStream = File.Open(excelFilePath, FileMode.Open, FileAccess.Read);
                excelReader = ExcelReaderFactory.CreateOpenXmlReader(excelStream);
                excelDataSet = excelReader.AsDataSet();
</code>```

If using EPPlus my connection code looks like

```<code>            excelPackage = new ExcelPackage(new FileInfo(excelFilePath));
            excelWorkbook = excelPackage.Workbook;
            excelSheet = excelWorkbook.Worksheets[1];
</code>```

EPPlus has some protection related methods but i can't figure out  how to use them. ExcelDataReader doesnt seem to have any protection related methods.

Any tips appreciated, thanks.

EDIT: I do already know the password

答:
With EPPlus you can use

excelPackage = new ExcelPackage(new FileInfo(excelFilePath), "mypassword");

ExcelDataReader now supports opening password protected sheets. I opened an issue on their GitHub asking if they have such support and received a response saying that they do not, but after sometime they added support for some password methods. Details on the password methods they still do not support are in the link.

Body:
title pretty much says it all. Looking for a way to access a password protected excel file with ExcelDataReader and Epplus, can't find a proper answer.

If using ExcelDataReader, my code looks like

                excelStream = File.Open(excelFilePath, FileMode.Open, FileAccess.Read);
                excelReader = ExcelReaderFactory.CreateOpenXmlReader(excelStream);
                excelDataSet = excelReader.AsDataSet();

If using EPPlus my connection code looks like

            excelPackage = new ExcelPackage(new FileInfo(excelFilePath));
            excelWorkbook = excelPackage.Workbook;
            excelSheet = excelWorkbook.Worksheets[1];

EPPlus has some protection related methods but i can't figure out  how to use them. ExcelDataReader doesnt seem to have any protection related methods.

Any tips appreciated, thanks.

EDIT: I do already know the password


问:
How can I compile and load the pure CSS in ReactJS with webpack?
I am using a simple CSS based template for a ReactJS application with webpack module and not able to connect the CSS after compilation.

My webpack configuration looks like this...

var rucksack = require('rucksack-css')
var webpack = require('webpack')
var path = require('path')

module.exports = {
  context: path.join(__dirname, './src'),
  entry: {
    css : './public/assets/css/main.css',
    jsx: './index.js',
    html: './public/index.html',
    vendor: [
      'react',
      'react-dom',
      'react-redux',
      'react-router',
      'react-router-redux',
      'redux'
    ]
  },
  output: {
    path: path.join(__dirname, './static'),
    filename: 'bundle.js',
  },
  module: {
    loaders: [
      {
        test: /\.html$/,
        loader: 'file?name=[name].[ext]'
      },
      {
        test: /\.css$/,
        include: /src/,
        loaders: [
          'style-loader',
          'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[local]___[hash:base64:5]',
          'postcss-loader'
        ]
      },
      {
        test: /\.css$/,
        exclude: /src/,
        loader: 'style!css'
      },
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loaders: [
          'react-hot',
          'babel-loader'
        ]
      },
    ],
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  postcss: [
    rucksack({
      autoprefixer: true
    })
  ],
  plugins: [

    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'),
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development') }
    })
  ],
  devServer: {
    contentBase: './src',
    hot: true
  }
}```

and relative path for my css file is 'src/public/assets/css/main.css'.
Is there any way to use pure traditional CSS without changing it to the react based CSS-in-JS ?

答:
You could use the extract-text-webpack-plugin to pull your css out  of your JS files. I believe the general best practice is to use the 'CSS-in-JS' (as you mentioned it) while working in development to benefit from hot-reloading. And then using the plugin above to build for production.

Also, it seems as though your config file has some redundancy.

```<code> {
    test: /\.css$/,
    include: /src/,
    loaders: [
      'style-loader',
      'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[local]___[hash:base64:5]',
      'postcss-loader'
    ]
  },
  {
    test: /\.css$/, // <--- this test seems redunant. Perhaps remove it.
    exclude: /src/,
    loader: 'style!css'
  },
</code>```

Body:
I am using a simple CSS based template for a ReactJS application with webpack module and not able to connect the CSS after compilation.

My webpack configuration looks like this...

var rucksack = require('rucksack-css')
var webpack = require('webpack')
var path = require('path')

module.exports = {
  context: path.join(__dirname, './src'),
  entry: {
    css : './public/assets/css/main.css',
    jsx: './index.js',
    html: './public/index.html',
    vendor: [
      'react',
      'react-dom',
      'react-redux',
      'react-router',
      'react-router-redux',
      'redux'
    ]
  },
  output: {
    path: path.join(__dirname, './static'),
    filename: 'bundle.js',
  },
  module: {
    loaders: [
      {
        test: /\.html$/,
        loader: 'file?name=[name].[ext]'
      },
      {
        test: /\.css$/,
        include: /src/,
        loaders: [
          'style-loader',
          'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[local]___[hash:base64:5]',
          'postcss-loader'
        ]
      },
      {
        test: /\.css$/,
        exclude: /src/,
        loader: 'style!css'
      },
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loaders: [
          'react-hot',
          'babel-loader'
        ]
      },
    ],
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  postcss: [
    rucksack({
      autoprefixer: true
    })
  ],
  plugins: [

    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'),
    new webpack.DefinePlugin({
      'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development') }
    })
  ],
  devServer: {
    contentBase: './src',
    hot: true
  }
}

and relative path for my css file is 'src/public/assets/css/main.css'.
Is there any way to use pure traditional CSS without changing it to the react based CSS-in-JS ?

Body:
You could use the extract-text-webpack-plugin to pull your css out  of your JS files. I believe the general best practice is to use the 'CSS-in-JS' (as you mentioned it) while working in development to benefit from hot-reloading. And then using the plugin above to build for production.

Also, it seems as though your config file has some redundancy.

 {
    test: /\.css$/,
    include: /src/,
    loaders: [
      'style-loader',
      'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[local]___[hash:base64:5]',
      'postcss-loader'
    ]
  },
  {
    test: /\.css$/, // <--- this test seems redunant. Perhaps remove it.
    exclude: /src/,
    loader: 'style!css'
  },


问:
Help required in Alarm Application
I am new to Android. I am trying to develop an Alarm Application, which is actually a speaking clock. I just want the clock to use TextToSpeech API and speak out the greeting stuff and the current time as soon as the alarm time is ticked. The speech part is done. And now I want to implement the Alarm functionality. But Initially I am just trying to display a toast after 10 secs in order to check whether my classes are working properly. And I am not getting the desired response and I don't know why ? Following are the classes

Main Class aClockActivity

```<code>public class aClockActivity extends Activity {
    /** Called when the activity is first created. */
  private PendingIntent mAlarmSender;

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        Button button1 = (Button)findViewById(R.id.buttonOn);
        button1.setOnClickListener(mStartAlarmListener);
        Button button2 = (Button)findViewById(R.id.buttonOff);
        button2.setOnClickListener(mStopAlarmListener);

    }

 private OnClickListener mStartAlarmListener = new OnClickListener() {
        public void onClick(View v) {
            // We want the alarm to go off 30 seconds from now.
            //long firstTime = SystemClock.elapsedRealtime();
            EditText Ehour = (EditText) findViewById(R.id.hour);
            EditText Eminute = (EditText) findViewById(R.id.minute);

            CharSequence CharHour = Ehour.getText();
            CharSequence CharMinute = Eminute.getText();
            int hour = Integer.parseInt(CharHour.toString());
            int minute = Integer.parseInt(CharMinute.toString());

            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(System.currentTimeMillis());
           // calendar.add(Calendar.MINUTE, 1);
            cal.add(Calendar.SECOND, 10);

            mAlarmSender = PendingIntent.getBroadcast(aClockActivity.this,
                    0, new Intent(aClockActivity.this, Alarm_Broadcast.class), 0);

            // Schedule the alarm!
            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP,
                            cal.getTimeInMillis(), mAlarmSender);

            // Tell the user about what we did.
            Toast.makeText(aClockActivity.this, "The Alarm is Set",
                    Toast.LENGTH_LONG).show();
        }
    };

    private OnClickListener mStopAlarmListener = new OnClickListener() {
        public void onClick(View v) {
            // And cancel the alarm.
            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
            am.cancel(mAlarmSender);

            // Tell the user about what we did.
            Toast.makeText(aClockActivity.this, "Setting off the alarm",
                    Toast.LENGTH_LONG).show();

        }
    };
</code>```

Second Class Alarm_Broadcast

```<code>public class Alarm_Broadcast extends BroadcastReceiver{
  @Override
     public void onReceive(Context context, Intent intent) {
         Toast.makeText(context, "Alarm worked", Toast.LENGTH_LONG).show();
     }

}
</code>```

Note: Just ignore the Edittext part in the OnClick() method, I'd use it later on.

Apart from the above problem there are few questions that I would like to ask.

1) How can I implement this app so that when the alarm is set, it can actually run as a service in the notification bar where the original AlarmClock runs. So that even if the app is closed its still running to invoke the alarm message at the right time.

2) I cannot show any Dialog box or can use TTS if the AlarmManager invokes a Class that extends either Service or BroadcastReciever.

3) I would appreciate if some one give me the idea to implement this app, I am sure there are many experts who would have gone through the same application.

Regards

Omayr

答: Just got the answer, whatever service, receiver, activity and etc you are using, you need to register it in your AndroidManifest.xml. Or else it wont work</p>

ContentLicense: CC BY-SA 2.5

Title: Help required in Alarm Application

Body:
I am new to Android. I am trying to develop an Alarm Application, which is actually a speaking clock. I just want the clock to use TextToSpeech API and speak out the greeting stuff and the current time as soon as the alarm time is ticked. The speech part is done. And now I want to implement the Alarm functionality. But Initially I am just trying to display a toast after 10 secs in order to check whether my classes are working properly. And I am not getting the desired response and I don't know why ? Following are the classes

Main Class aClockActivity

public class aClockActivity extends Activity {
    /** Called when the activity is first created. */
  private PendingIntent mAlarmSender;

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        Button button1 = (Button)findViewById(R.id.buttonOn);
        button1.setOnClickListener(mStartAlarmListener);
        Button button2 = (Button)findViewById(R.id.buttonOff);
        button2.setOnClickListener(mStopAlarmListener);

    }

 private OnClickListener mStartAlarmListener = new OnClickListener() {
        public void onClick(View v) {
            // We want the alarm to go off 30 seconds from now.
            //long firstTime = SystemClock.elapsedRealtime();
            EditText Ehour = (EditText) findViewById(R.id.hour);
            EditText Eminute = (EditText) findViewById(R.id.minute);

            CharSequence CharHour = Ehour.getText();
            CharSequence CharMinute = Eminute.getText();
            int hour = Integer.parseInt(CharHour.toString());
            int minute = Integer.parseInt(CharMinute.toString());

            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(System.currentTimeMillis());
           // calendar.add(Calendar.MINUTE, 1);
            cal.add(Calendar.SECOND, 10);

            mAlarmSender = PendingIntent.getBroadcast(aClockActivity.this,
                    0, new Intent(aClockActivity.this, Alarm_Broadcast.class), 0);

            // Schedule the alarm!
            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
            am.set(AlarmManager.RTC_WAKEUP,
                            cal.getTimeInMillis(), mAlarmSender);

            // Tell the user about what we did.
            Toast.makeText(aClockActivity.this, "The Alarm is Set",
                    Toast.LENGTH_LONG).show();
        }
    };

    private OnClickListener mStopAlarmListener = new OnClickListener() {
        public void onClick(View v) {
            // And cancel the alarm.
            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
            am.cancel(mAlarmSender);

            // Tell the user about what we did.
            Toast.makeText(aClockActivity.this, "Setting off the alarm",
                    Toast.LENGTH_LONG).show();

        }
    };

Second Class Alarm_Broadcast

public class Alarm_Broadcast extends BroadcastReceiver{
  @Override
     public void onReceive(Context context, Intent intent) {
         Toast.makeText(context, "Alarm worked", Toast.LENGTH_LONG).show();
     }

}

Note: Just ignore the Edittext part in the OnClick() method, I'd use it later on.

Apart from the above problem there are few questions that I would like to ask.

1) How can I implement this app so that when the alarm is set, it can actually run as a service in the notification bar where the original AlarmClock runs. So that even if the app is closed its still running to invoke the alarm message at the right time.

2) I cannot show any Dialog box or can use TTS if the AlarmManager invokes a Class that extends either Service or BroadcastReciever.

3) I would appreciate if some one give me the idea to implement this app, I am sure there are many experts who would have gone through the same application.

Regards

Omayr


问:
FPGA - CPU Latency measurement with C/C++
I am trying to measure Read/write Latency between an ARM CPU and An FPGA in the same board. I am wondering if using the global timer is sufficient to report this latency in term of clock cycles, because the ARM and the FPGA are running at different frequency.
My scenario is</p>

```<code>    resetTimer();
    startTimer();
    for(i=0; i<1000; i++) {
      T1 = readTimer();
      writeToFpgaIP(int* regAddress, int data);
      T2 = readTimer();
      storeInArray(T2-T1);
    }
    StopTimer();
    latency  = sum (array_write_timing[]) / 1000;
    -*-*-*-End algo-*-*-*
</code>```

答: Rather than using an external scope or logic analyzer, I tend to add performance measurement to the FPGA. That way, I can measure the total and average number of cycles for handling requests from the CPU and I can also measure the CPU overhead by performing back to back requests and measuring total elapsed cycles. I often also measure the quantity of data transferred in either direction.</p>

Body:
I am trying to measure Read/write Latency between an ARM CPU and An FPGA in the same board. I am wondering if using the global timer is sufficient to report this latency in term of clock cycles, because the ARM and the FPGA are running at different frequency.
My scenario is

    resetTimer();
    startTimer();
    for(i=0; i<1000; i++) {
      T1 = readTimer();
      writeToFpgaIP(int* regAddress, int data);
      T2 = readTimer();
      storeInArray(T2-T1);
    }
    StopTimer();
    latency  = sum (array_write_timing[]) / 1000;
    -*-*-*-End algo-*-*-*


问:
Why can't I place this class using the tkinter grid method?
I have an existing Python 3 program which I wrote quick-and-dirty without any object-oriented techniques (it was my first Python program). It's time I clean it up, and I'm having problems making tkinter work in my classes.

Here is a simplified example. It is only attempting to place a ttk.Entry widget into the class, which is inheriting from ttk.Frame:

```<code>import tkinter as tk
from tkinter import ttk

class MyClass(ttk.Frame):
    def __init__(self, parent):
        self.frame = ttk.Frame(parent)

        # Entry widget
        self.entValue = ttk.Entry(self.frame)
        self.entValue.grid(column=0, row=0)

# tkinter init
root = tk.Tk()

# Make the class instance and place it
test = MyClass(root)
test.grid(column=0, row=0)
</code>```

It gives me the following error:

```<code>Traceback (most recent call last):
  File "{path_to_code}/so.py", line 17, in <module>
    test.grid(column=0, row=0)
  File "{path_to_python}\Python35-32\lib\tkinter\__init__.py", line 2072, in grid_configure
    self.tk.call(
AttributeError: 'MyClass' object has no attribute 'tk'
</code>```

What am I missing?

答:
Your Frame hasn't been initialized. Add super().__init__(parent) to the top of your MyClass.__init__ method to allow ttk to initialize the frame.

Also, I think you can get rid of self.frame. Set self as the parent for the widgets in MyClass instead of self.frame.

Body:
I have an existing Python 3 program which I wrote quick-and-dirty without any object-oriented techniques (it was my first Python program). It's time I clean it up, and I'm having problems making tkinter work in my classes.

Here is a simplified example. It is only attempting to place a ttk.Entry widget into the class, which is inheriting from ttk.Frame:

import tkinter as tk
from tkinter import ttk

class MyClass(ttk.Frame):
    def __init__(self, parent):
        self.frame = ttk.Frame(parent)

        # Entry widget
        self.entValue = ttk.Entry(self.frame)
        self.entValue.grid(column=0, row=0)

# tkinter init
root = tk.Tk()

# Make the class instance and place it
test = MyClass(root)
test.grid(column=0, row=0)

It gives me the following error:

Traceback (most recent call last):
  File "{path_to_code}/so.py", line 17, in <module>
    test.grid(column=0, row=0)
  File "{path_to_python}\Python35-32\lib\tkinter\__init__.py", line 2072, in grid_configure
    self.tk.call(
AttributeError: 'MyClass' object has no attribute 'tk'

What am I missing?


答:
I have been loving the lubridate package for working with dates. Super slick. The quarter function finds the quarter (of course) and then just pair that with the year.

```<code>library(lubridate)
Data <- Data %>%
  mutate(qtr = paste0(substring(year(date),3,4),"/0",quarter(date)))
</code>```

If you are not familiar with the %>% from magrittr the first line basically says "use data frame called Data" and the second line says "mutate (or add) a column called qtr"

EDIT 2021-Q2

If the "YY/QQ" format is not critical, then a quick and safe way to get the year and the quarter is:

```<code>library(lubridate)
Data %>%
  mutate(qtr = quarter(date, with_year = T))
</code>```

Title: Format date as Year/Quarter

Body:
I have the following dataframe:

Data <- data.frame(
  date = c("2001-01-01", "2001-02-01", "2001-03-01", "2001-04-01", "2001-05-01", "2001-06-01"),
  qtr = c("NA", "NA","NA","NA","NA","NA")
)

I want to fill Data$qtr with Year/Quarter - f.e. 01/01 (I need this format!).

I wrote a function:

fun <- function(x) {
  if(x == "2001-01-01" | x == "2001-02-01" | x == "2001-03-01") y <- "01/01"
  if(x == "2001-04-01" | x == "2001-05-01" | x == "2001-06-01") y <- "01/02"
  return(y)
}
n$qtr <- sapply(n$date, fun)

But it does not work. I always get the error message:

Error in FUN(X[[1L]], ...) : Object 'y' not found

Why?

Body:
I have been loving the lubridate package for working with dates. Super slick. The quarter function finds the quarter (of course) and then just pair that with the year.

library(lubridate)
Data <- Data %>%
  mutate(qtr = paste0(substring(year(date),3,4),"/0",quarter(date)))

If you are not familiar with the %>% from magrittr the first line basically says "use data frame called Data" and the second line says "mutate (or add) a column called qtr"

EDIT 2021-Q2

If the "YY/QQ" format is not critical, then a quick and safe way to get the year and the quarter is:

library(lubridate)
Data %>%
  mutate(qtr = quarter(date, with_year = T))


问:
Subsequent HTML not being displayed after PHP call
I am relatively new to PHP programming. I am building a small crud app (to-do list) to be exact for practice. I am working on fleshing out the UI and testing how information displays from my database on the page.

When a user logs in, they are shown a table of all the items they have saved.

table listing items

```<code>  <div class="container">
    <table class="table">
      <tr>
        <th>Completed</th>
        <th>Description</th>
        <th>Actions</th>
      </tr>
      <tr>
        <td colspan="3"></td>
      </tr>
      <?php
      $document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");
      while($match_value = mysql_fetch_array($document_get)) {
      ?>
      <tr>
        <td>
          Hi
        </td>
      </tr>
    </table>
    <?php
    }
    ?>
  </div>
</code>```

php call to display list item

```<code>      <?php
      $document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");
      while($match_value = mysql_fetch_array($document_get)) {
      ?>
</code>```

Anything under this PHP request does not show up for some reason. I have looked at other posts where people have mentioned the same thing but I did not see anything specific that matched my issue per say.

答:
mysql_fetch_array returns an array. The structure of your while statement will not have the outcome that you desire. The while loop will continue to be true forever because nothing is changing in the while condition.

This should have the effect closer to what you are looking for:

```<code>$document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");
$match_value = mysql_fetch_array($document_get);
foreach ($match_value as $value){
    //Do something
}
</code>```

As a side note - I would highly recommend using PDO and not putting php in-line with html. Tutorial here: https://phpdelusions.net/pdo

If you use PDO your loop would look more like this:

```<code>while($row = $st->fetch(PDO::FETCH_ASSOC)){
    //Do something
}
</code>```

Body:
I am relatively new to PHP programming. I am building a small crud app (to-do list) to be exact for practice. I am working on fleshing out the UI and testing how information displays from my database on the page.

When a user logs in, they are shown a table of all the items they have saved.

table listing items

        Completed
        Description
        Actions

      <?php
      $document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");
      while($match_value = mysql_fetch_array($document_get)) {
      ?>

          Hi

    <?php
    }
    ?>

php call to display list item

      <?php
      $document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");
      while($match_value = mysql_fetch_array($document_get)) {
      ?>

Anything under this PHP request does not show up for some reason. I have looked at other posts where people have mentioned the same thing but I did not see anything specific that matched my issue per say.

Body:
mysql_fetch_array returns an array. The structure of your while statement will not have the outcome that you desire. The while loop will continue to be true forever because nothing is changing in the while condition.

This should have the effect closer to what you are looking for:

$document_get = mysql_query("SELECT * FROM todolist WHERE user_id='$user_id' ORDER BY id DESC");
$match_value = mysql_fetch_array($document_get);
foreach ($match_value as $value){
    //Do something
}

As a side note - I would highly recommend using PDO and not putting php in-line with html. Tutorial here: https://phpdelusions.net/pdo

If you use PDO your loop would look more like this:

while($row = $st->fetch(PDO::FETCH_ASSOC)){
    //Do something
}


问:
Is there a difference between int(floatvar) and (int)floatvar?

Possible Duplicate:

  C++: What's the difference between function(myVar) and (function)myVar ?

I have seen and used both variants of these typecasts:

```<code>int(floatvar)

(int)floatvar
</code>```

Is there any difference between the two? Are there any preferences about when to use which?

答: There is no difference between them.  (int)floatvar is C way of doing the cast where as int(floatvar) is the C++ way (Although it is better to be explicit and use static_cast<>).

Body:
Possible Duplicate:

  C++: What's the difference between function(myVar) and (function)myVar ?

I have seen and used both variants of these typecasts:

int(floatvar)

(int)floatvar

Is there any difference between the two? Are there any preferences about when to use which?


问:
Download a .zip file from database using C# Ado.net
I have a .zip file in the database (BLOB). I want to retrieve the same in my api. Please find below code snippet. I am able to download a zip file but not able to extract it. getting an error while extracting.</p>

```<code>public IHttpActionResult GetDownloadLetter()
{
    DownloadDocument docInfo = blogicObj.DownloadLetter();
    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(docInfo.Document.GetBuffer())
    };
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = docInfo.DocumentName + ".zip"
    };

    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
    var response = ResponseMessage(result);
    return response;
}

public class DownloadDocument
{
    public MemoryStream Document { get; set; }
    public string DocumentType { get; set; }
    public string DocumentName { get; set; }
}

public DownloadDocument DownloadDocument()
{
    DownloadDocument letter = null;
    try
    {
        letter = GetDummyDownload();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return letter;
}

public MemoryStream GetMemoryStream(SqlDataReader reader, int columnIndex)
{
    using (MemoryStream stream = new MemoryStream())
    {
        long startIdx = 0;
        byte[] buffer = new byte[256];

        while (true)
        {
            long retBytes = reader.GetBytes(columnIndex, startIdx, buffer, 0, buffer.Length);
            stream.Write(buffer, 0, (int)retBytes);
            startIdx += retBytes;
            if (retBytes != buffer.Length)
                break;
        }
        return stream;
    }
}

public DownloadDocument GetDummyDownload()
{
    DownloadDocument letter = null;
    string strQuery = "select * from [dbo].[documents] where id=1";

    using (SqlConnection connection = new SqlConnection(connStr))
    {
        SqlCommand command = new SqlCommand(connStr);
        command.CommandType = CommandType.Text;
        command.CommandText = strQuery;
        command.Connection = connection;
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        // Call Read before accessing data.
        while (reader.Read())
        {
            letter = new DownloadDocument();
            letter.Document = GetMemoryStream(reader, 4); //4 is for document column
            letter.DocumentType = Convert.ToString(reader["DocumentType"]);
            letter.DocumentName = Convert.ToString(reader["Name"]);
        }
        // Call Close when done reading.
        reader.Close();
    }
    return letter;
}
</code>```

答:
Your C# application can use J# library to extract zip file.  It's basically Java library:</p>

```<code>using(var fis = new java.io.FileInputStream(FileName))
{
    using(var zis = new java.util.zip.ZipInputStream(fis))
    {
        java.util.zip.ZipEntry ze;
        while((ze = zis.getNextEntry()) != null)
        {
            if (ze.isDirectory())
                continue;

            Console.WriteLine("File name: " + ze.getName());
        }
    }
}
</code>```

Body:
I have a .zip file in the database (BLOB). I want to retrieve the same in my api. Please find below code snippet. I am able to download a zip file but not able to extract it. getting an error while extracting.

public IHttpActionResult GetDownloadLetter()
{
    DownloadDocument docInfo = blogicObj.DownloadLetter();
    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(docInfo.Document.GetBuffer())
    };
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = docInfo.DocumentName + ".zip"
    };

    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
    var response = ResponseMessage(result);
    return response;
}

public class DownloadDocument
{
    public MemoryStream Document { get; set; }
    public string DocumentType { get; set; }
    public string DocumentName { get; set; }
}

public DownloadDocument DownloadDocument()
{
    DownloadDocument letter = null;
    try
    {
        letter = GetDummyDownload();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return letter;
}

public MemoryStream GetMemoryStream(SqlDataReader reader, int columnIndex)
{
    using (MemoryStream stream = new MemoryStream())
    {
        long startIdx = 0;
        byte[] buffer = new byte[256];

        while (true)
        {
            long retBytes = reader.GetBytes(columnIndex, startIdx, buffer, 0, buffer.Length);
            stream.Write(buffer, 0, (int)retBytes);
            startIdx += retBytes;
            if (retBytes != buffer.Length)
                break;
        }
        return stream;
    }
}

public DownloadDocument GetDummyDownload()
{
    DownloadDocument letter = null;
    string strQuery = "select * from [dbo].[documents] where id=1";

    using (SqlConnection connection = new SqlConnection(connStr))
    {
        SqlCommand command = new SqlCommand(connStr);
        command.CommandType = CommandType.Text;
        command.CommandText = strQuery;
        command.Connection = connection;
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        // Call Read before accessing data.
        while (reader.Read())
        {
            letter = new DownloadDocument();
            letter.Document = GetMemoryStream(reader, 4); //4 is for document column
            letter.DocumentType = Convert.ToString(reader["DocumentType"]);
            letter.DocumentName = Convert.ToString(reader["Name"]);
        }
        // Call Close when done reading.
        reader.Close();
    }
    return letter;
}

Body:
Your C# application can use J# library to extract zip file.  It's basically Java library:

using(var fis = new java.io.FileInputStream(FileName))
{
    using(var zis = new java.util.zip.ZipInputStream(fis))
    {
        java.util.zip.ZipEntry ze;
        while((ze = zis.getNextEntry()) != null)
        {
            if (ze.isDirectory())
                continue;

            Console.WriteLine("File name: " + ze.getName());
        }
    }
}


问:
how to send component data as json to server?
this is my setup:

```<code><template>
    <div id="" style="min-height: 100px">
        <template v-for="(block, index) in blockList">
            <component :is="block"></component>
        </template>
    </div>
</template>

<script>
    import TextBlock from './blocks/TextBlock.vue'
    import ImageBlock from './blocks/ImageBlock.vue'

    export default {
        data: function data() {
            return {
                blockList: ['text-block', 'image-block', 'text-block']
            }
        },

        props: {
            blocks: {type: Array}
        },
        // afterMount () {
        //     this.blocks.push(['text-block']);
        // },
        components: {
            TextBlock,
            ImageBlock
        }
    }
</script>

<style lang="scss">

</style>
</code>```

So just to test everything is working I added some components manually: blockList: ['text-block', 'image-block', 'text-block']

and everything renders fine on the page. However I will not be manually adding components but I will let user add them and user will be able to add any number of components. There will be more components then currently 2 I am using.

When I have added lets say 10 different components to the page and user presses Save button, how would I go about sending this data to the server? I can't just send blockList array to the server as that is just an array of strings.

What I want to do is to keep a track of all components that have been added and then with a push of button send to server a json with all components and their properties like if I had entered any text into a text component, or if I had uploaded an image into image component, I need all that data to be sent to server as well so I can recreate it when page is later reloaded for edit again.

So how can I do this as blockList: ['text-block', 'image-block', 'text-block'] wont do? How do I keep an array of components and all their properties and with push of button send this to server?

答:
Build your components to support v-model. Change your blockList data structure to look something like this:

```<code>const blockList = [
  {
    component: "text-block",
    model: null,
    label: "Name"
  },
  {
    component: "text-block",
    model: null,
    label: "Address"
  }
]
</code>```

Notice that each of the items in the blockList now has a model you can use to collect data from the component. Then, bind your component to the blocks model using v-model.

```<code><component v-for="item in blockList"
           :is="item.component"
           v-model="item.model"
           :label="item.label"
           :key="item">
</component>
</code>```

Here is an example component implementation:

```<code>const TextBlock = {
  props:["value", "label"],
  template: `
    <div>
      {{label}}
      <input type="text" @input="$emit('input', $event.target.value)" :value="value">
    </div>
  `
}
</code>```

Now, each element in the blockList will contain the data collected from that component. When you want to save that data, iterate over the blockList and pull out the data you want to submit.

Here is a working example.

In this example, I'm not doing the work of submitting the data, you can probably work that out on your own. Nor have I implemented an ImageBlock component; I'm not sure how you want that to work anyway. But following the same pattern, you should be able to support v-model on the ImageBlock component and submit the data in the same way.

Body:
this is my setup:

<template>

        <template v-for="(block, index) in blockList">
            <component :is="block"></component>
        </template>

</template>

So just to test everything is working I added some components manually: blockList: ['text-block', 'image-block', 'text-block']

and everything renders fine on the page. However I will not be manually adding components but I will let user add them and user will be able to add any number of components. There will be more components then currently 2 I am using.

When I have added lets say 10 different components to the page and user presses Save button, how would I go about sending this data to the server? I can't just send blockList array to the server as that is just an array of strings.

What I want to do is to keep a track of all components that have been added and then with a push of button send to server a json with all components and their properties like if I had entered any text into a text component, or if I had uploaded an image into image component, I need all that data to be sent to server as well so I can recreate it when page is later reloaded for edit again.

So how can I do this as blockList: ['text-block', 'image-block', 'text-block'] wont do? How do I keep an array of components and all their properties and with push of button send this to server?

Body:
Build your components to support v-model. Change your blockList data structure to look something like this:

const blockList = [
  {
    component: "text-block",
    model: null,
    label: "Name"
  },
  {
    component: "text-block",
    model: null,
    label: "Address"
  }
]

Notice that each of the items in the blockList now has a model you can use to collect data from the component. Then, bind your component to the blocks model using v-model.

<component v-for="item in blockList"
           :is="item.component"
           v-model="item.model"
           :label="item.label"
           :key="item">
</component>

Here is an example component implementation:

const TextBlock = {
  props:["value", "label"],
  template: `
    <div>
      {{label}}
      <input type="text" @input="$emit('input', $event.target.value)" :value="value">
    </div>
  `
}

Now, each element in the blockList will contain the data collected from that component. When you want to save that data, iterate over the blockList and pull out the data you want to submit.

Here is a working example.

In this example, I'm not doing the work of submitting the data, you can probably work that out on your own. Nor have I implemented an ImageBlock component; I'm not sure how you want that to work anyway. But following the same pattern, you should be able to support v-model on the ImageBlock component and submit the data in the same way.


问:
'UCS-2' not able to encode
I'm trying to read the text file but it throws one error.

```<code>UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 12416-12416: Non-BMP character not supported in Tk
</code>```

I've tried to ignore it also but it I not working.
Here is the code:

```<code>with io.open('reviews1.txt', mode='r',encoding='utf-8') as myfile:
document1=myfile.read().replace('\n', '')
print(document1)
</code>```

答:
I can reproduce the error in Python IDLE environment (Python version 3.5.1, Tk version 8.6.4, IDLE version 3.5.1). It seems to be a bug in Tk. However, the original script runs smoothly from a console (Windows cmd, in my case): Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32.

The only way I can see could be very slow: the following commented script copies the whole document character by character eliminating all ones out of the Basic Multilingual Plane.

Edit: I found this (more Python-ish) solution (thanks to Mark Ransom). Unfortunately, this runs in Python shell but Python console complains:

```<code>>>> print( ''.join(c if c <= '\uffff' else ''.join(chr(x) for x in struct.unpack(
...   '>2H', c.encode('utf-16be'))) for c in document1)
... )
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\Python\Python35\lib\site-packages\win_unicode_console\streams.py",
line 179, in write

    return self.base.write(s)
UnicodeEncodeError: 'utf-16-le' codec can't encode character '\ud83d' in position 0:
surrogates not allowed
>>>
</code>```

-

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

import sys, io
import os, codecs                       # for debugging

print(os.path.basename(sys.executable), sys.argv[0], '\n') # for debugging

#######################
### original answer ###
#######################
filepath = 'D:\\test\\reviews1.txt'
with io.open(filepath, mode='r',encoding='utf-8') as myfile:
    document1=myfile.read() #.replace('\n', '')
    document2=u''
    for character in document1:
        ordchar = ord(character)
        if ordchar <= 0xFFFF:
            # debugging # print( 'U+%.4X' % ordchar, character)
            document2+=character
        else:
            # debugging # print( 'U+%.6X' % ordchar, '�')
            ###         �=Replacement Character; codepoint=U+FFFD; utf8=0xEFBFBD
            document2+='�'
print(document2)                        # original answer, runs universally

######################
### updated answer ###
######################
if os.path.basename(sys.executable) == 'pythonw.exe':
    import struct
    document3 = ''.join(c if c <= '\uffff' else ''.join(chr(x) for x in struct.unpack('>2H', c.encode('utf-16be'))) for c in document1)
    print(document3)                    # Pythonw shell
else:
    print(document1)                    # Python console
</code>```

Output, Pythonw shell:

```<code>================== RESTART: D:/test/Python/Py/q44965129a.py ==================
pythonw.exe D:/test/Python/Py/q44965129a.py

� smiling face with smiling eyes �
� smiling face with open mouth   �
� angry face                     �

 smiling face with smiling eyes
 smiling face with open mouth
 angry face

>>>
</code>```

Output, Python console:

```<code>==> D:\test\Python\Py\q44965129a.py
python.exe D:\test\Python\Py\q44965129a.py

� smiling face with smiling eyes �
� smiling face with open mouth   �
� angry face                     �

 smiling face with smiling eyes
 smiling face with open mouth
 angry face

==>
</code>```

Title: 'UCS-2' not able to encode

Body:
I'm trying to read the text file but it throws one error.

UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 12416-12416: Non-BMP character not supported in Tk

I've tried to ignore it also but it I not working.
Here is the code:

with io.open('reviews1.txt', mode='r',encoding='utf-8') as myfile:
document1=myfile.read().replace('\n', '')
print(document1)

Body:
I can reproduce the error in Python IDLE environment (Python version 3.5.1, Tk version 8.6.4, IDLE version 3.5.1). It seems to be a bug in Tk. However, the original script runs smoothly from a console (Windows cmd, in my case): Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32.

The only way I can see could be very slow: the following commented script copies the whole document character by character eliminating all ones out of the Basic Multilingual Plane.

Edit: I found this (more Python-ish) solution (thanks to Mark Ransom). Unfortunately, this runs in Python shell but Python console complains:

>>> print( ''.join(c if c <= '\uffff' else ''.join(chr(x) for x in struct.unpack(
...   '>2H', c.encode('utf-16be'))) for c in document1)
... )
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\Python\Python35\lib\site-packages\win_unicode_console\streams.py",
line 179, in write

    return self.base.write(s)
UnicodeEncodeError: 'utf-16-le' codec can't encode character '\ud83d' in position 0:
surrogates not allowed
>>>

-

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

import sys, io
import os, codecs                       # for debugging

print(os.path.basename(sys.executable), sys.argv[0], '\n') # for debugging

#######################
### original answer ###
#######################
filepath = 'D:\\test\\reviews1.txt'
with io.open(filepath, mode='r',encoding='utf-8') as myfile:
    document1=myfile.read() #.replace('\n', '')
    document2=u''
    for character in document1:
        ordchar = ord(character)
        if ordchar <= 0xFFFF:
            # debugging # print( 'U+%.4X' % ordchar, character)
            document2+=character
        else:
            # debugging # print( 'U+%.6X' % ordchar, '�')
            ###         �=Replacement Character; codepoint=U+FFFD; utf8=0xEFBFBD
            document2+='�'
print(document2)                        # original answer, runs universally

######################
### updated answer ###
######################
if os.path.basename(sys.executable) == 'pythonw.exe':
    import struct
    document3 = ''.join(c if c <= '\uffff' else ''.join(chr(x) for x in struct.unpack('>2H', c.encode('utf-16be'))) for c in document1)
    print(document3)                    # Pythonw shell
else:
    print(document1)                    # Python console

Output, Pythonw shell:

================== RESTART: D:/test/Python/Py/q44965129a.py ==================
pythonw.exe D:/test/Python/Py/q44965129a.py

� smiling face with smiling eyes �
� smiling face with open mouth   �
� angry face                     �

 smiling face with smiling eyes
 smiling face with open mouth
 angry face

>>>

Output, Python console:

==> D:\test\Python\Py\q44965129a.py
python.exe D:\test\Python\Py\q44965129a.py

� smiling face with smiling eyes �
� smiling face with open mouth   �
� angry face                     �

 smiling face with smiling eyes
 smiling face with open mouth
 angry face

==>


问:
How can I use a java string image object in a html img tag - Is it possible?
I am currently generating a javascript image from a base64 string.
I am doing something like this

```<code>function generateHTML()
{
  var image = new Image();
  var src = "data:image/jpeg;base64," + picString;
  image.src = src;
  ......
}
</code>```

Now I know i can do something like this

```<code>document.body.appendChild(image);
</code>```

but that is not what I want. In my javascript function I am returning back an html string. My question is if it is possible for me to use the javascript image with a html statement like this

```<code><img src=image alt="Mountain View" style="width:304px;height:228px;">
</code>```

答:
If you are looking to get the html string of an element and not looking to append it to the current document, use outerHTML on the Image instance you created.</p>

```<code>function generateHTML() {
  var image = new Image();
  var src = "data:image/jpeg;base64," + picString;
  image.src = src;
  return image.outerHTML;
}
</code>```

Body:
I am currently generating a javascript image from a base64 string.
I am doing something like this

function generateHTML()
{
  var image = new Image();
  var src = "data:image/jpeg;base64," + picString;
  image.src = src;
  ......
}

Now I know i can do something like this

document.body.appendChild(image);

but that is not what I want. In my javascript function I am returning back an html string. My question is if it is possible for me to use the javascript image with a html statement like this

Body:
If you are looking to get the html string of an element and not looking to append it to the current document, use outerHTML on the Image instance you created.

function generateHTML() {
  var image = new Image();
  var src = "data:image/jpeg;base64," + picString;
  image.src = src;
  return image.outerHTML;
}


问:
XSLT - XML to XML Transformation with xsl:for-each
The XML I'm trying to transform looks as follows. I can't post the actual file as it contains sensitive information.

```<code>   <?xml version="1.0" encoding="utf-16"?>
    <TimesheetDetails>
     <timeAllocations>
       <TimeAllocationEntryDetails>
         <activity>
           <displayText> Value </displayText>
         </activity>
       </TimeAllocationEntryDetails>
       <TimeAllocationEntryDetails>
          <activity>
           <displayText> Value </displayText>
         </activity>
       </TimeAllocationEntryDetails>
       <TimeAllocationEntryDetails>
          <activity>
           <displayText> Value </displayText>
         </activity>
       </TimeAllocationEntryDetails>
       <TimeAllocationEntryDetails>
          <activity>
           <displayText> Value </displayText>
         </activity>
       </TimeAllocationEntryDetails>
     </timeAllocations>
    </TimesheetDetais>
</code>```

Here's a simple XSLT stylesheet I wrote to extract the data from the child nodes. It works as expected, however it only returns data from ONE of the TimesheetEntryDetails

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/TimeSheetDetails">
   <xsl:apply-templates select="timeAllocations"/>
</xsl:template>

<xsl:template match="timeAllocations">

<xsl:for-each select="TimeAllocationEntryDetails">
      <xsl:for-each select=".">
          <DisplayText>
          <xsl:value-of select="displayText"/>
          </DisplayText>
      </xsl:for-each>

</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code>```

My expected output should look something like

```<code><DisplayText>
   SomeData
</DisplayText>
</code>```

one for each TimeSheetAllocationEntryDetails node under timeheetAllocations.

Any help appreciated. I'm new to XSLT and I have a feeling I'm not using the xsl:for-each construct correctly.

Output I'm getting looks like (just one element ... the first)

```<code><DisplayText>
       SomeData
 </DisplayText>
</code>```

答:
You can simply replace the .(current node) with a *(all child elements of the current node) in the second for-each.

```<code><xsl:for-each select="TimeAllocationEntryDetails">
  <xsl:for-each select="*">          <!-- here -->
    ...
  </xsl:for-each>
</xsl:for-each>
</code>```

Body:
The XML I'm trying to transform looks as follows. I can't post the actual file as it contains sensitive information.

   <?xml version="1.0" encoding="utf-16"?>
    <TimesheetDetails>
     <timeAllocations>
       <TimeAllocationEntryDetails>
         <activity>
           <displayText> Value </displayText>
         </activity>
       </TimeAllocationEntryDetails>
       <TimeAllocationEntryDetails>
          <activity>
           <displayText> Value </displayText>
         </activity>
       </TimeAllocationEntryDetails>
       <TimeAllocationEntryDetails>
          <activity>
           <displayText> Value </displayText>
         </activity>
       </TimeAllocationEntryDetails>
       <TimeAllocationEntryDetails>
          <activity>
           <displayText> Value </displayText>
         </activity>
       </TimeAllocationEntryDetails>
     </timeAllocations>
    </TimesheetDetais>

Here's a simple XSLT stylesheet I wrote to extract the data from the child nodes. It works as expected, however it only returns data from ONE of the TimesheetEntryDetails

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/TimeSheetDetails">
   <xsl:apply-templates select="timeAllocations"/>
</xsl:template>

<xsl:template match="timeAllocations">

<xsl:for-each select="TimeAllocationEntryDetails">
      <xsl:for-each select=".">
          <DisplayText>
          <xsl:value-of select="displayText"/>
          </DisplayText>
      </xsl:for-each>

</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

My expected output should look something like

<DisplayText>
   SomeData
</DisplayText>

one for each TimeSheetAllocationEntryDetails node under timeheetAllocations.

Any help appreciated. I'm new to XSLT and I have a feeling I'm not using the xsl:for-each construct correctly.

Output I'm getting looks like (just one element ... the first)

<DisplayText>
       SomeData
 </DisplayText>

Body:
You can simply replace the .(current node) with a *(all child elements of the current node) in the second for-each.

<xsl:for-each select="TimeAllocationEntryDetails">
  <xsl:for-each select="*">          <!-- here -->
    ...
  </xsl:for-each>
</xsl:for-each>


问:
Using CSS for layout, clearing float for stating on next line ?? Need to create a layout of 2 cols and 5 rows
I have created a layout using DIVs rather than tables. It seems to be working... I had to clear:none after each div consisting of column and content.

But i end up with an extra line under each 2 columns before the other 2 columns start. I will outlay my code below, what am i doing wrong?.. What i want to do is create a table like layout but using divs consisting of 5 rows and each row have 2 columns.

```<code> <div id="column1" style="float:left;width:200px;">1st Title</div>
 <div id="container1" style="float:left;"> <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList></div>
 <div style="clear:both;"></div>
 <div id="column2" style="float:left;width:200px;">2nd Title</div>
 <div id="container2" style="float:left;"> <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList></div>
 <div style="clear:both;"></div>
</code>```

答:
I'm pretty sure you can get the same effect by adding clear: left to your column divs and clear: right to your container divs.

Edit: In fact, I would expect that the clear:left in the columns would be enough, but if that was true, making table-like layouts using floats would be easy, and it never is.

Body:
I have created a layout using DIVs rather than tables. It seems to be working... I had to clear:none after each div consisting of column and content.

But i end up with an extra line under each 2 columns before the other 2 columns start. I will outlay my code below, what am i doing wrong?.. What i want to do is create a table like layout but using divs consisting of 5 rows and each row have 2 columns.

1st Title

 <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>

2nd Title

 <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>


问:
c# HttpClient upload file to spring rest service
Problem:
I have a Java spring rest service to upload a file (large size).
I want use a .NET httpClient (or other .net client) to call upload service.

Questions:

It seems that best option to send large file is multi-part file, what's about interoperability ?

If it weren't possible, what is the best alternative ?

Thank you!

答:
java spring boot

```<code>@RequestMapping(value="/upload", method=RequestMethod.POST)
public @ResponseBody String upload(@RequestParam("FileParam") MultipartFile file){
    InputStream fromClient=file.getInputStream();
    ...do stuff with the database/ process the input file...
</code>```

c#

```<code>HttpClient client = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
FileInfo file = new FileInfo(@"<file path>");
form.Add(new StreamContent(file.OpenRead()),"FileParam",file.Name);
HttpResponseMessage response = await client.PostAsync("http://<host>:<port>/upload", form);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.ReasonPhrase);
Console.WriteLine(response.ToString());
Console.WriteLine(Encoding.ASCII.GetString(await response.Content.ReadAsByteArrayAsync()));
</code>```

Body:
java spring boot

@RequestMapping(value="/upload", method=RequestMethod.POST)
public @ResponseBody String upload(@RequestParam("FileParam") MultipartFile file){
    InputStream fromClient=file.getInputStream();
    ...do stuff with the database/ process the input file...

c#

HttpClient client = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
FileInfo file = new FileInfo(@"<file path>");
form.Add(new StreamContent(file.OpenRead()),"FileParam",file.Name);
HttpResponseMessage response = await client.PostAsync("http://<host>:<port>/upload", form);
Console.WriteLine(response.StatusCode);
Console.WriteLine(response.ReasonPhrase);
Console.WriteLine(response.ToString());
Console.WriteLine(Encoding.ASCII.GetString(await response.Content.ReadAsByteArrayAsync()));


问:
slickslider not working on dynamic content
Below is an example I made on jsFiddle to reprodice the problem I am facing. I am firing an init function to create slider after loading dynamic content via ajax. Part of the elements and classes created by slick are added to DOM but does not work.

function top_posts(el){
        var reqUrl = 'https://jsonplaceholder.typicode.com/users';
        el.children('.loadspan').html('');
        $.ajax({
            url: reqUrl,
            dataType: 'json',
            }).done(function( data ) {
                el.children('.loadspan').hide();
                if(data != ""){
                  console.log(data);
                    $.each(data, function(index) {
                          var output = '
' +
                                            '

' +
                                            '
' +
                                                '
' +
                                                    this.name +
                                                '
' +
                                            '
' +
                                        '
';
                        setTimeout(function() {
                            el.append(output);
                        }, (100 * (index + 1)));
                    });
                    top_slider_init();
                } else{
                    el.children('.loadspan').html('');
                }

            }).fail(function(jqXHR, textStatus) {
                el.children('.loadspan').html('');
                console.log("Request failed: " + textStatus);
            });
        return false;
}

  var el = $('.top-posts-slider');
  top_posts(el);

function top_slider_init() {
    $('.top-posts-slider').slick({
        slidesToShow: 3,
        slidesToScroll: 1,
        speed: 300,
        adaptiveHeight: false,
        variableWidth: false,
        autoplay: true,
        autoplaySpeed: 3000,
        infinite: true,
        dots: false,
        arrows: false,
        centerMode: false,
        centerPadding: "50px",
        cssEase: "ease-in-out",
        draggable: true,
        fade: false,
        focusOnSelect: false,
        pauseOnFocus: true,
        pauseOnDotsHover: false,
        vertical: false,
        verticalSwiping: false,
        rtl: false,
    });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.card-out {
  height: 200px;
  width: 100%;
  position: relative;
}
.card-bg {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-size: cover;
}
.card-title {
  position: absolute;
  bottom: 10px;
  left: 10px;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

```

any help appreciated :)

答:
Firstly, what is the loadspan div doing inside of the slider container?  When you slick that it's going to try to use that as a slide.

Beyond that, it looks as if you have a race condition between the markup being built and the slider being initialized.  The slider is being initialized before the content is actually inside of the container.  I also  don't think you need that setTimeout function in there, you should structure it something like

```<code>    var output = '';
    $.each(data, function(index) {
         output += 'All of your markup';
    }
    el.append(output);
    top_slider_init();
</code>```

Body:
Below is an example I made on jsFiddle to reprodice the problem I am facing. I am firing an init function to create slider after loading dynamic content via ajax. Part of the elements and classes created by slick are added to DOM but does not work.

function top_posts(el){
        var reqUrl = 'https://jsonplaceholder.typicode.com/users';
        el.children('.loadspan').html('');
        $.ajax({
            url: reqUrl,
            dataType: 'json',
            }).done(function( data ) {
                el.children('.loadspan').hide();
                if(data != ""){
                  console.log(data);
                    $.each(data, function(index) {
                          var output = '
' +
                                            '

' +
                                            '
' +
                                                '
' +
                                                    this.name +
                                                '
' +
                                            '
' +
                                        '
';
                        setTimeout(function() {
                            el.append(output);
                        }, (100 * (index + 1)));
                    });
                    top_slider_init();
                } else{
                    el.children('.loadspan').html('');
                }

            }).fail(function(jqXHR, textStatus) {
                el.children('.loadspan').html('');
                console.log("Request failed: " + textStatus);
            });
        return false;
}

  var el = $('.top-posts-slider');
  top_posts(el);

function top_slider_init() {
    $('.top-posts-slider').slick({
        slidesToShow: 3,
        slidesToScroll: 1,
        speed: 300,
        adaptiveHeight: false,
        variableWidth: false,
        autoplay: true,
        autoplaySpeed: 3000,
        infinite: true,
        dots: false,
        arrows: false,
        centerMode: false,
        centerPadding: "50px",
        cssEase: "ease-in-out",
        draggable: true,
        fade: false,
        focusOnSelect: false,
        pauseOnFocus: true,
        pauseOnDotsHover: false,
        vertical: false,
        verticalSwiping: false,
        rtl: false,
    });
}

.card-out {
  height: 200px;
  width: 100%;
  position: relative;
}
.card-bg {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-size: cover;
}
.card-title {
  position: absolute;
  bottom: 10px;
  left: 10px;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

any help appreciated :)

Body:
Firstly, what is the loadspan div doing inside of the slider container?  When you slick that it's going to try to use that as a slide.

Beyond that, it looks as if you have a race condition between the markup being built and the slider being initialized.  The slider is being initialized before the content is actually inside of the container.  I also  don't think you need that setTimeout function in there, you should structure it something like

    var output = '';
    $.each(data, function(index) {
         output += 'All of your markup';
    }
    el.append(output);
    top_slider_init();