问:
What is the best way to re-use code in two different situations when it needs variables from the current scope?
I've been writing a lot of code, and I try to avoid duplicated logic a lot, but I couldn't think of a way around this case.

```<code>if(something){
 // do something
 // then run a lot of code
} else {
 // do something else
 // then run a lot of the same code
}
</code>```

I tried this:

```<code>if(something){
 // do something
 traloc()
} else {
 // do something else
 traloc()
}

function traloc(){
 // then run a lot of code
}
</code>```

And it was working with variables, but I couldn't call resolve or reject from within the function, which means it doesn't inherit the function variables of the scope it's called in, and only some variables?

So to really achieve perfection I'd need to do:

```<code>if(something){
 // do something
 traloc(var1, var2, var3, var4)
} else {
 // do something else
 traloc(var1, var2, var3, var4)
}

function traloc(var1, var2, var3, var4){
 // then run a lot of code
}
</code>```

Is there a better way to abstract logic into functioning snippets that inherit function scope?

This is the real code for when I need to pass variables resolve and reject instead of having access to them

```<code>function relateRe(thing, relations, relation, relative, commonStateHash){
    /** params
     *  @param thing is the thing we are saving relations for
     *  @param relations is a list of relationships we are saving
     *  @param relation will be a @type {Number} representing the index of the relationship string, ie: the property of thing that is a list of related things
     *  @param relative will be a @type {Number} representing the property of the related thing where the _id of the thing should be inserted
     *  @param commonStateHash is the common hash used to identify backup states from this save function
     */
    /** returns a promise that resolves to:
     *  @func success
     *    @var thingRelatedFully
     *  @func failure
     *    @var thingRelatedSemi
     *    @var err
     */
    return new Promise((resolve, reject)=>{
      /** store a backup state of the relative for use if any other saving fails
       *  also handles conversion of non-registered documents into ._id bearing saveable model objects
       *  also handles conversion of non-object, ObjectId type relatives to ._id bearing saveable model objects
       */
      console.log(thing)
      console.log('relations')
      console.log(relations)
      console.log('relation')
      console.log(relation)
      console.log('relative')
      console.log(relative)
      if(!thing[relations[relation].relationship][relative]){
        /** check if we continue updating relationships
         */
          continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash, resolve, reject)

      } else {
        makeBackupState(thing[relations[relation].relationship][relative], relations, commonStateHash)
            .then((thingRelative, err)=>{
              if(!err){
                console.log(thingRelative)
                thing[relations[relation].relationship][relative] = thingRelative
                // thingRelative = thing[relations[relation].relationship][relative]
                /** add the _id of the given thing to the relationships list of the current relative
                 */
                  smartOpts.pushOpt(thing._id, relative[relations[relation].property])
                let relativeRelations = createRelativeRelations(relations, relation)
                let optsRelative = {
                  thing: thingRelative,
                  relations: relativeRelations,
                  save: relations[relation],
                  commonStateHash: commonStateHash,
                  backupState: false
                }
                saveThing(optsRelative)
                  .then((thingRelativeSaved, err)=>{
                    if(!err){
                      /** check if we continue updating relationships
                       */
                        continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash, resolve, reject)
                    } else {
                      resolve(thing, err)
                    }
                  })
              } else {
                resolve(thing, err)
              }
            })
      }
    })

    function continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash, resolve, reject){
      /** if the current relation is not the last of this relationship group/list
       *  increment the relationship counter
       *  update the next relationship
       */
        if((relative < thing[relations[relation].relationship].length-1) && ((relations[relation].save && (thing.stateId == commonStateHash)) || relations[relation].upsert)){
          console.log('next relative in relationship %s', relation)
          relateRe(thing, relations, relation, relative+=1, commonStateHash)
            .then((thing, err)=>{
              if(!err){
                resolve(thing)
              } else {
                resolve(thing, err)
              }
            })
        }
      /** otherwise if the current relationship group/list is not the last group/list
       *  increment the relationship group/list counter
       *  update the next relationship
       */
        else if(relation < relations.length-1){
          console.log('next relationship in relationship %s', relation+1)
          relateRe(thing, relations, relation+=1, 0, commonStateHash)
            .then((thing, err)=>{
              if(!err){
                resolve(thing)
              } else {
                resolve(thing, err)
              }
            })
        }
      /** otherwise if that was the last relationship and the last relationship group
       *  resolve the current state of the thing
       */
        else {
          console.log("resolving due to last relationship")
          resolve(thing)
        }
    }
  }
</code>```

答:
You can easily write</p>

```<code>if (something) {
  // do something
} else {
  // do something else
}
// then run a lot of code
</code>```

Body:
I've been writing a lot of code, and I try to avoid duplicated logic a lot, but I couldn't think of a way around this case.

if(something){
 // do something
 // then run a lot of code
} else {
 // do something else
 // then run a lot of the same code
}

I tried this:

if(something){
 // do something
 traloc()
} else {
 // do something else
 traloc()
}

function traloc(){
 // then run a lot of code
}

And it was working with variables, but I couldn't call resolve or reject from within the function, which means it doesn't inherit the function variables of the scope it's called in, and only some variables?

So to really achieve perfection I'd need to do:

if(something){
 // do something
 traloc(var1, var2, var3, var4)
} else {
 // do something else
 traloc(var1, var2, var3, var4)
}

function traloc(var1, var2, var3, var4){
 // then run a lot of code
}

Is there a better way to abstract logic into functioning snippets that inherit function scope?

This is the real code for when I need to pass variables resolve and reject instead of having access to them

function relateRe(thing, relations, relation, relative, commonStateHash){
    /** params
     *  @param thing is the thing we are saving relations for
     *  @param relations is a list of relationships we are saving
     *  @param relation will be a @type {Number} representing the index of the relationship string, ie: the property of thing that is a list of related things
     *  @param relative will be a @type {Number} representing the property of the related thing where the _id of the thing should be inserted
     *  @param commonStateHash is the common hash used to identify backup states from this save function
     */
    /** returns a promise that resolves to:
     *  @func success
     *    @var thingRelatedFully
     *  @func failure
     *    @var thingRelatedSemi
     *    @var err
     */
    return new Promise((resolve, reject)=>{
      /** store a backup state of the relative for use if any other saving fails
       *  also handles conversion of non-registered documents into ._id bearing saveable model objects
       *  also handles conversion of non-object, ObjectId type relatives to ._id bearing saveable model objects
       */
      console.log(thing)
      console.log('relations')
      console.log(relations)
      console.log('relation')
      console.log(relation)
      console.log('relative')
      console.log(relative)
      if(!thing[relations[relation].relationship][relative]){
        /** check if we continue updating relationships
         */
          continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash, resolve, reject)

      } else {
        makeBackupState(thing[relations[relation].relationship][relative], relations, commonStateHash)
            .then((thingRelative, err)=>{
              if(!err){
                console.log(thingRelative)
                thing[relations[relation].relationship][relative] = thingRelative
                // thingRelative = thing[relations[relation].relationship][relative]
                /** add the _id of the given thing to the relationships list of the current relative
                 */
                  smartOpts.pushOpt(thing._id, relative[relations[relation].property])
                let relativeRelations = createRelativeRelations(relations, relation)
                let optsRelative = {
                  thing: thingRelative,
                  relations: relativeRelations,
                  save: relations[relation],
                  commonStateHash: commonStateHash,
                  backupState: false
                }
                saveThing(optsRelative)
                  .then((thingRelativeSaved, err)=>{
                    if(!err){
                      /** check if we continue updating relationships
                       */
                        continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash, resolve, reject)
                    } else {
                      resolve(thing, err)
                    }
                  })
              } else {
                resolve(thing, err)
              }
            })
      }
    })

    function continueRelatingOrResolve(thing, relations, relation, relative, commonStateHash, resolve, reject){
      /** if the current relation is not the last of this relationship group/list
       *  increment the relationship counter
       *  update the next relationship
       */
        if((relative < thing[relations[relation].relationship].length-1) && ((relations[relation].save && (thing.stateId == commonStateHash)) || relations[relation].upsert)){
          console.log('next relative in relationship %s', relation)
          relateRe(thing, relations, relation, relative+=1, commonStateHash)
            .then((thing, err)=>{
              if(!err){
                resolve(thing)
              } else {
                resolve(thing, err)
              }
            })
        }
      /** otherwise if the current relationship group/list is not the last group/list
       *  increment the relationship group/list counter
       *  update the next relationship
       */
        else if(relation < relations.length-1){
          console.log('next relationship in relationship %s', relation+1)
          relateRe(thing, relations, relation+=1, 0, commonStateHash)
            .then((thing, err)=>{
              if(!err){
                resolve(thing)
              } else {
                resolve(thing, err)
              }
            })
        }
      /** otherwise if that was the last relationship and the last relationship group
       *  resolve the current state of the thing
       */
        else {
          console.log("resolving due to last relationship")
          resolve(thing)
        }
    }
  }

Body:
You can easily write

if (something) {
  // do something
} else {
  // do something else
}
// then run a lot of code


来源: stackexchange

问:
Python 2.7 & GCP Google BigQuery: Capturing file load errors?
All,

I'm getting some Python 2.7 BiqQuery (BQ) data loads "operations ready" and I'm struggling with the right way to capture file loading errors in a comparable manner as other Big Data DW platforms I've used in the past.

In BQ, I can access the errors from this and examples are below:   bigquery_client.load_table_from_uri.errors

```<code>{
    {'reason': 'invalid',
        'message': "Could not parse 'r2501' as int for field lineNum (position 0) starting at location 56708 ",
        'location': 'gs://bucketNameHere/fake-data.csv'}
    {'reason': 'invalid',
        'message': 'CSV table references column position 2, but line starting at position:56731 contains only 2 columns.',
        'location': 'gs://bucketNameHere/fake-data.csv'}
    {'reason': 'invalid',
        'message': "Could not parse 'a' as int for field lineNum (position 0) starting at location 56734 ",
        'location': 'gs://bucketNameHere/fake-data.csv'}
    {'reason': 'invalid',
        'message': "Could not parse 'a' as int for field lineNum (position 0) starting at location 56739 ",
        'location': 'gs://bucketNameHere/fake-data.csv'}
    {'reason': 'invalid',
        'message': 'CSV table references column position 1, but line starting at position:56751 contains only 1 columns.',
        'location': 'gs://bucketNameHere/fake-data.csv'}
}
</code>```

This is good, but I really need a little bit better information, particularly the line number of the error, that is the main issue I'm having.

In Redshift:  stl_loaderror_detail & stl_load_errors   http://docs.aws.amazon.com/redshift/latest/dg/r_STL_LOAD_ERRORS.html

In SnowflakeDB:  load_history & TABLE(VALIDATE(table_name, job_id => '_last'));   https://docs.snowflake.net/manuals/sql-reference/functions/validate.html

In summary, I need to load the data I can (set my max_bad_records fairly high), and when records fail, I need to know:

the filename of the load (in case I do a wildcard file load), this
is currently provided

the line number where the error occurred, this is currently not provided, but the byte# is embedded in the message - "starting at location" or "position:".    I really need line number as a stand alone element

error message, this is provided and the current message is more than adequet

Any guidance would be appreciated.

Thanks and best...Rich

p.s. I'll follow up with a comment containing my load script, I think the way I'm grabbing the statistics might be helpful for folks since it took me a while to figure out.

p.s.s.
running on Linux and GOOGLE_APPLICATION_CREDENTIALS is set
python 2.7

library versions as follows:

```<code>google-cloud==0.29.0
google-cloud-bigquery==0.28.0
google-cloud-core==0.28.0

# load a table to bq from gcs with the schema
def load_table_from_gcs(dataset_name, table_name, schema, source, skip_leading_rows=1, source_format='CSV', max_bad_records=0, write_disposition='WRITE_EMPTY', project=None):
    try:

        # convert the schema json string to a list
        schemaList = convert_schema(schema)

        bigquery_client = bigquery.Client(project=project)
        dataset_ref = bigquery_client.dataset(dataset_name)
        table_ref = dataset_ref.table(table_name)
        table = bigquery.Table(table_ref, schema=schemaList)

        bigquery_client.create_table(table)

        job_id_prefix = "bqTools_load_job"
        job_config = bigquery.LoadJobConfig()
        job_config.create_disposition = 'NEVER'
        job_config.skip_leading_rows = skip_leading_rows
        job_config.source_format = source_format
        job_config.write_disposition = write_disposition

        if max_bad_records:
            job_config.max_bad_records = max_bad_records

        load_job = bigquery_client.load_table_from_uri(
            source, table_ref, job_config=job_config,
            job_id_prefix=job_id_prefix)

        # the following waits for table load to complete
        load_job.result()

        print("------ load_job\n")
        print("load_job: " + str(type(load_job)))
        print(dir(load_job))

        print("------ load_job.result\n")
        job_result = load_job.result
        print("job_result: " + str(type(job_result)))
        print(job_result)

        job_exception = load_job.exception
        job_id = load_job.job_id
        job_state = load_job.state
        error_result = load_job.error_result
        job_statistics = load_job._job_statistics()
        badRecords = job_statistics['badRecords']
        outputRows = job_statistics['outputRows']
        inputFiles = job_statistics['inputFiles']
        inputFileBytes = job_statistics['inputFileBytes']
        outputBytes = job_statistics['outputBytes']

        print("\n ***************************** ")
        print(" job_state:      " + str(job_state))
        print(" error_result:   " + str(error_result))
        print(" job_id:         " + str(job_id))
        print(" badRecords:     " + str(badRecords))
        print(" outputRows:     " + str(outputRows))
        print(" inputFiles:     " + str(inputFiles))
        print(" inputFileBytes: " + str(inputFileBytes))
        print(" outputBytes:    " + str(outputBytes))
        print(" type(job_exception):  " + str(type(job_exception)))
        print(" job_exception:  " + str(job_exception))
        print(" ***************************** ")

        print("------ load_job.errors \n")
        myErrors = load_job.errors
        # print("myErrors: " + str(type(myErrors)))
        for errorRecord in myErrors:
            print(errorRecord)

        print("------ ------ ------ ------\n")

        # TODO:  need to figure out how to get # records failed, and which ones they are
        # research shoed "statistics.load_job" - but not sure how that works

        returnMsg = 'load_table_from_gcs {}:{} {}'.format(dataset_name, table_name, source)

        return returnMsg

    except Exception as e:
        errorStr = 'ERROR (load_table_from_gcs): ' + str(e)
        print(errorStr)
        raise
</code>```

答:
The reason BigQuery doesn't report line number for errors is because the file is split and parsed by many workers in parallel. Say if a worker is responsible for offset 10000~20000 of the file, it'll seek to 10000 and start parsing from there. When it fails to parse a line, it only knows the start offset of the line. To know the line number it'll need to scan from the beginning of the file.

You can find out the line given the start offset. Is there a specific reason that you need the line number?

ContentLicense: CC BY-SA 3.0

Body:
All,

I'm getting some Python 2.7 BiqQuery (BQ) data loads "operations ready" and I'm struggling with the right way to capture file loading errors in a comparable manner as other Big Data DW platforms I've used in the past.

In BQ, I can access the errors from this and examples are below:   bigquery_client.load_table_from_uri.errors

{
    {'reason': 'invalid',
        'message': "Could not parse 'r2501' as int for field lineNum (position 0) starting at location 56708 ",
        'location': 'gs://bucketNameHere/fake-data.csv'}
    {'reason': 'invalid',
        'message': 'CSV table references column position 2, but line starting at position:56731 contains only 2 columns.',
        'location': 'gs://bucketNameHere/fake-data.csv'}
    {'reason': 'invalid',
        'message': "Could not parse 'a' as int for field lineNum (position 0) starting at location 56734 ",
        'location': 'gs://bucketNameHere/fake-data.csv'}
    {'reason': 'invalid',
        'message': "Could not parse 'a' as int for field lineNum (position 0) starting at location 56739 ",
        'location': 'gs://bucketNameHere/fake-data.csv'}
    {'reason': 'invalid',
        'message': 'CSV table references column position 1, but line starting at position:56751 contains only 1 columns.',
        'location': 'gs://bucketNameHere/fake-data.csv'}
}

This is good, but I really need a little bit better information, particularly the line number of the error, that is the main issue I'm having.

In Redshift:  stl_loaderror_detail & stl_load_errors   http://docs.aws.amazon.com/redshift/latest/dg/r_STL_LOAD_ERRORS.html

In SnowflakeDB:  load_history & TABLE(VALIDATE(table_name, job_id => '_last'));   https://docs.snowflake.net/manuals/sql-reference/functions/validate.html

In summary, I need to load the data I can (set my max_bad_records fairly high), and when records fail, I need to know:

the filename of the load (in case I do a wildcard file load), this
is currently provided

the line number where the error occurred, this is currently not provided, but the byte# is embedded in the message - "starting at location" or "position:".    I really need line number as a stand alone element

error message, this is provided and the current message is more than adequet

Any guidance would be appreciated.

Thanks and best...Rich

p.s. I'll follow up with a comment containing my load script, I think the way I'm grabbing the statistics might be helpful for folks since it took me a while to figure out.

p.s.s.
running on Linux and GOOGLE_APPLICATION_CREDENTIALS is set
python 2.7

library versions as follows:

google-cloud==0.29.0
google-cloud-bigquery==0.28.0
google-cloud-core==0.28.0

# load a table to bq from gcs with the schema
def load_table_from_gcs(dataset_name, table_name, schema, source, skip_leading_rows=1, source_format='CSV', max_bad_records=0, write_disposition='WRITE_EMPTY', project=None):
    try:

        # convert the schema json string to a list
        schemaList = convert_schema(schema)

        bigquery_client = bigquery.Client(project=project)
        dataset_ref = bigquery_client.dataset(dataset_name)
        table_ref = dataset_ref.table(table_name)
        table = bigquery.Table(table_ref, schema=schemaList)

        bigquery_client.create_table(table)

        job_id_prefix = "bqTools_load_job"
        job_config = bigquery.LoadJobConfig()
        job_config.create_disposition = 'NEVER'
        job_config.skip_leading_rows = skip_leading_rows
        job_config.source_format = source_format
        job_config.write_disposition = write_disposition

        if max_bad_records:
            job_config.max_bad_records = max_bad_records

        load_job = bigquery_client.load_table_from_uri(
            source, table_ref, job_config=job_config,
            job_id_prefix=job_id_prefix)

        # the following waits for table load to complete
        load_job.result()

        print("------ load_job\n")
        print("load_job: " + str(type(load_job)))
        print(dir(load_job))

        print("------ load_job.result\n")
        job_result = load_job.result
        print("job_result: " + str(type(job_result)))
        print(job_result)

        job_exception = load_job.exception
        job_id = load_job.job_id
        job_state = load_job.state
        error_result = load_job.error_result
        job_statistics = load_job._job_statistics()
        badRecords = job_statistics['badRecords']
        outputRows = job_statistics['outputRows']
        inputFiles = job_statistics['inputFiles']
        inputFileBytes = job_statistics['inputFileBytes']
        outputBytes = job_statistics['outputBytes']

        print("\n ***************************** ")
        print(" job_state:      " + str(job_state))
        print(" error_result:   " + str(error_result))
        print(" job_id:         " + str(job_id))
        print(" badRecords:     " + str(badRecords))
        print(" outputRows:     " + str(outputRows))
        print(" inputFiles:     " + str(inputFiles))
        print(" inputFileBytes: " + str(inputFileBytes))
        print(" outputBytes:    " + str(outputBytes))
        print(" type(job_exception):  " + str(type(job_exception)))
        print(" job_exception:  " + str(job_exception))
        print(" ***************************** ")

        print("------ load_job.errors \n")
        myErrors = load_job.errors
        # print("myErrors: " + str(type(myErrors)))
        for errorRecord in myErrors:
            print(errorRecord)

        print("------ ------ ------ ------\n")

        # TODO:  need to figure out how to get # records failed, and which ones they are
        # research shoed "statistics.load_job" - but not sure how that works

        returnMsg = 'load_table_from_gcs {}:{} {}'.format(dataset_name, table_name, source)

        return returnMsg

    except Exception as e:
        errorStr = 'ERROR (load_table_from_gcs): ' + str(e)
        print(errorStr)
        raise


问:
TypeScript definition for RequireJS Module return without export
Usage without TypeScript

I have a RequireJS Module which i can't edit

The RequireJS Module:

```<code>//app/Router.js
define([], function() {
  return {
    generate: function(route) { /*do something*/ }
  }
});
</code>```

The module don't have any export, but with the return statement it works in other require modules by using it like:

```<code>define(['app/Router'], function(router) {
  router.generate('myRoute');
});
</code>```

I want to use the app/Router.js in TypeScript

Variant 1: TypeScript knows the type, but JS has errors

So i try to make my definition module:

```<code>//Router.d.ts
export interface Router
{
    generate(route:string): string;
}
declare let router: Router;
export default router;
</code>```

Using it in my TypeScript file like:

```<code>import router from 'app/Router'

router.generate('something');
</code>```

Will generate that file:

```<code>define(
  ["require", "exports", "app/Router"],
  function (require, exports, Router_1)
) {
   Router_1.default.generate();
}
</code>```

The Problem is the default attribute. JS says that can't call generate on null. Because Router_1 is already the object i want.

Variant 2: JS is correct but TypeScript don't knows the type

I also tried:

```<code>//Router.d.ts
export interface Router
{
    generate(route:string): string;
}
declare let router: Router;
declare module "router" {
    export = router;
}
</code>```

Using it like:

```<code>import * as router from 'app/Router'

router.generate('something');
</code>```

The output is correct:

```<code>define(["require", "exports", "app/Router"], function (require, exports, router) {
  router.generate();
});
</code>```

But TypeScript compiler says: Property 'generate' does not exist on type

Question

How must my Router.d.ts and import statement looks like, in order to have the right output and TypeScript knows the correct type?

答:
When you use export default stuff you are telling to the compiler that the object exported has a property named default which has as value stuff, if in the .js file the object.default == undefined it will throw a TypeError when invoked as a function. Try this approach instead:

```<code>//Router.d.ts

declare module "app/Router" { // <- this must contain the path and the file's name;

    const router: {
        generate: (route: string) => string;
    }

    export = router;
}

// in the .ts file ...

import * as router from "app/Router";

router.generate("go/some/url");
</code>```

Using tsc 2.6.1 this outputs:

```<code>define(["require", "exports", "app/Router"], function (require, exports, router) {
                                                               //^^^^^^^
    "use strict";                                              //|||||||
    exports.__esModule = true; // <- it extends this object that was passed as argument ...
    router.generate("go/some/url");// <- but this was the desired effect, right?
});
</code>```

I have no prior knowledge of the amd system so i have no way to tell what are the consequences of extending or setting the exports object inside the body of the function. I don't think that the change that was made will matter, but is better check for yourself anyway.

Body:
Usage without TypeScript

I have a RequireJS Module which i can't edit

The RequireJS Module:

//app/Router.js
define([], function() {
  return {
    generate: function(route) { /*do something*/ }
  }
});

The module don't have any export, but with the return statement it works in other require modules by using it like:

define(['app/Router'], function(router) {
  router.generate('myRoute');
});

I want to use the app/Router.js in TypeScript

Variant 1: TypeScript knows the type, but JS has errors

So i try to make my definition module:

//Router.d.ts
export interface Router
{
    generate(route:string): string;
}
declare let router: Router;
export default router;

Using it in my TypeScript file like:

import router from 'app/Router'

router.generate('something');

Will generate that file:

define(
  ["require", "exports", "app/Router"],
  function (require, exports, Router_1)
) {
   Router_1.default.generate();
}

The Problem is the default attribute. JS says that can't call generate on null. Because Router_1 is already the object i want.

Variant 2: JS is correct but TypeScript don't knows the type

I also tried:

//Router.d.ts
export interface Router
{
    generate(route:string): string;
}
declare let router: Router;
declare module "router" {
    export = router;
}

Using it like:

import * as router from 'app/Router'

router.generate('something');

The output is correct:

define(["require", "exports", "app/Router"], function (require, exports, router) {
  router.generate();
});

But TypeScript compiler says: Property 'generate' does not exist on type

Question

How must my Router.d.ts and import statement looks like, in order to have the right output and TypeScript knows the correct type?

Body:
When you use export default stuff you are telling to the compiler that the object exported has a property named default which has as value stuff, if in the .js file the object.default == undefined it will throw a TypeError when invoked as a function. Try this approach instead:

//Router.d.ts

declare module "app/Router" { // <- this must contain the path and the file's name;

    const router: {
        generate: (route: string) => string;
    }

    export = router;
}

// in the .ts file ...

import * as router from "app/Router";

router.generate("go/some/url");

Using tsc 2.6.1 this outputs:

define(["require", "exports", "app/Router"], function (require, exports, router) {
                                                               //^^^^^^^
    "use strict";                                              //|||||||
    exports.__esModule = true; // <- it extends this object that was passed as argument ...
    router.generate("go/some/url");// <- but this was the desired effect, right?
});

I have no prior knowledge of the amd system so i have no way to tell what are the consequences of extending or setting the exports object inside the body of the function. I don't think that the change that was made will matter, but is better check for yourself anyway.


问:
Extracting variable from array for use in command on CMD
I am trying to make a CMD batch script that constantly logs IP statistics and puts them in different .txt files, for this I have created 2 arrays, one that contains the names I wish to give to the txt files and other one that contains the ips I wish to ping.

I try to loop the elements in the arrays as names/parameters for different commands on the CMD shell, the part for the .txt names works but I can't get extracting the ip addresses from the corresponding array and passing them to the ping command to work. My code is:

```<code>@echo off
set Noms=(bni csc cba lpz oro pnd pts scz trj)
set Dirs=(8.8.8.8 8.8.8.4 8.8.8.4 8.8.8.8 8.8.8.8 8.8.8.4 8.8.8.8 8.8.8.4 8.8.8.8)
rem --------------------------------------------------------------
rem Builds .txts with names in list Noms pinging Addresses in Dirs
rem --------------------------------------------------------------
for %%j in %Noms% do (
set direccion = %Dirs[%%j]%
ping /n 3 %direccion% > c:\log\p0.txt
findstr "Media" c:\log\p0.txt > c:\log\p1.txt
for /f "tokens=3 delims=," %%i in (c:\log\p1.txt) do @echo %%i > c:\log\p2.txt
for /f "tokens=4 delims=<equal> " %%i in (c:\log\p2.txt) do @echo %%i > c:\log\p0.txt
for /f "tokens=1 delims=m" %%i in (c:\log\p0.txt) do (set pingvar=%%i)
for /f "tokens=1-3 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-3 delims=/:," %%a in ("%TIME%") do (set mytime=%%a:%%b:%%c)
set totvar=%mydate%     %mytime%    %pingvar%
echo %totvar% > c:\log\%%j.txt
)
</code>```

I found no mistake in my code, basically I try to put the IP address from the array "Dirs" in the variable "direccion" and then passit as an argument to ping.

Thank you for helping me.

答:
You have to use enable delayed expansion. I'll show a sample code with some of your names

```<code>@echo off

setlocal EnableDelayedExpansion

set "names=bni csc cba"
set "Dirs[bni]=1.1.1.1"
set "Dirs[csc]=2.2.2.2"
set "Dirs[cba]=3.3.3.3"

for %%I in (%names%) do (
   echo(Name:%%I, IP:!Dirs[%%I]!
)
</code>```

The output for the above is:

```<code>Name:bni, IP:1.1.1.1
Name:csc, IP:2.2.2.2
Name:cba, IP:3.3.3.3
</code>```

Hope it helps.

Body:
I am trying to make a CMD batch script that constantly logs IP statistics and puts them in different .txt files, for this I have created 2 arrays, one that contains the names I wish to give to the txt files and other one that contains the ips I wish to ping.

I try to loop the elements in the arrays as names/parameters for different commands on the CMD shell, the part for the .txt names works but I can't get extracting the ip addresses from the corresponding array and passing them to the ping command to work. My code is:

@echo off
set Noms=(bni csc cba lpz oro pnd pts scz trj)
set Dirs=(8.8.8.8 8.8.8.4 8.8.8.4 8.8.8.8 8.8.8.8 8.8.8.4 8.8.8.8 8.8.8.4 8.8.8.8)
rem --------------------------------------------------------------
rem Builds .txts with names in list Noms pinging Addresses in Dirs
rem --------------------------------------------------------------
for %%j in %Noms% do (
set direccion = %Dirs[%%j]%
ping /n 3 %direccion% > c:\log\p0.txt
findstr "Media" c:\log\p0.txt > c:\log\p1.txt
for /f "tokens=3 delims=," %%i in (c:\log\p1.txt) do @echo %%i > c:\log\p2.txt
for /f "tokens=4 delims=<equal> " %%i in (c:\log\p2.txt) do @echo %%i > c:\log\p0.txt
for /f "tokens=1 delims=m" %%i in (c:\log\p0.txt) do (set pingvar=%%i)
for /f "tokens=1-3 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-3 delims=/:," %%a in ("%TIME%") do (set mytime=%%a:%%b:%%c)
set totvar=%mydate%     %mytime%    %pingvar%
echo %totvar% > c:\log\%%j.txt
)

I found no mistake in my code, basically I try to put the IP address from the array "Dirs" in the variable "direccion" and then passit as an argument to ping.

Thank you for helping me.

Body:
You have to use enable delayed expansion. I'll show a sample code with some of your names

@echo off

setlocal EnableDelayedExpansion

set "names=bni csc cba"
set "Dirs[bni]=1.1.1.1"
set "Dirs[csc]=2.2.2.2"
set "Dirs[cba]=3.3.3.3"

for %%I in (%names%) do (
   echo(Name:%%I, IP:!Dirs[%%I]!
)

The output for the above is:

Name:bni, IP:1.1.1.1
Name:csc, IP:2.2.2.2
Name:cba, IP:3.3.3.3

Hope it helps.


问:
How to create native module to retrieve realm data value in react native?
I've finded out almost two days to get some tutorial/refer about access realm db in react-native using native module

but no luck till now,

I've realm package in node_modules but I cant add Realm.init(context) in android folder because I don't have import io.realm.*

there's any way to retrieve realm database value?

答:
You have two options. Automatic or manual link.

1) Automatic: You just run "react-native link "npm-module"

It should do it for you. Keep in mind that it could duplicate some code if you already modify some code manually

2) Manually:

You added half of it. You need yo modify at least 2 files. One is the settings.gradle like you said, where you define the project.

It should look something like this:

```<code>rootProject.name = 'YourName'
include ':realm'
project(':realm').projectDir = new File(rootProject.projectDir, '../node_modules/realm/android')
include ':app'
</code>```

Then the second part is in the app/build.gradle fie, where you need to tell gradle to actually compile the project.

Something like:

```<code>dependencies {
    // You would need to add this
    compile project(':realm')
}
</code>```

You should now see the project being compiled when you bundle the project.

The second part might solve the problem that is not finding your classes. Now, the plugin might need another specific setup like adding a classpath or something like that.

Try it and post back if you have any other issue.

Body:
You have two options. Automatic or manual link.

1) Automatic: You just run "react-native link "npm-module"

It should do it for you. Keep in mind that it could duplicate some code if you already modify some code manually

2) Manually:

You added half of it. You need yo modify at least 2 files. One is the settings.gradle like you said, where you define the project.

It should look something like this:

rootProject.name = 'YourName'
include ':realm'
project(':realm').projectDir = new File(rootProject.projectDir, '../node_modules/realm/android')
include ':app'

Then the second part is in the app/build.gradle fie, where you need to tell gradle to actually compile the project.

Something like:

dependencies {
    // You would need to add this
    compile project(':realm')
}

You should now see the project being compiled when you bundle the project.

The second part might solve the problem that is not finding your classes. Now, the plugin might need another specific setup like adding a classpath or something like that.

Try it and post back if you have any other issue.


问:
Defining super easy function with python but "missing 1 required positional argument"
I put 2 arguments like this it said missing 1 required positional argument.
I put 3 arguments it said it requires 2, but 3 were given.

What is the issue with the logic below?

```<code>def mergeSort(alist,sentence):
    if len(alist)>1:
        mid = len(alist)//2
        lefthalf = alist[:mid]
        righthalf = alist[mid:]

        mergeSort(lefthalf)
        mergeSort(righthalf)

        i=0
        j=0
        k=0
        while i < len(lefthalf) and j < len(righthalf):
            if lefthalf[i] < righthalf[j]:
                alist[k]=lefthalf[i]
                i=i+1
            else:
                alist[k]=righthalf[j]
                j=j+1
            k=k+1

        while i < len(lefthalf):
            alist[k]=lefthalf[i]
            i=i+1
            k=k+1

        while j < len(righthalf):
            alist[k]=righthalf[j]
            j=j+1
            k=k+1
        print(sentence)
        return alist

a=[7,5,4]
mergeSort(a,'Finished')
</code>```

答:
mergeSort takes in two arguments, but you've only given it one argument when you recursively call it in the function body.
You should change the

```<code>mergeSort(lefthalf)
mergeSort(righthalf)
</code>```

part to

```<code>mergeSort(lefthalf, sentence)
mergeSort(righthalf, sentence)
</code>```

Body:
I put 2 arguments like this it said missing 1 required positional argument.
I put 3 arguments it said it requires 2, but 3 were given.

What is the issue with the logic below?

def mergeSort(alist,sentence):
    if len(alist)>1:
        mid = len(alist)//2
        lefthalf = alist[:mid]
        righthalf = alist[mid:]

        mergeSort(lefthalf)
        mergeSort(righthalf)

        i=0
        j=0
        k=0
        while i < len(lefthalf) and j < len(righthalf):
            if lefthalf[i] < righthalf[j]:
                alist[k]=lefthalf[i]
                i=i+1
            else:
                alist[k]=righthalf[j]
                j=j+1
            k=k+1

        while i < len(lefthalf):
            alist[k]=lefthalf[i]
            i=i+1
            k=k+1

        while j < len(righthalf):
            alist[k]=righthalf[j]
            j=j+1
            k=k+1
        print(sentence)
        return alist

a=[7,5,4]
mergeSort(a,'Finished')

Body:
mergeSort takes in two arguments, but you've only given it one argument when you recursively call it in the function body.
You should change the

mergeSort(lefthalf)
mergeSort(righthalf)

part to

mergeSort(lefthalf, sentence)
mergeSort(righthalf, sentence)


问:
How to add command line option to include an additional make options from the command line
I have a Makefile and make.options and I dont want to edit the Makefile.
I want to run the gnu make with some command line options to include the make.options in the Makefile.
Is there a way to do that?</p>

答:
If I understand your question correctly -- and I'm not sure I do, it's highly unclear -- then you can do it this way:</p>

```<code>make -f make.options -f Makefile
</code>```

Body:
If I understand your question correctly -- and I'm not sure I do, it's highly unclear -- then you can do it this way:

make -f make.options -f Makefile


问:
Google ML Engine Jobs Differ in Accuracy between Standard and Premium ScaleTier
I'm new to Machine Learning. I ran two similar ML jobs that only differed in the config.yaml file for GCP, specifically scaleTier:. Ran the first job with just scaleTier: STANDARD_1 and got an accuracy of around 93%. Take the same Tensorflow records and adjusted the scaleTier to scaleTier: PREMIUM_1 and the accuracy drops down to around 50%. Does increasing the number of ML Training Units decrease the accuracy of the model?

Two questions to this problem: Why does the accuracy drop considerably, and what are the work arounds to it?

答: Typically, when you do distributed training, you should use smaller batch sizes. Can you try reducing your batch size to 1/8 of what you used in standard? You will have to increase your steps by 8x to make sure you are going through the dataset the same number of times.</p>


问:
script to dump single record from table in mysql
I want to dump single record from mysql table named as table1 for id = 5.

What is mysql query for same?

I think we can use mysqldump but i have used it with full records of table. But how to use it with single record?

答:
Try </p>

```<code>INSERT INTO table2 (SELECT * FROM table1 WHERE id = 5);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Try

INSERT INTO table2 (SELECT * FROM table1 WHERE id = 5);


问:
How to stop webcam running when navigated to another page in UWP application
I have a camera feature in my UWP application, and one part of the feature is to actually check whether there is any camera device found connected. I developed the feature following this set of example: CameraStarterKit

When I tested the codes on a machine without a webcam or camera, the message prompt will be shown. But I think that the codes that are checking whether there is a camera device is still running behind when I exit the page as the prompt is showing up when I minimize the application and open it up again.

Is there anyway I can stop the codes for checking whether there is a camera is connected when I navigate to another page?

Here is the codes for checking the if there is a camera connected:

```<code>private async Task InitializeCameraAsync()
    {
        Debug.WriteLine("InitializeCameraAsync");

        if (_mediaCapture == null)
        {

            // Attempt to get the back camera if one is available, but use any camera device if not
            var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);

            if (cameraDevice == null)
            {
                this.LoadProgressRing.IsActive = false;
                this.LoadProgressStackPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

                MessageDialog cameraError = new MessageDialog("Connection Problem. No camera device found. Please kindly contacct the administrator.");
                UICommand YesBtn = new UICommand("Ok", delegate (IUICommand command)
                {
                    idleTimer.Stop();
                    var rootFrame = (Window.Current.Content as Frame);
                    rootFrame.Navigate(typeof(HomePage));
                    rootFrame.BackStack.Clear();
                });
                cameraError.Commands.Add(YesBtn);
                await cameraError.ShowAsync();

                Debug.WriteLine("No camera device found!");
                return;
            }

            // Create MediaCapture and its settings
            _mediaCapture = new MediaCapture();

            var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };

            // Initialize MediaCapture
            try
            {
                await _mediaCapture.InitializeAsync(settings);
                _isInitialized = true;
            }
            catch (UnauthorizedAccessException)
            {
                Debug.WriteLine("The app was denied access to the camera");
            }

            // If initialization succeeded, start the preview
            if (_isInitialized)
            {
                // Figure out where the camera is located
                if (cameraDevice.EnclosureLocation == null || cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown)
                {
                    // No information on the location of the camera, assume it's an external camera, not integrated on the device
                    _externalCamera = true;
                }
                else
                {
                    // Camera is fixed on the device
                    _externalCamera = false;

                    // Only mirror the preview if the camera is on the front panel
                    _mirroringPreview = (cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
                }

                // Initialize rotationHelper
                _rotationHelper = new CameraRotationHelper(cameraDevice.EnclosureLocation);
                _rotationHelper.OrientationChanged += RotationHelper_OrientationChanged;

                await StartPreviewAsync();

                UpdateCaptureControls();

            }

            return;
        }

    }
</code>```

EDIT

Codes for SetUpBasedOnStateAsync() method:

```<code>private async Task SetUpBasedOnStateAsync()
    {
        // Avoid reentrancy: Wait until nobody else is in this function.
        while (!_setupTask.IsCompleted)
        {
            await _setupTask;
        }

        // We want our UI to be active if
        // * We are the current active page.
        // * The window is visible.
        // * The app is not suspending.
        bool wantUIActive = _isActivePage && Window.Current.Visible && !_isSuspending;

        if (_isUIActive != wantUIActive)
        {
            _isUIActive = wantUIActive;

            Func<Task> setupAsync = async () =>
            {
                if (wantUIActive)
                {
                    await SetupUiAsync();
                    await InitializeCameraAsync();
                }
                else
                {
                    await CleanupCameraAsync();
                    await CleanupUiAsync();
                }
            };
            _setupTask = setupAsync();
        }

        await _setupTask;
    }
</code>```

答:
Is there anyway I can stop the codes for checking whether there is a camera is connected when I navigate to another page?

When you navigate to another page, the OnNavigatingFrom handler method would be called, you could see that SetUpBasedOnStateAsync method would be called in it. In this method, the InitializeCameraAsync method would be called. So, you just need to change some lines codes in SetUpBasedOnStateAsync method.

But I think that the codes that are checking whether there is a camera device is still running behind when I exit the page as the prompt is showing up when I minimize the application and open it up again.

It's normal behavior. When you minimize and open your app,the code would go into this if block. If you do not want this behavior. I suggest that you could create a new project instead of changing the official code sample. Because you would need to change many places.

Body:
I have a camera feature in my UWP application, and one part of the feature is to actually check whether there is any camera device found connected. I developed the feature following this set of example: CameraStarterKit

When I tested the codes on a machine without a webcam or camera, the message prompt will be shown. But I think that the codes that are checking whether there is a camera device is still running behind when I exit the page as the prompt is showing up when I minimize the application and open it up again.

Is there anyway I can stop the codes for checking whether there is a camera is connected when I navigate to another page?

Here is the codes for checking the if there is a camera connected:

private async Task InitializeCameraAsync()
    {
        Debug.WriteLine("InitializeCameraAsync");

        if (_mediaCapture == null)
        {

            // Attempt to get the back camera if one is available, but use any camera device if not
            var cameraDevice = await FindCameraDeviceByPanelAsync(Windows.Devices.Enumeration.Panel.Back);

            if (cameraDevice == null)
            {
                this.LoadProgressRing.IsActive = false;
                this.LoadProgressStackPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

                MessageDialog cameraError = new MessageDialog("Connection Problem. No camera device found. Please kindly contacct the administrator.");
                UICommand YesBtn = new UICommand("Ok", delegate (IUICommand command)
                {
                    idleTimer.Stop();
                    var rootFrame = (Window.Current.Content as Frame);
                    rootFrame.Navigate(typeof(HomePage));
                    rootFrame.BackStack.Clear();
                });
                cameraError.Commands.Add(YesBtn);
                await cameraError.ShowAsync();

                Debug.WriteLine("No camera device found!");
                return;
            }

            // Create MediaCapture and its settings
            _mediaCapture = new MediaCapture();

            var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameraDevice.Id };

            // Initialize MediaCapture
            try
            {
                await _mediaCapture.InitializeAsync(settings);
                _isInitialized = true;
            }
            catch (UnauthorizedAccessException)
            {
                Debug.WriteLine("The app was denied access to the camera");
            }

            // If initialization succeeded, start the preview
            if (_isInitialized)
            {
                // Figure out where the camera is located
                if (cameraDevice.EnclosureLocation == null || cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown)
                {
                    // No information on the location of the camera, assume it's an external camera, not integrated on the device
                    _externalCamera = true;
                }
                else
                {
                    // Camera is fixed on the device
                    _externalCamera = false;

                    // Only mirror the preview if the camera is on the front panel
                    _mirroringPreview = (cameraDevice.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front);
                }

                // Initialize rotationHelper
                _rotationHelper = new CameraRotationHelper(cameraDevice.EnclosureLocation);
                _rotationHelper.OrientationChanged += RotationHelper_OrientationChanged;

                await StartPreviewAsync();

                UpdateCaptureControls();

            }

            return;
        }

    }

EDIT

Codes for SetUpBasedOnStateAsync() method:

private async Task SetUpBasedOnStateAsync()
    {
        // Avoid reentrancy: Wait until nobody else is in this function.
        while (!_setupTask.IsCompleted)
        {
            await _setupTask;
        }

        // We want our UI to be active if
        // * We are the current active page.
        // * The window is visible.
        // * The app is not suspending.
        bool wantUIActive = _isActivePage && Window.Current.Visible && !_isSuspending;

        if (_isUIActive != wantUIActive)
        {
            _isUIActive = wantUIActive;

            Func<Task> setupAsync = async () =>
            {
                if (wantUIActive)
                {
                    await SetupUiAsync();
                    await InitializeCameraAsync();
                }
                else
                {
                    await CleanupCameraAsync();
                    await CleanupUiAsync();
                }
            };
            _setupTask = setupAsync();
        }

        await _setupTask;
    }


问:
Create a "slot machine" with dynamic height children
I am working on a layout that is similar in nature to a slot machine. Each of its children will be text, and the layout is responsive (so at different resolutions, the children's text may or may not wrap to multiple lines, thus changing the height).

The layout will have a visible "viewport" of 3 items at a time. So that the "viewport" does not shift around, all children need to have the same height. This got me thinking of 2 different routes, but I can't make either work.

Use display: flex. With a column layout, you can have them all stack. The problem with this is, I don't think you can make all children have the same height unless you specify a calculated height on the flex container (thus, you'd have to use js to calculate the max height of all the flex children)

Use display: grid. Out of the box you can make all children have equal height with grid. The problem is, how do hide the overflow guaranteeing you are only showing 3 at a time in the "viewport" for the slot machine?

This layout may not be possible without js calculations, but because of the fact that it has to be completely responsive, I don't want to have to redo the calculations on every window resize. Can anyone think of a way to do this using pure css?

I made a fiddle to show a bare-bones implementation. The "viewport" is the red box, and each item is in the blue box. In the real world, I would be hiding everything outside of the red box and would not want to have to specifically set height on any container.

var scroll = document.getElementById('scroll');
var wrapper = document.getElementById('wrapper');

scroll.addEventListener('click', function() {
  wrapper.classList.toggle('scrolled');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.example {
  display: flex;
}

.container {
  height: 90px;
  width: 300px;
  outline: 1px solid red;
  z-index:1;
}

.wrapper {
  display: flex;
  flex-direction: column;
  transition-property: transform;
  transition-duration: 500ms;
}

.wrapper.scrolled {
  transform: translateY(-300px);
}

.inner {
  outline: 1px solid blue;
  flex-grow: 1;
  height: 30px;
}

.buttons {
  margin-right: 3em;
}</code>```

    <button id="scroll">Scroll</button>

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Some text

```

答:
Hey so I think I get what you're going for here and designed a "slot machine" mechanic that scales its inner and outer objects using vh.

So the container object would have something like...

```<code>.container {
    width: 300px;
    height: 90vh;
    outline: 1px solid red;
    z-index:1;
    overflow: hidden;
}
</code>```

...and the inner object would have something like...

```<code>.inner {
    outline: 1px solid blue;
    flex-grow: 1;
    height: 30vh;
}
</code>```

I also adjusted the Javascript scrolling to base the amount scrolled off of what object is being scrolled to. This can be automated with something like a timer instead of the button:

```<code>var scroll = document.getElementById('scroll');
var wrapper = document.getElementById('wrapper');
var innerArray = document.getElementsByClassName('inner');

var innerNum = 1; // Start at the second element
scroll.addEventListener('click', function() {
  if (innerNum == innerArray.length-2) { // Check to see if the last item has been scrolled to
    innerNum = 0; // Scroll back to the first item if it has
  }
  //wrapper.classList.toggle('scrolled');
  innerArray[innerNum].scrollIntoView({
    behavior: 'smooth'
  });
  innerNum++;
});
</code>```

Here is the Codepen that demonstrates the example. I can clarify the code further if you would like me to. My apologies if I was way off the ball on what you were going for!

Body:
I am working on a layout that is similar in nature to a slot machine. Each of its children will be text, and the layout is responsive (so at different resolutions, the children's text may or may not wrap to multiple lines, thus changing the height).

The layout will have a visible "viewport" of 3 items at a time. So that the "viewport" does not shift around, all children need to have the same height. This got me thinking of 2 different routes, but I can't make either work.

Use display: flex. With a column layout, you can have them all stack. The problem with this is, I don't think you can make all children have the same height unless you specify a calculated height on the flex container (thus, you'd have to use js to calculate the max height of all the flex children)

Use display: grid. Out of the box you can make all children have equal height with grid. The problem is, how do hide the overflow guaranteeing you are only showing 3 at a time in the "viewport" for the slot machine?

This layout may not be possible without js calculations, but because of the fact that it has to be completely responsive, I don't want to have to redo the calculations on every window resize. Can anyone think of a way to do this using pure css?

I made a fiddle to show a bare-bones implementation. The "viewport" is the red box, and each item is in the blue box. In the real world, I would be hiding everything outside of the red box and would not want to have to specifically set height on any container.

var scroll = document.getElementById('scroll');
var wrapper = document.getElementById('wrapper');

scroll.addEventListener('click', function() {
  wrapper.classList.toggle('scrolled');
});

.example {
  display: flex;
}

.container {
  height: 90px;
  width: 300px;
  outline: 1px solid red;
  z-index:1;
}

.wrapper {
  display: flex;
  flex-direction: column;
  transition-property: transform;
  transition-duration: 500ms;
}

.wrapper.scrolled {
  transform: translateY(-300px);
}

.inner {
  outline: 1px solid blue;
  flex-grow: 1;
  height: 30px;
}

.buttons {
  margin-right: 3em;
}

    <button id="scroll">Scroll</button>

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Some text

Body:
Hey so I think I get what you're going for here and designed a "slot machine" mechanic that scales its inner and outer objects using vh.

So the container object would have something like...

.container {
    width: 300px;
    height: 90vh;
    outline: 1px solid red;
    z-index:1;
    overflow: hidden;
}

...and the inner object would have something like...

.inner {
    outline: 1px solid blue;
    flex-grow: 1;
    height: 30vh;
}

I also adjusted the Javascript scrolling to base the amount scrolled off of what object is being scrolled to. This can be automated with something like a timer instead of the button:

var scroll = document.getElementById('scroll');
var wrapper = document.getElementById('wrapper');
var innerArray = document.getElementsByClassName('inner');

var innerNum = 1; // Start at the second element
scroll.addEventListener('click', function() {
  if (innerNum == innerArray.length-2) { // Check to see if the last item has been scrolled to
    innerNum = 0; // Scroll back to the first item if it has
  }
  //wrapper.classList.toggle('scrolled');
  innerArray[innerNum].scrollIntoView({
    behavior: 'smooth'
  });
  innerNum++;
});

Here is the Codepen that demonstrates the example. I can clarify the code further if you would like me to. My apologies if I was way off the ball on what you were going for!


问:
Better way to identify cellphone numbers based on the first four digits
Currently I have this python program for identifying cellphone numbers based on the first four digits.

```<code>cellnum = (input("Enter your 11-digit cellphone number with no spaces or dashes: "))
n1 = cellnum[:4]
if n1 == "0917" or n1 == "0916":
  print(cellnum, "is Globe")
elif n1 == "0935":
  print(cellnum, "is TM")
elif n1 == "0918" or n1 == "0910":
  print(cellnum, "is Smart")
elif n1 == "0922" or n1 == "0923":
  print(cellnum, "is Sun")
else:
  print("~unknown provider~ :(")
</code>```

Is there a better way to improve my script and make it more dynamic.

答:
If you are asking on how to improve it ived made a simple example for you.

https://repl.it/@marksman/riavillacorte

```<code>cellnum = (input("Enter your 11-digit cellphone number with no spaces or dashes: "))

def checkProvider(numb):
    provider_key = numb[:4]
    providers = [
        ('Globe', ['0917', '0916']),
        ('TM', ['0935']),
        ('Smart', ['0918', '0910']),
        ('Sun', ['0922', '0923'])
    ]
    for provider in providers:
        provider_name, numbers = provider
        if provider_key in numbers:
            return provider_name
    return None

cellProvider = checkProvider(cellnum)

if cellProvider is None:
    print('~unknown provider~ :(')
else:
    print(cellnum, 'is ' + cellProvider)
</code>```

Body:
Currently I have this python program for identifying cellphone numbers based on the first four digits.

cellnum = (input("Enter your 11-digit cellphone number with no spaces or dashes: "))
n1 = cellnum[:4]
if n1 == "0917" or n1 == "0916":
  print(cellnum, "is Globe")
elif n1 == "0935":
  print(cellnum, "is TM")
elif n1 == "0918" or n1 == "0910":
  print(cellnum, "is Smart")
elif n1 == "0922" or n1 == "0923":
  print(cellnum, "is Sun")
else:
  print("~unknown provider~ :(")

Is there a better way to improve my script and make it more dynamic.

Body:
If you are asking on how to improve it ived made a simple example for you.

https://repl.it/@marksman/riavillacorte

cellnum = (input("Enter your 11-digit cellphone number with no spaces or dashes: "))

def checkProvider(numb):
    provider_key = numb[:4]
    providers = [
        ('Globe', ['0917', '0916']),
        ('TM', ['0935']),
        ('Smart', ['0918', '0910']),
        ('Sun', ['0922', '0923'])
    ]
    for provider in providers:
        provider_name, numbers = provider
        if provider_key in numbers:
            return provider_name
    return None

cellProvider = checkProvider(cellnum)

if cellProvider is None:
    print('~unknown provider~ :(')
else:
    print(cellnum, 'is ' + cellProvider)


问:
Selecting a radio button when clicking an image
I want to select radio button when I click on his image but it's not working.
This is what I've tried:

```<code><ul id="options-31-list" class="options-list">
    <li>
        <a class="mydata" href="" data="84">
            <img class="small-image-preview" src="value_id/84/file/o2.jpg/">
        </a>
        <input class="radio validate-one-required-by-name product-custom-option" type="radio" data="84" value="84" onclick="opConfig.reloadPrice();">
    </li>
    <li>
        <a class="mydata" href="" data="85">
            <img class="small-image-preview" src="value_id/85/file/vodafone.jpg/">
        </a>
        <input class="radio validate-one-required-by-name product-custom-option" type="radio" data="85" value="85" onclick="opConfig.reloadPrice();">
    </li>
    <li>
        <a class="mydata" href="" data="86">
            <img class="small-image-preview" src="value_id/86/file/t-mobile.jpg/">
        </a>
        <input class="radio validate-one-required-by-name product-custom-option" type="radio" data="86" value="86" onclick="opConfig.reloadPrice();">
    </li>
</ul>
</code>```

I have the same data="" attribute for both: for image and for input, is there any way to make the input (that radio) to be checked when I click on image?

Thank you

UPDATE:
I found some code that work, but only for three clicks on image, so when click to the last one the script is stop, can't select the first or second again, I don't know why... I think must to uncheck all radio buttons and than check the one selected ...
can someone help me with this?

```<code>jQuery(".mydata").click(function(){
jQuery(this).parent().children("input").attr('checked','true');
})
</code>```

答:
try this:</p>

```<code><input type="radio" id="radio_1"  />
<label for="radio_1"><img src="image.jpg" id="radio_1" /></label>
<label for="radio_1">Radio - 1</label>
</code>```

Body:
I want to select radio button when I click on his image but it's not working.
This is what I've tried:

        <input class="radio validate-one-required-by-name product-custom-option" type="radio" data="84" value="84" onclick="opConfig.reloadPrice();">

        <input class="radio validate-one-required-by-name product-custom-option" type="radio" data="85" value="85" onclick="opConfig.reloadPrice();">

        <input class="radio validate-one-required-by-name product-custom-option" type="radio" data="86" value="86" onclick="opConfig.reloadPrice();">

I have the same data="" attribute for both: for image and for input, is there any way to make the input (that radio) to be checked when I click on image?

Thank you

UPDATE:
I found some code that work, but only for three clicks on image, so when click to the last one the script is stop, can't select the first or second again, I don't know why... I think must to uncheck all radio buttons and than check the one selected ...
can someone help me with this?

jQuery(".mydata").click(function(){
jQuery(this).parent().children("input").attr('checked','true');
})

Body:
try this:

<input type="radio" id="radio_1"  />
<label for="radio_1"><img src="image.jpg" id="radio_1" /></label>
<label for="radio_1">Radio - 1</label>


问:
$var not working though out php mysql script
I don't understand why the second mysql look is not working.
from what i can tell where $sqlb = "SELECT * FROM emp_list  WHERE password = '$pw' AND username = '$un' LIMIT 1 "; is on the second line there is no value in the $pw or $un in fact i can not echo any of the

```<code>$un = $_POST['username'];
$pw = $_POST['password'];
$store = $_POST['store'];
$pw = md5($pw);
$ipaddress = $ipaddress;
</code>```

from the start or $nip from the first loop What am i doing wrong?

```<code>     <?php

    $ipaddress = '';
        if (isset($_SERVER['HTTP_CLIENT_IP']))
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        else if(isset($_SERVER['HTTP_X_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        else if(isset($_SERVER['HTTP_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
        else if(isset($_SERVER['REMOTE_ADDR']))
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        else {
            $ipaddress = 'UNKNOWN';

 }
    $servername = "localhost";
    $username = "******";
    $password = "**********";
    $dbname = "************";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$connb = new mysqli($servername, $username, $password, $dbname, true);

// Check connection
if ($conn->connect_error)
{
    die("Connection failed: " . $conn->connect_error);
}

$un = $_POST['username'];
$pw = $_POST['password'];
$store = $_POST['store'];
$pw = md5($pw);
$ipaddress = $ipaddress;

$sql = "SELECT * FROM acclst  WHERE s = '$ipaddress' LIMIT 1 ";
$result = $conn->query($sql);

if ($result->num_rows > 0)
{
   // There is an ipaddress and it is approved
    while($row = $result->fetch_assoc())
{

        echo 'welcome ';
        echo $nip = $row['s'];

    if ($conn->connect_error)
{
    die("Connection failed: " . $conn->connect_error);
}

// this does not echo
echo $store;

$sqlb = "SELECT * FROM emp_list  WHERE `username` = '$un' AND password = '$pw' LIMIT 1 ";
$resultb = $connb->query($sqlb);

if ($result->num_rows > 0) {
   // There is an ipaddress and it is approved
    while($rowb = $result->fetch_assoc()) {
// none of this echo's

        echo $pw;
        echo 'welcome ';
        echo $rowb['namel'];

         }
      }
    }
}

else
{
    // There is no ip address and you do not have access.
    echo "0 results";
}

?>
</code>```

答:
Not sure if I understand your question, but try something like this:</p>

```<code>$sqlb = "SELECT * FROM emp_list  WHERE password = " . $pw . " AND username = " . $un . " LIMIT 1 ";
</code>```

Body:
I don't understand why the second mysql look is not working.
from what i can tell where $sqlb = "SELECT * FROM emp_list  WHERE password = '$pw' AND username = '$un' LIMIT 1 "; is on the second line there is no value in the $pw or $un in fact i can not echo any of the

$un = $_POST['username'];
$pw = $_POST['password'];
$store = $_POST['store'];
$pw = md5($pw);
$ipaddress = $ipaddress;

from the start or $nip from the first loop What am i doing wrong?

     <?php

    $ipaddress = '';
        if (isset($_SERVER['HTTP_CLIENT_IP']))
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        else if(isset($_SERVER['HTTP_X_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        else if(isset($_SERVER['HTTP_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
        else if(isset($_SERVER['REMOTE_ADDR']))
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        else {
            $ipaddress = 'UNKNOWN';

 }
    $servername = "localhost";
    $username = "******";
    $password = "**********";
    $dbname = "************";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$connb = new mysqli($servername, $username, $password, $dbname, true);

// Check connection
if ($conn->connect_error)
{
    die("Connection failed: " . $conn->connect_error);
}

$un = $_POST['username'];
$pw = $_POST['password'];
$store = $_POST['store'];
$pw = md5($pw);
$ipaddress = $ipaddress;

$sql = "SELECT * FROM acclst  WHERE s = '$ipaddress' LIMIT 1 ";
$result = $conn->query($sql);

if ($result->num_rows > 0)
{
   // There is an ipaddress and it is approved
    while($row = $result->fetch_assoc())
{

        echo 'welcome ';
        echo $nip = $row['s'];

    if ($conn->connect_error)
{
    die("Connection failed: " . $conn->connect_error);
}

// this does not echo
echo $store;

$sqlb = "SELECT * FROM emp_list  WHERE `username` = '$un' AND password = '$pw' LIMIT 1 ";
$resultb = $connb->query($sqlb);

if ($result->num_rows > 0) {
   // There is an ipaddress and it is approved
    while($rowb = $result->fetch_assoc()) {
// none of this echo's

        echo $pw;
        echo 'welcome ';
        echo $rowb['namel'];

         }
      }
    }
}

else
{
    // There is no ip address and you do not have access.
    echo "0 results";
}

?>

Body:
Not sure if I understand your question, but try something like this:

$sqlb = "SELECT * FROM emp_list  WHERE password = " . $pw . " AND username = " . $un . " LIMIT 1 ";


答:
Here you go:</p>

```<code>def mergeSort(alist,sentence):
    if len(alist)>1:
        mid = len(alist)//2
        lefthalf = alist[:mid]
        righthalf = alist[mid:]

        mergeSort(lefthalf, 'Not finished')
        mergeSort(righthalf, 'Not finished')

        i=0
        j=0
        k=0
        while i < len(lefthalf) and j < len(righthalf):
            if lefthalf[i] < righthalf[j]:
                alist[k]=lefthalf[i]
                i=i+1
            else:
                alist[k]=righthalf[j]
                j=j+1
            k=k+1

        while i < len(lefthalf):
            alist[k]=lefthalf[i]
            i=i+1
            k=k+1

        while j < len(righthalf):
            alist[k]=righthalf[j]
            j=j+1
            k=k+1

    print(sentence)
    return alist

a=[7,5,4]
mergeSort(a,'Finished')
</code>```

Title: Defining super easy function with python but "missing 1 required positional argument"

Body:
Here you go:

def mergeSort(alist,sentence):
    if len(alist)>1:
        mid = len(alist)//2
        lefthalf = alist[:mid]
        righthalf = alist[mid:]

        mergeSort(lefthalf, 'Not finished')
        mergeSort(righthalf, 'Not finished')

        i=0
        j=0
        k=0
        while i < len(lefthalf) and j < len(righthalf):
            if lefthalf[i] < righthalf[j]:
                alist[k]=lefthalf[i]
                i=i+1
            else:
                alist[k]=righthalf[j]
                j=j+1
            k=k+1

        while i < len(lefthalf):
            alist[k]=lefthalf[i]
            i=i+1
            k=k+1

        while j < len(righthalf):
            alist[k]=righthalf[j]
            j=j+1
            k=k+1

    print(sentence)
    return alist

a=[7,5,4]
mergeSort(a,'Finished')


问:
How to write a conditional statement in vsts if previous task fails in a task group
We would like to send slack messages only if the previous task fails. How can we specify the previous task using task groups?

It is getting skipped!!!

Tried this but could not locate anything with the previous task.
https://learn.microsoft.com/en-us/vsts/build-release/concepts/process/conditions

答:
There isn’t the task condition feature for the tasks in task group, also the task group doesn’t have the condition feature.

There is a related user voice: VSTS Task Group usage should have a conditional usage (You can submit a new user voice)

The workaround is that you can put the tasks out of the task group, which need to be run according to the condition statement.

On the other hand, there is Only when a previous task has failed condition:


问:
Getting free of scrolling up after submit in Oracle Apex
Good evening to everybody.

At this moment I'm working on a new page for Oracle Apex and again I have trouble with Interactive Report. My page (let it be named 500) consists of Interactive Report with id rep_main and Classic one with id rep_child, which are connected by master-detail logic (I choose the row from the main report and then I get the rows in the child one depending on my choice). Also every row of the main report has several buttons (precisely tags "a" with links like "javascript:..."), which call dialog windows for updating data of the chosen row.

My aim is to make page more comfortable for users: firstly, the chosen row from the main report should change its color; secondly, the reports should refresh correctly. The second condition means, that, after I choose the rown in the main report, the pagination must not change and the view of the page must not scroll up by itself.

I managed to make the master-detail logic and recoloring the rows (thanks to Stack Overflow for helping me with this task) in my IR, but I have some difficulties with the condition of correct refresh. Apart from JavaScript/jQuery functions, I have to call standard Apex function apex.submit, because if I don't do this, pagination of my IR won't save, but at the same time the page scrolls up by itself, which is very unlikely for users. Moreover, the pagination resets after any dialog window appears.

I've tried to find solution in Google, but all is in vain. I hope that somebody knows if there is any workaround in my case (against the scrolling up at least).

I use Oracle Apex 4.2.6.00.03 and application is executed mainly through Mozilla Firefox. The code I wrote for my page 500 is written below in the current post.

On the page load executes the process with PL/SQL lines like this:

```<code>:P500_MAIN_ID := APEX_UTIL.GET_NUMERIC_SESSION_STATE(P_ITEM => 'P500_MAIN_ID'); --receiving the chosen row's ID saved in session
</code>```

The main report region header contains the following script:

```<code><script>
  $("#rep_main").find("table.apexir_WORKSHEET_DATA td).live("click",function(){
    var chosenOne = $(this).find("span").attr("id"); //finding ID of the chosen row
    chooseMAIN(chosenOne);
    apex.submit({set:{'P500_MAIN_ID':chosenOne,'P500_CHILD_ID':null}});
  });
</script>
</code>```

In this code P500_CHILD_RN is the item for saving ID of child report's row and the function chooseMAIN is:

```<code>function chooseMAIN(docID){
  $.post('wwv_flow.show',
         {'p_request'      : 'APPLICATION_PROCESS=SET_MAIN',
          'p_flow_id'      : $v('pFlowId'),
          'p_flow_step_id' : $v('pFlowStepId'),
          'p_instance'     : $v('pInstance'),
          'x01'            : docID},
         function(data){
           //for the opportunity to get the ID in pure JavaScript
           $("#P500_MAIN_ID").val(docID);
           $("#P500_CHILD_ID").val("");
           $("#rep_main").trigger('apexrefresh');
           $("rep_child").trigger('apexrefresh');
         }
       );
}
</code>```

The process SET_MAIN looks this way:

```<code>begin
  APEX_UTIL.SET_SESSION_STATE(P_NAME => 'P500_CHILD_ID',P_VALUE => NULL);
  APEX_UTIL.SET_SESSION_STATE(P_NAME => 'P500_MAIN_ID',P_VALUE => APEX_APPLICATION.G_X01);
end;
</code>```

p.s. Earlier I asked some help with IR here, but I still haven't found proper solution (except making a submit, which has its side effects I said about).

答:
what you really want to use in this case is the FOEX plug-in because its AJAX based so you don't need to submit.

FOEX website

And do yourself a favor and move away from 4.2 you'll thank me later..

Body:
Good evening to everybody.

At this moment I'm working on a new page for Oracle Apex and again I have trouble with Interactive Report. My page (let it be named 500) consists of Interactive Report with id rep_main and Classic one with id rep_child, which are connected by master-detail logic (I choose the row from the main report and then I get the rows in the child one depending on my choice). Also every row of the main report has several buttons (precisely tags "a" with links like "javascript:..."), which call dialog windows for updating data of the chosen row.

My aim is to make page more comfortable for users: firstly, the chosen row from the main report should change its color; secondly, the reports should refresh correctly. The second condition means, that, after I choose the rown in the main report, the pagination must not change and the view of the page must not scroll up by itself.

I managed to make the master-detail logic and recoloring the rows (thanks to Stack Overflow for helping me with this task) in my IR, but I have some difficulties with the condition of correct refresh. Apart from JavaScript/jQuery functions, I have to call standard Apex function apex.submit, because if I don't do this, pagination of my IR won't save, but at the same time the page scrolls up by itself, which is very unlikely for users. Moreover, the pagination resets after any dialog window appears.

I've tried to find solution in Google, but all is in vain. I hope that somebody knows if there is any workaround in my case (against the scrolling up at least).

I use Oracle Apex 4.2.6.00.03 and application is executed mainly through Mozilla Firefox. The code I wrote for my page 500 is written below in the current post.

On the page load executes the process with PL/SQL lines like this:

:P500_MAIN_ID := APEX_UTIL.GET_NUMERIC_SESSION_STATE(P_ITEM => 'P500_MAIN_ID'); --receiving the chosen row's ID saved in session

The main report region header contains the following script:

In this code P500_CHILD_RN is the item for saving ID of child report's row and the function chooseMAIN is:

function chooseMAIN(docID){
  $.post('wwv_flow.show',
         {'p_request'      : 'APPLICATION_PROCESS=SET_MAIN',
          'p_flow_id'      : $v('pFlowId'),
          'p_flow_step_id' : $v('pFlowStepId'),
          'p_instance'     : $v('pInstance'),
          'x01'            : docID},
         function(data){
           //for the opportunity to get the ID in pure JavaScript
           $("#P500_MAIN_ID").val(docID);
           $("#P500_CHILD_ID").val("");
           $("#rep_main").trigger('apexrefresh');
           $("rep_child").trigger('apexrefresh');
         }
       );
}

The process SET_MAIN looks this way:

begin
  APEX_UTIL.SET_SESSION_STATE(P_NAME => 'P500_CHILD_ID',P_VALUE => NULL);
  APEX_UTIL.SET_SESSION_STATE(P_NAME => 'P500_MAIN_ID',P_VALUE => APEX_APPLICATION.G_X01);
end;

p.s. Earlier I asked some help with IR here, but I still haven't found proper solution (except making a submit, which has its side effects I said about).


问:
Xamarin.Forms Navigation.PushAsync not working in ContentView
I want to navigate to other page in Xamarin Forms but it is not working in Content View. I am using

await Navigation.PushAsync(new Page2());

This code is not giving any error and run successfully but there is no effect on page. I am using this code in content  page also and it works properly there but it is not working in case of ContentView.
Currently I am using

await ParentView.Navigation.PushAsync(new Page2());

and it is working fine in ContentView. But I am getting warning that "ParentView is obsolete as of version 2.1.0. Please use Parent instead.". But there is no function like

await Parent.Navigation.PushAsync(new Page2());

and it is giving syntax error. So, is there any other way to navigate to other page using ContentView.

答:
If the MainPage of your app is a NavigationPage, then you can always call PushAsync() from inside your app.  I would recommend checking that the MainPage is of type NavigationPage just to be sure you don't throw a cast exception.  To do this, just use these two lines:

```<code>if(App.Current.MainPage is NavigationPage)
    (App.Current.Mainpage as NavigationPage).PushAsync(new Page2());
</code>```

Body:
If the MainPage of your app is a NavigationPage, then you can always call PushAsync() from inside your app.  I would recommend checking that the MainPage is of type NavigationPage just to be sure you don't throw a cast exception.  To do this, just use these two lines:

if(App.Current.MainPage is NavigationPage)
    (App.Current.Mainpage as NavigationPage).PushAsync(new Page2());


问:
how to give a number a leading zero in scheme
How do you give a number a leading zero in scheme language?
For instance, I want the time to give 09:05 AM with a leading zero in front of the 9 and 5, instead of having 9:5 AM.</p>

答:
This depends heavily on what interpreter you're using. For example, in Racket this is how we do it:</p>

```<code>(format "~a:~a AM"
        (~r 9 #:min-width 2 #:pad-string "0")
        (~r 5 #:min-width 2 #:pad-string "0"))

=> "09:05 AM"
</code>```

Body:
This depends heavily on what interpreter you're using. For example, in Racket this is how we do it:

(format "~a:~a AM"
        (~r 9 #:min-width 2 #:pad-string "0")
        (~r 5 #:min-width 2 #:pad-string "0"))

=> "09:05 AM"


问:
How to Save, Separate, and Write Data from File to Multiple TextBoxes
I need to save a bunch (around 600) of TextBox content to a (Preferably) single file, then be able to write that data back to their respective TextBoxes on file open. Essentially I'm making a D&D stat sheet, and I want to save what each player has entered as the [character's name].txt. I already got simple saving and writing down by using a single control and the code:

```<code>Dim SaveCharacter As StreamWriter
        If txtName.Text = "" Then
            MessageBox.Show("In order to save, you must enter a name for your character.", "Error: No Name Entered")
        Else
            Try
                SaveCharacter = File.AppendText("H:\Visual Basic Projects\DAndD-2.5\DAndD-2.5\Saves\" & txtName.Text & ".txt")
                SaveCharacter.WriteLine(frmNotes.rtxNotes.Text)
                SaveCharacter.Close()
            Catch
                MessageBox.Show("Error")
            End Try
        End If

 'Next event handler
            Dim OpenCharacter As StreamReader
            OpenCharacter = File.OpenText("H:\Visual Basic Projects\DAndD-2.5\DAndD-2.5\Saves\Jared.txt")
            Do Until OpenCharacter.EndOfStream
                frmNotes.rtxNotes.Text = OpenCharacter.ReadToEnd.ToString()
                For Each strLine As String In frmNotes.rtxNotes.Text.Split(vbNewLine)
                Next
            Loop
</code>```

Is there an easy(ish) way to do what I need, especially in mass (few lines of code) without having to save each TextBox as a different .txt file?

Thanks for the help!

答:
Loop through all the controls and pull out the TextBoxes:

```<code>  Sub SaveFile(strFilename As String)
    Using fs As New System.IO.FileStream(strFilename, IO.FileMode.OpenOrCreate)
      Using sr As New System.IO.StreamWriter(fs)
        For Each ctl As Control In Me.Controls
          If TypeOf ctl Is TextBox Then
            Dim txt As TextBox = DirectCast(ctl, TextBox)
            sr.WriteLine(txt.Name & ":" & txt.Text)
          End If
        Next ctl
      End Using
    End Using
  End Sub

  Sub Readfile(strfilename As String)
    Using fs As New System.IO.FileStream(strfilename, IO.FileMode.Open)
      Using sr As New System.IO.StreamReader(fs)
        Do Until sr.EndOfStream
          Dim strLine As String = sr.ReadLine
          Dim colonposition As Integer = strLine.IndexOf(":")
          If colonposition > 0 And colonposition < strLine.Length - 1 Then
            Dim strTextBoxName As String = strLine.Substring(0, colonposition)
            Dim strTextBoxText As String = strLine.Substring(colonposition + 1)
            Dim ctl() As Control = Me.Controls.Find(strTextBoxName, False)
            If ctl.Length > 0 AndAlso TypeOf ctl(0) Is TextBox Then
              DirectCast(ctl(0), TextBox).Text = strTextBoxText
            End If
          End If
        Loop
      End Using
    End Using
  End Sub
</code>```

The above code only works for textboxes on the form itself. You can rework it to be a recursive function to walk the containers, but I'll leave that as an exercise for the reader.

Body:
I need to save a bunch (around 600) of TextBox content to a (Preferably) single file, then be able to write that data back to their respective TextBoxes on file open. Essentially I'm making a D&D stat sheet, and I want to save what each player has entered as the [character's name].txt. I already got simple saving and writing down by using a single control and the code:

Dim SaveCharacter As StreamWriter
        If txtName.Text = "" Then
            MessageBox.Show("In order to save, you must enter a name for your character.", "Error: No Name Entered")
        Else
            Try
                SaveCharacter = File.AppendText("H:\Visual Basic Projects\DAndD-2.5\DAndD-2.5\Saves\" & txtName.Text & ".txt")
                SaveCharacter.WriteLine(frmNotes.rtxNotes.Text)
                SaveCharacter.Close()
            Catch
                MessageBox.Show("Error")
            End Try
        End If

 'Next event handler
            Dim OpenCharacter As StreamReader
            OpenCharacter = File.OpenText("H:\Visual Basic Projects\DAndD-2.5\DAndD-2.5\Saves\Jared.txt")
            Do Until OpenCharacter.EndOfStream
                frmNotes.rtxNotes.Text = OpenCharacter.ReadToEnd.ToString()
                For Each strLine As String In frmNotes.rtxNotes.Text.Split(vbNewLine)
                Next
            Loop

Is there an easy(ish) way to do what I need, especially in mass (few lines of code) without having to save each TextBox as a different .txt file?

Thanks for the help!

Body:
Loop through all the controls and pull out the TextBoxes:

  Sub SaveFile(strFilename As String)
    Using fs As New System.IO.FileStream(strFilename, IO.FileMode.OpenOrCreate)
      Using sr As New System.IO.StreamWriter(fs)
        For Each ctl As Control In Me.Controls
          If TypeOf ctl Is TextBox Then
            Dim txt As TextBox = DirectCast(ctl, TextBox)
            sr.WriteLine(txt.Name & ":" & txt.Text)
          End If
        Next ctl
      End Using
    End Using
  End Sub

  Sub Readfile(strfilename As String)
    Using fs As New System.IO.FileStream(strfilename, IO.FileMode.Open)
      Using sr As New System.IO.StreamReader(fs)
        Do Until sr.EndOfStream
          Dim strLine As String = sr.ReadLine
          Dim colonposition As Integer = strLine.IndexOf(":")
          If colonposition > 0 And colonposition < strLine.Length - 1 Then
            Dim strTextBoxName As String = strLine.Substring(0, colonposition)
            Dim strTextBoxText As String = strLine.Substring(colonposition + 1)
            Dim ctl() As Control = Me.Controls.Find(strTextBoxName, False)
            If ctl.Length > 0 AndAlso TypeOf ctl(0) Is TextBox Then
              DirectCast(ctl(0), TextBox).Text = strTextBoxText
            End If
          End If
        Loop
      End Using
    End Using
  End Sub

The above code only works for textboxes on the form itself. You can rework it to be a recursive function to walk the containers, but I'll leave that as an exercise for the reader.


问:
Flash Builder ignores output folder when syncing with SVN repository
I am having a lot of trouble while syncing my Flash Builder Actionscript project with Subversion. I have read that the output folders bin, bin-debug and html-template should not be checked in to the repository. The project bin folder contains a lot of XML files and assets that other project members needs to access. The problem is that Flash builder ignores it.

Is there a way of setting up Flash Builder to override the ignored bin folder? If not, what other approach should I consider? Different folder structures?

/src (commited)

/bin (ignored)

/swc (commited)

I would really like to override the default "DO NOT COMMIT YOUR DEPLOY FOLDER" setting. Bounty it is.

答: Why not externalize those assets in to a separate root folder (of your project) ? Checking in bin-debug folder is  a hassle , but if you keep a separate folder and use ant build to package it in to .war, then I do not see any issue.(with checking in this folder) (In fact that what we do, since sometimes we want to deploy our applications as portlets)</p>


问:
Decoding Windows-1252 characters in imap subject line to UTF-8
I have a website that will allow people to post things to it using the subject line of an email in Outlook. Using PHP and imap, I get the subject line of the text and store it in a mysql db. But every once in a while, someone will copy text from a website into the subject line of that email and I will get garbled text. Similar to this:

=?Windows-1252?Q?_Every_day_in_our_offices_we_recycle_cardboard,aluminum?=
=?Windows-1252?Q?=96_won=92t_you_join_us=3F?=

What I've done is try to decode this text so it will appear normal on the page using the following code:

```<code>$subject = strip_tags($mailHeader->subject);
$header = imap_mime_header_decode($subject);
$subject = "";
for($i=0;$i<count($header);$i++)
{
    $subject .= $header[$i]->text;
}
</code>```

When finished I get rid of most of the garbled text, but am left behind with replacement characters for an em dash and a curly quote that was in the original subject line text. See the result below:

Every day in our offices we recycle cardboard, aluminum, � won�t you join us?

The charset for the website is set to UTF-8. When I set the website charset to ISO-8859-1, the replacement characters are replaced with the curly quote and em dash, which is great but I want to leave the website's charset at UTF-8.

Any help on how to get rid of the replacement characters without changing the charset to ISO-8859-1 would be great. Thanks.

答:
Code above works except for one small change to the very end:</p>

```<code>$subject .= mb_convert_encoding($header[$i]->text, "UTF-8", $header[$i]->charset);
</code>```

Body:
I have a website that will allow people to post things to it using the subject line of an email in Outlook. Using PHP and imap, I get the subject line of the text and store it in a mysql db. But every once in a while, someone will copy text from a website into the subject line of that email and I will get garbled text. Similar to this:

=?Windows-1252?Q?_Every_day_in_our_offices_we_recycle_cardboard,aluminum?=
=?Windows-1252?Q?=96_won=92t_you_join_us=3F?=

What I've done is try to decode this text so it will appear normal on the page using the following code:

$subject = strip_tags($mailHeader->subject);
$header = imap_mime_header_decode($subject);
$subject = "";
for($i=0;$i<count($header);$i++)
{
    $subject .= $header[$i]->text;
}

When finished I get rid of most of the garbled text, but am left behind with replacement characters for an em dash and a curly quote that was in the original subject line text. See the result below:

Every day in our offices we recycle cardboard, aluminum, � won�t you join us?

The charset for the website is set to UTF-8. When I set the website charset to ISO-8859-1, the replacement characters are replaced with the curly quote and em dash, which is great but I want to leave the website's charset at UTF-8.

Any help on how to get rid of the replacement characters without changing the charset to ISO-8859-1 would be great. Thanks.

Body:
Code above works except for one small change to the very end:

$subject .= mb_convert_encoding($header[$i]->text, "UTF-8", $header[$i]->charset);