问:
How to Detach Glyphs with FontForge Python?
In the FontForge GUI under the 'Encoding' menu there is an option 'Detach Glyphs.' Can I do this in Python?

More specifically, in my Python script when I remove a glyph that is attached to another glyph, both are cleared. How can I avoid this?

答:
I was able to find a workaround from here https://sourceforge.net/p/fontforge/mailman/message/29723762/

It is essentially:

```<code>font.selection.select("a")           #select glyph
font.copy()
for i in font.selection.byGlyphs:
    font.removeGlyph(i)
font.selection.select("a")
font.paste()
</code>```

Body:
I was able to find a workaround from here https://sourceforge.net/p/fontforge/mailman/message/29723762/

It is essentially:

font.selection.select("a")           #select glyph
font.copy()
for i in font.selection.byGlyphs:
    font.removeGlyph(i)
font.selection.select("a")
font.paste()


来源: stackexchange

问:
JavaScript - Determine how a user arrived at html page
I'm building a web application and for one of my pages, I need to determine how a user arrived at the page (i.e. by redirect or by directly typing in the URL).

Is this possible with vanilla JavaScript?

答:
You can try using document.referrer

If somone types url in address bar it should return an empty string, otherwise if a link was clicked it should return prior page url

ContentLicense: CC BY-SA 3.0


问:
How to call two method one after another?
I'm building a simple Android Application. I want to parse JSON. I have everything working using Button. But I want call it without using Button. It need to be get the JSON first from url and then Parse it. I have function getJson() and parseJSON(). First I want getJSON to be called and after 5 second parseJSON(). here is my code:

```<code>Runnable[] methods = new Runnable[]{
            new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(SheduleActivity.this, "This is gettin JSON", Toast.LENGTH_LONG).show();
                    getJSON();

                }
            },
            new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(SheduleActivity.this, "This is Parsing JSON", Toast.LENGTH_LONG).show();
                    parseJSON();

                }
            }

    };

    for(Runnable r : methods)
        //r.run();
       service.submit(r);
   service.shutdown();
    while (!service.isTerminated()) {}
    Toast.makeText(SheduleActivity.this,"Finished all threads", Toast.LENGTH_LONG).show();
</code>```

Everytime I run my app only getJSON() method calls and stops. Any suggetions?

答:
Android does not suggest to use sleep(5000) for delay. Use handler to do this. See the documentation of Handler.

For example in your code,

```<code>Handler handler = new Handler( /* --- */ );
handler.postDelayed(methods[i], 5000);
</code>```

Also for getting json from web, it is suggested to use Asynctask to make the UI responsive. Best tutorial for Asynctask is here.

Body:
I'm building a simple Android Application. I want to parse JSON. I have everything working using Button. But I want call it without using Button. It need to be get the JSON first from url and then Parse it. I have function getJson() and parseJSON(). First I want getJSON to be called and after 5 second parseJSON(). here is my code:

Runnable[] methods = new Runnable[]{
            new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(SheduleActivity.this, "This is gettin JSON", Toast.LENGTH_LONG).show();
                    getJSON();

                }
            },
            new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(SheduleActivity.this, "This is Parsing JSON", Toast.LENGTH_LONG).show();
                    parseJSON();

                }
            }

    };

    for(Runnable r : methods)
        //r.run();
       service.submit(r);
   service.shutdown();
    while (!service.isTerminated()) {}
    Toast.makeText(SheduleActivity.this,"Finished all threads", Toast.LENGTH_LONG).show();

Everytime I run my app only getJSON() method calls and stops. Any suggetions?

Body:
Android does not suggest to use sleep(5000) for delay. Use handler to do this. See the documentation of Handler.

For example in your code,

Handler handler = new Handler( /* --- */ );
handler.postDelayed(methods[i], 5000);

Also for getting json from web, it is suggested to use Asynctask to make the UI responsive. Best tutorial for Asynctask is here.


问:
Java libraries that work with Microsoft Office documents but do not depend on automation
By "not depend on automation", I mean that it should not require a Microsoft Office installation to work; let alone interact with a live instance of a Microsoft Office component.  One such library is Aspose.Total for Java.  Are there any more out there?

Another solution I'm considering is to use OpenOffice.org.  However, I'm not sure if I'm going to run into the same problems as with Microsoft Office as detailed here.

答:
For Office Documents: http://poi.apache.org/

I have not tried this myself, but Apache usually deliver good libraries

For just Excel: JExcel API for Java

I use this for one application, and it works quite well. May use a fair bit of RAM for larger documents.

ContentLicense: CC BY-SA 2.5


问:
How to slow down animation time in Recharts?
I was trying to slow down the animation in recharts but i did not get any idea about it ..

I have tried in CSS part but that does not work

isAnimationActive={true} is to enable animation
isAnimationActive={false} is to disable animation
is there anyway to handle animation time ,

This is my Code

```<code>const {LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend} = Recharts;
const data = [
      {name: 'Page A', uv: 4000, pv: 2400, amt: 2400},
      {name: 'Page B', uv: 3000, pv: 1398, amt: 2210},
      {name: 'Page C', uv: 2000, pv: 9800, amt: 2290},
      {name: 'Page D', uv: 2780, pv: 3908, amt: 2000},
      {name: 'Page E', uv: 1890, pv: 4800, amt: 2181},
      {name: 'Page F', uv: 2390, pv: 3800, amt: 2500},
      {name: 'Page G', uv: 3490, pv: 4300, amt: 2100},
];
const SimpleLineChart = React.createClass({
    render () {
    return (
        <LineChart width={600} height={300} data={data}
            margin={{top: 5, right: 30, left: 20, bottom: 5}}>
       <XAxis dataKey="name"/>
       <YAxis yAxisId="left" />
       <YAxis yAxisId="right" orientation="right" />
       <CartesianGrid strokeDasharray="3 3"/>
       <Tooltip/>
       <Legend />
       <Line yAxisId="left" type="monotone" dataKey="pv" stroke="#8884d8" activeDot={{r: 8}}/>
       <Line yAxisId="right" type="monotone" dataKey="uv" stroke="#82ca9d" />
      </LineChart>
    );
  }
})

ReactDOM.render(
  <SimpleLineChart />,
  document.getElementById('container')
);
</code>```

recharts Js fiddle link

答:
the Soution is

```<code>let duration = 1000;
animationDuration={duration}
</code>```

Body:
I was trying to slow down the animation in recharts but i did not get any idea about it ..

I have tried in CSS part but that does not work

isAnimationActive={true} is to enable animation
isAnimationActive={false} is to disable animation
is there anyway to handle animation time ,

This is my Code

const {LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend} = Recharts;
const data = [
      {name: 'Page A', uv: 4000, pv: 2400, amt: 2400},
      {name: 'Page B', uv: 3000, pv: 1398, amt: 2210},
      {name: 'Page C', uv: 2000, pv: 9800, amt: 2290},
      {name: 'Page D', uv: 2780, pv: 3908, amt: 2000},
      {name: 'Page E', uv: 1890, pv: 4800, amt: 2181},
      {name: 'Page F', uv: 2390, pv: 3800, amt: 2500},
      {name: 'Page G', uv: 3490, pv: 4300, amt: 2100},
];
const SimpleLineChart = React.createClass({
    render () {
    return (
        <LineChart width={600} height={300} data={data}
            margin={{top: 5, right: 30, left: 20, bottom: 5}}>
       <XAxis dataKey="name"/>
       <YAxis yAxisId="left" />
       <YAxis yAxisId="right" orientation="right" />
       <CartesianGrid strokeDasharray="3 3"/>
       <Tooltip/>
       <Legend />
       <Line yAxisId="left" type="monotone" dataKey="pv" stroke="#8884d8" activeDot={{r: 8}}/>
       <Line yAxisId="right" type="monotone" dataKey="uv" stroke="#82ca9d" />
      </LineChart>
    );
  }
})

ReactDOM.render(
  <SimpleLineChart />,
  document.getElementById('container')
);

recharts Js fiddle link

Body:
the Soution is

let duration = 1000;
animationDuration={duration}


问:
API URL call with PHP and cURL
I'm hoping someone can help me out.

I have an API call using this URL.

```<code>https://192.168.11.234:4444/webconsole/APIController?reqxml=<Request><Login<Username>XXXXX</Username><Password>XXXXX></Password></Login><Get><User><Username>manager</Username></User></Get></Request>
</code>```

This works fine and returns an XML as expected.

However I'm attempting to do the same thing with PHP and cURL.

I have very little experience with cURL

So far I've tried variations of this but I get no response. only a blank page.  wondering if maybe someone could help me out.

```<code><?php
$input_xml = '<Request><Login><Username>XXXX</Username><Password>XXXX</Password></Login><Get><User></User></Get></Request>';
$url = "https://192.168.11.234:4444/webconsole/APIController";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_POSTFIELDS,
            "reqxml=" . $input_xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);

$array_data = json_decode(json_encode(simplexml_load_string($data)), true);

print_r('```');
print_r($array_data);
print_r('```');
?>
</code>```

I will admit I have not worked with cURL much, so I may be way off.

答:
What do you get when you try the following:

var_dump($data);

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));

Edit:
Oh, and CURLOPT_POST = true

ContentLicense: CC BY-SA 4.0

Title: API URL call with PHP and cURL

Body:
I'm hoping someone can help me out.

I have an API call using this URL.

https://192.168.11.234:4444/webconsole/APIController?reqxml=<Request><Login<Username>XXXXX</Username><Password>XXXXX></Password></Login><Get><User><Username>manager</Username></User></Get></Request>

This works fine and returns an XML as expected.

However I'm attempting to do the same thing with PHP and cURL.

I have very little experience with cURL

So far I've tried variations of this but I get no response. only a blank page.  wondering if maybe someone could help me out.

<?php
$input_xml = '<Request><Login><Username>XXXX</Username><Password>XXXX</Password></Login><Get><User></User></Get></Request>';
$url = "https://192.168.11.234:4444/webconsole/APIController";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_POSTFIELDS,
            "reqxml=" . $input_xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);

$array_data = json_decode(json_encode(simplexml_load_string($data)), true);

print_r('
');
print_r($array_data);
print_r('
');
?>

I will admit I have not worked with cURL much, so I may be way off.


问:
NAudio Start new song error
I'm trying to develop a music player based on NAudio lib. When I first start a song, its OK. When I try to start another song, I get an error:

InvalidParameter calling waveOutOpen at string:

```<code>player.Init(aReader);
</code>```

A little context: I'm using those methods to start and stop playing a song:

Playing

```<code>        StopAudio();
        aReader = new AudioFileReader((string)musicFile);
        aReader.Volume = Form1.Singleton.GetMusicVolume();

        player.Init(aReader);
        player.Play();
</code>```

Re-Playing / Stopping

```<code>       if (player == null || aReader == null) return;

        aReader.Dispose();
        player.Stop();
        player.Dispose();
</code>```

答:
Fixed.
At song stopping needs to make player & nAudio as null, and at start check is player null and if it is then initialize it.</p>

Title: NAudio Start new song error

Body:
I'm trying to develop a music player based on NAudio lib. When I first start a song, its OK. When I try to start another song, I get an error:

InvalidParameter calling waveOutOpen at string:

player.Init(aReader);

A little context: I'm using those methods to start and stop playing a song:

Playing

        StopAudio();
        aReader = new AudioFileReader((string)musicFile);
        aReader.Volume = Form1.Singleton.GetMusicVolume();

        player.Init(aReader);
        player.Play();

Re-Playing / Stopping

       if (player == null || aReader == null) return;

        aReader.Dispose();
        player.Stop();
        player.Dispose();


问:
Ignore file from git commit but protect it from clean
In my work tree I have a mixture of files in .gitignore:

Build outputs

Sensitive files that shouldn't be part of the repo (e.g. passwords, connection details for local servers)

If I want to rebuild my project from scratch, I can do git clean -x to remove the build outputs in (1). But this also removes the sensitive files in (2).

Is there a way to mark a file so it's not affected by git clean while still being ignored by git commit?

答:
Take a look at this answer from @Borealid to the question Git - Difference Between 'assume-unchanged' and 'skip-worktree'.

It looks like using the skip-worktree flag is a good way to solve my problem.  I got to your problem by looking for an answer to my problem, and I think they are essentially the same problem.  However, using the skip-worktree flag, you still need to pay attention when performing certain operations and the file has changed either locally or on the remote.

Prior to learning about the skip-worktree flag, the best solution I could come up with is to use a combination of .gitignore plus an alias for git clean.  It is a bit of a hack, but if your only option is to use the exclude option with git clean, then this may help.

Add a consistent and unique prefix and/or postfix to any files you are modifying and do not want to commit.  For example, add myusername. to the beginning of the filename.

Always use git clean -dx --exclude=myusername.* (make an alias for this).

Write a script that recursively walks your files and copies files beginning with myusername. to files without myusername..

Now, whenever you run cleanup, the files with the desired/true filename are going to get cleaned, but you can restore them by running the script.  Also, treat the files with the true filename as readonly.  Always edit the files with the kludged filenames and then run the script.

Combining these might also work to mitigate the edge cases when using the skip-worktree flag.


问:
How to use the "handler" of UIAlertAction to call another UIAlertAction?
Is it possible to use the handler to trigger other alerts?

```<code>func jokeFinal() {
    let alert = UIAlertController(title: "Never Mind", message: "It's Pointless", preferredStyle: .alert)
    let action = UIAlertAction(title: "Hahahahahaha", style: .default, handler: nil)
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
}

func joke() {
    let alert = UIAlertController(title: "A broken pencil", message: "...", preferredStyle: .alert)
    let action = UIAlertAction(title: "A broken pencil who?", style: .default, handler: jokeFinal())
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
}

@IBAction func nock() {
    let alert = UIAlertController(title: "Knock,Knock", message: "..", preferredStyle: .alert)
    let action = UIAlertAction(title: "Who's there??", style: .default, handler: joke())
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
}
</code>```

I'm trying to use the handler of a UIAlertAction to call another UIAlert. Is it possible?

I am receiving the following error:

Cannot convert value of type '()' to expected argument type '((UIAlertAction) -> Void)?'

答:
Yes of course! It's possible. Try something like that:

```<code>let alertController = UIAlertController.init(title: "Title", message: "Message", preferredStyle: .alert)
alertController.addAction(UIAlertAction.init(title: "Title", style: .default, handler: { (action) in
        self.someFunction()
}))
self.present(alertController, animated: true, completion: nil)
</code>```

Here's your function:

```<code>func someFunction() {
    let alertController = UIAlertController.init(title: "Some Title", message: "Some Message", preferredStyle: .alert)
    alertController.addAction(UIAlertAction.init(title: "Title For Button", style: .default, handler: { (action) in
        // Completion block
    }))
    self.present(alertController, animated: true, completion: nil)
}
</code>```

Here's your problem line:

```<code>let action = UIAlertAction(title: "Who's there??", style: .default, handler: joke())
</code>```

You can easily change it to:

```<code>let action = UIAlertAction(title: "Who's there??", style: .default, handler: { (action) in
        // Completion block
})
</code>```

Hope it helps!

Body:
Is it possible to use the handler to trigger other alerts?

func jokeFinal() {
    let alert = UIAlertController(title: "Never Mind", message: "It's Pointless", preferredStyle: .alert)
    let action = UIAlertAction(title: "Hahahahahaha", style: .default, handler: nil)
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
}

func joke() {
    let alert = UIAlertController(title: "A broken pencil", message: "...", preferredStyle: .alert)
    let action = UIAlertAction(title: "A broken pencil who?", style: .default, handler: jokeFinal())
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
}

@IBAction func nock() {
    let alert = UIAlertController(title: "Knock,Knock", message: "..", preferredStyle: .alert)
    let action = UIAlertAction(title: "Who's there??", style: .default, handler: joke())
    alert.addAction(action)
    present(alert, animated: true, completion: nil)
}

I'm trying to use the handler of a UIAlertAction to call another UIAlert. Is it possible?

I am receiving the following error:

Cannot convert value of type '()' to expected argument type '((UIAlertAction) -> Void)?'

Body:
Yes of course! It's possible. Try something like that:

let alertController = UIAlertController.init(title: "Title", message: "Message", preferredStyle: .alert)
alertController.addAction(UIAlertAction.init(title: "Title", style: .default, handler: { (action) in
        self.someFunction()
}))
self.present(alertController, animated: true, completion: nil)

Here's your function:

func someFunction() {
    let alertController = UIAlertController.init(title: "Some Title", message: "Some Message", preferredStyle: .alert)
    alertController.addAction(UIAlertAction.init(title: "Title For Button", style: .default, handler: { (action) in
        // Completion block
    }))
    self.present(alertController, animated: true, completion: nil)
}

Here's your problem line:

let action = UIAlertAction(title: "Who's there??", style: .default, handler: joke())

You can easily change it to:

let action = UIAlertAction(title: "Who's there??", style: .default, handler: { (action) in
        // Completion block
})

Hope it helps!


问:
Pandas GroupBy column value and create list of fixed size from values in each group
First post, did my best to describe my issue. Let me know if I need to adjust anything with respect to format or clarify any aspects of the problem. Thanks!

I have large Pandas data frame of movie ratings and I need to create user ratings vectors for each movie. I am looking for a way to this more efficiently (using pandas / numpy operations or vectorization??) in order to process the 26M rows or user, movie rating pairs in my dataset.

The data frame of movie ratings looks like this:
Input:

```<code>movieId userId  rating
1            1     1.0
1            2     4.5
1            5     5.0
1            8     5.0
1           10     5.0
2            1     2.0
2            3     4.5
2            5     5.0
2            6     3.0
2            8     4.0
</code>```

Output:

Key = MovieID

Value = Dense array of ratings for each user, 0 means the user did not rate the movie.

```<code>{
   0:[1.0, 4.5, 0.0, 0.0, 5.0, 0.0, 0.0, 5.0, 0.0, 5.0]
   1:[2.0, 0.0, 4.5, 0.0, 5.0, 3.0, 0.0, 4.0, 0.0, 0.0]
}
</code>```

I currently have this function which performs the job correctly but is not scaling which the amount of data I need to process.
user_rating_by_movie is a global pandas data frame matching the form of the input.
num_users is the largest user id to serve as the length of the vector.

```<code>def build_rating_vector_for_movie(movie_id, num_users):
    rating_vector = [0] * num_users
    movie_group = user_rating_by_movie.get_group(movie_id)

    for u, r in zip(movie_group.userId.values, movie_group.rating.values):
        rating_vector[u - 1] = r

    movie_user_ratings[movie_id] = rating_vector
</code>```

答:
Inspired by @Wen

```<code>pd.crosstab(df.movieId, df.userId, df.rating, aggfunc='mean').fillna(0).T.to_dict('list')
</code>```

Output:

```<code>{1: [1.0, 4.5, 0.0, 5.0, 0.0, 5.0, 5.0],
 2: [2.0, 0.0, 4.5, 5.0, 3.0, 4.0, 0.0]}
</code>```

Note:

The 'mean' in aggfunc should be meaningless if one rating per user for each movie.

Body:
First post, did my best to describe my issue. Let me know if I need to adjust anything with respect to format or clarify any aspects of the problem. Thanks!

I have large Pandas data frame of movie ratings and I need to create user ratings vectors for each movie. I am looking for a way to this more efficiently (using pandas / numpy operations or vectorization??) in order to process the 26M rows or user, movie rating pairs in my dataset.

The data frame of movie ratings looks like this:
Input:

movieId userId  rating
1            1     1.0
1            2     4.5
1            5     5.0
1            8     5.0
1           10     5.0
2            1     2.0
2            3     4.5
2            5     5.0
2            6     3.0
2            8     4.0

Output:

Key = MovieID

Value = Dense array of ratings for each user, 0 means the user did not rate the movie.

{
   0:[1.0, 4.5, 0.0, 0.0, 5.0, 0.0, 0.0, 5.0, 0.0, 5.0]
   1:[2.0, 0.0, 4.5, 0.0, 5.0, 3.0, 0.0, 4.0, 0.0, 0.0]
}

I currently have this function which performs the job correctly but is not scaling which the amount of data I need to process.
user_rating_by_movie is a global pandas data frame matching the form of the input.
num_users is the largest user id to serve as the length of the vector.

def build_rating_vector_for_movie(movie_id, num_users):
    rating_vector = [0] * num_users
    movie_group = user_rating_by_movie.get_group(movie_id)

    for u, r in zip(movie_group.userId.values, movie_group.rating.values):
        rating_vector[u - 1] = r

    movie_user_ratings[movie_id] = rating_vector

Body:
Inspired by @Wen

pd.crosstab(df.movieId, df.userId, df.rating, aggfunc='mean').fillna(0).T.to_dict('list')

Output:

{1: [1.0, 4.5, 0.0, 5.0, 0.0, 5.0, 5.0],
 2: [2.0, 0.0, 4.5, 5.0, 3.0, 4.0, 0.0]}

Note:

The 'mean' in aggfunc should be meaningless if one rating per user for each movie.


问:
rbind () on a conditional basis
Here's the question. I have a bunch of if statements that create different data frames (A-F) based on the user inputs. In some instances, some of the data frames will be empty, so maybe (A-C) are empty, but (D-F) have information.

I'm trying to create a conditional rbind(), where it combines the rows only if the data frame is not empty.

I'm not quite sure how to go about this? I don't know if I should create a bunch of conditions and use another if statement:

```<code>cond_a <- nrow(a) != 0
cond_b <- nrow(b) != 0
cond_c <- nrow(c) != 0
cond_d <- nrow(d) != 0
cond_e <- nrow(e) != 0
cond_f <- nrow(f) != 0
</code>```

but then I don't know how to utilize these conditions...

EDIT: To take a step back and better explain: I have one data frame that I split into 6 different data frames by subsetting by a column, so it splits it into 6 data frames (A-G). The column has the letters A-G. These letters A-G in that column change depending on user inputs.

I then have a series of if statements that asks "if A is not empty then perform this aggregation", thereby skipping the df if it has no data in it. The aggregation takes it from 16 to 19 columns. Because the empty df has not been aggregated it still has 19 columns. After I perform these if statements and aggregations, I am left with dfA, dfB, dfC, etc. that have either been aggregated (16 columns) or still empty (19 columns). I then want a piece of code that says "for the df that have been aggregated (16 columns) rbind, if the df has not been aggregated (is empty), then don't perform the rbind.

thanks!

答:
You can do something like this :

Create an empty list of the data frames you wish to select.

Write a bunch of if statements to see which ones contain non-zero zeros

Keep adding those names of non-zero DFs to the empty list created in step 1

Write an expression which collapses those names to an rbind expression

Evaluate the expression

Here is the script to do it :

1.Create an Empty list to store the names of dataframes

```<code>list.df = " "
</code>```

2&3. If statements check if the Data Frame is Non-Zero, add the name to the  list if true

```<code>if(nrow(df.a) > 0) {
  list.df=c(list.df,deparse(substitute(df.a)))
 }

if(nrow(df.b) > 0) {
  list.df=c(list.df,deparse(substitute(df.b)))
 }

if(nrow(df.c) > 0) {
 list.df=c(list.df,deparse(substitute(df.c)))
 }
</code>```

.... So on from A through G

```<code>if(nrow(df.g) > 0) {
 list.df=c(list.df,deparse(substitute(df.g)))
 }
</code>```

4.Formulate the expression

```<code>list.df = list.df[2:length(list.df)] #remove first element
expression = paste0("df.combined = rbind(",paste0( list.df, collapse =
','), paste0(")"))
</code>```

5.Evaluate the expression

```<code>eval(parse(text=expression))
</code>```

df.combined will be your final dataset that you are looking for

Title: rbind () on a conditional basis

Body:
Here's the question. I have a bunch of if statements that create different data frames (A-F) based on the user inputs. In some instances, some of the data frames will be empty, so maybe (A-C) are empty, but (D-F) have information.

I'm trying to create a conditional rbind(), where it combines the rows only if the data frame is not empty.

I'm not quite sure how to go about this? I don't know if I should create a bunch of conditions and use another if statement:

cond_a <- nrow(a) != 0
cond_b <- nrow(b) != 0
cond_c <- nrow(c) != 0
cond_d <- nrow(d) != 0
cond_e <- nrow(e) != 0
cond_f <- nrow(f) != 0

but then I don't know how to utilize these conditions...

EDIT: To take a step back and better explain: I have one data frame that I split into 6 different data frames by subsetting by a column, so it splits it into 6 data frames (A-G). The column has the letters A-G. These letters A-G in that column change depending on user inputs.

I then have a series of if statements that asks "if A is not empty then perform this aggregation", thereby skipping the df if it has no data in it. The aggregation takes it from 16 to 19 columns. Because the empty df has not been aggregated it still has 19 columns. After I perform these if statements and aggregations, I am left with dfA, dfB, dfC, etc. that have either been aggregated (16 columns) or still empty (19 columns). I then want a piece of code that says "for the df that have been aggregated (16 columns) rbind, if the df has not been aggregated (is empty), then don't perform the rbind.

thanks!

Body:
You can do something like this :

Create an empty list of the data frames you wish to select.

Write a bunch of if statements to see which ones contain non-zero zeros

Keep adding those names of non-zero DFs to the empty list created in step 1

Write an expression which collapses those names to an rbind expression

Evaluate the expression

Here is the script to do it :

1.Create an Empty list to store the names of dataframes

list.df = " "

2&3. If statements check if the Data Frame is Non-Zero, add the name to the  list if true

if(nrow(df.a) > 0) {
  list.df=c(list.df,deparse(substitute(df.a)))
 }

if(nrow(df.b) > 0) {
  list.df=c(list.df,deparse(substitute(df.b)))
 }

if(nrow(df.c) > 0) {
 list.df=c(list.df,deparse(substitute(df.c)))
 }

.... So on from A through G

if(nrow(df.g) > 0) {
 list.df=c(list.df,deparse(substitute(df.g)))
 }

4.Formulate the expression

list.df = list.df[2:length(list.df)] #remove first element
expression = paste0("df.combined = rbind(",paste0( list.df, collapse =
','), paste0(")"))

5.Evaluate the expression

eval(parse(text=expression))

df.combined will be your final dataset that you are looking for


问:
Return false within anchor tag gives error
I have the following statement

```<code><a href="javascript: return false;" id="addNew1">ADD NEW ROW</a>
</code>```

If I click on this I get the following error in my browser.

```<code>return not in function
</code>```

I use the following JQuery function

```<code>$('#addNew,#addNew1').click(function(){
</code>```

Do I need to include this in the function, the reason I do not add 'n # sign in is because the the page jumps to the top of the page.

答:
```<code><a href="#" onclick="return false;" id="addNew1">ADD NEW ROW</a>
</code>```

Body:
I have the following statement

ADD NEW ROW

If I click on this I get the following error in my browser.

return not in function

I use the following JQuery function

$('#addNew,#addNew1').click(function(){

Do I need to include this in the function, the reason I do not add 'n # sign in is because the the page jumps to the top of the page.


问:
Invalid provider for the NgModule 'DynamicTestModule' when testing a service in Angular 2
I have the following service:

```<code>import { Injectable } from '@angular/core';

import { MenuItem } from './../classes/menu-item';
import { ITEMS } from './../static-data/items-list';

@Injectable()
export class ItemsListService {

    getItems(): Promise<MenuItem[]> {
        return Promise.resolve(ITEMS);
    }

}
</code>```

The test for this service is here:

```<code>import { TestBed, async, inject } from '@angular/core/testing';

import { ItemListService } from './item-list.service';
import { MenuItem } from './../classes/menu-item';
import { ITEMS } from './../static-data/items-list';

describe('ItemListService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [ ItemListService, MenuItem, ITEMS ]
    });
  });

  it('should ...', inject([ItemListService], (service: ItemListService) => {
    expect(service).toBeTruthy();
  }));
});
</code>```

The MenuItem is defined here:

```<code>export class MenuItem {
    name: string;
    link: string;
}
</code>```

ITEMS is defined here:
import { MenuItem } from './../classes/menu-item';

```<code>export var ITEMS: MenuItem[] = [
    {name: 'Vehicles', link: '/vehicles'},
    {name: 'Gateways', link: '/gateways'},
    {name: 'Statuses', link: '/statuses'},
    {name: 'Logs', link: '/logs'}
]
</code>```

When I run the test I am getting in the browsers console the followings errors:

```<code>FAILED ItemListService should ...
</code>```

and

So why do I have these errors? And what is the solution for the test to work?

答:
This is such an annoying error, thought I'd include another subtle cause to look for in your spec. In my case I specified providers instead of the correct value of provide as below

```<code> TestBed.configureTestingModule({
      providers: [{provider: ApplicationActions, useClass: ActionMock}]
</code>```

rather than offer useful information like "no 'provide' key specified" it simply reports

Failed: Invalid provider for the NgModule 'DynamicTestModule' - only
instances of Provider and Type are allowed, got: [?[object Object]?,
...]

Body:
I have the following service:

import { Injectable } from '@angular/core';

import { MenuItem } from './../classes/menu-item';
import { ITEMS } from './../static-data/items-list';

@Injectable()
export class ItemsListService {

    getItems(): Promise<MenuItem[]> {
        return Promise.resolve(ITEMS);
    }

}

The test for this service is here:

import { TestBed, async, inject } from '@angular/core/testing';

import { ItemListService } from './item-list.service';
import { MenuItem } from './../classes/menu-item';
import { ITEMS } from './../static-data/items-list';

describe('ItemListService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [ ItemListService, MenuItem, ITEMS ]
    });
  });

  it('should ...', inject([ItemListService], (service: ItemListService) => {
    expect(service).toBeTruthy();
  }));
});

The MenuItem is defined here:

export class MenuItem {
    name: string;
    link: string;
}

ITEMS is defined here:
import { MenuItem } from './../classes/menu-item';

export var ITEMS: MenuItem[] = [
    {name: 'Vehicles', link: '/vehicles'},
    {name: 'Gateways', link: '/gateways'},
    {name: 'Statuses', link: '/statuses'},
    {name: 'Logs', link: '/logs'}
]

When I run the test I am getting in the browsers console the followings errors:

FAILED ItemListService should ...

and

So why do I have these errors? And what is the solution for the test to work?

Body:
This is such an annoying error, thought I'd include another subtle cause to look for in your spec. In my case I specified providers instead of the correct value of provide as below

 TestBed.configureTestingModule({
      providers: [{provider: ApplicationActions, useClass: ActionMock}]

rather than offer useful information like "no 'provide' key specified" it simply reports

Failed: Invalid provider for the NgModule 'DynamicTestModule' - only
instances of Provider and Type are allowed, got: [?[object Object]?,
...]


问:
How to confirm user in Cognito User Pools without verifying email or phone?
I am using Amazon Cognito Identity SDK for JavaScript (deprecated).

I created new pool without verifying email and phone_number.

By default, users aren't confirmed in Cognito User Pools, so I need to do this manually.

How to confirm user in Cognito User Pools without verifying email or phone?

答:
Actually, AWS has recently added the ability to verify email and verify phone number in the pre-signup lambda as well. You basically need to set autoVerifyEmail and autoVerifyPhone in the lambda and they will get verified.
More info in the official documentation.

```<code>"response": {
    "autoConfirmUser": boolean
    "autoVerifyEmail": boolean
    "autoVerifyPhone": boolean
}
</code>```

Body:
Actually, AWS has recently added the ability to verify email and verify phone number in the pre-signup lambda as well. You basically need to set autoVerifyEmail and autoVerifyPhone in the lambda and they will get verified.
More info in the official documentation.

"response": {
    "autoConfirmUser": boolean
    "autoVerifyEmail": boolean
    "autoVerifyPhone": boolean
}


问:
ASP.NET MVC 3: Override "name" attribute with TextBoxFor
Is it possible when using Html.TextBoxFor to override the name attribute?

I have tried with no success. I need to use TextBoxFor to get client side validation to work, however for reasons I won't go into I need the name of the textbox to be different from the generated one.

I have tried the following:

```<code>@Html.TextBoxFor(x => x.Data, new { name = Model.Key + "_Data", id = Model.Key + "_Data" })
</code>```

Which works for ID but not name. Is this possible?

Update: Looking into the code for TextBoxFor. It doesn't look like there is an easy way. Hopefully someone can prove me wrong.

答:
It is called Microsoft GOTCHA...

Use the name in caps, like this

```<code>@Html.TextBoxFor(m => m.Reply.Answer, new { Name = "Whatyouwant" })
</code>```

Body:
Is it possible when using Html.TextBoxFor to override the name attribute?

I have tried with no success. I need to use TextBoxFor to get client side validation to work, however for reasons I won't go into I need the name of the textbox to be different from the generated one.

I have tried the following:

@Html.TextBoxFor(x => x.Data, new { name = Model.Key + "_Data", id = Model.Key + "_Data" })

Which works for ID but not name. Is this possible?

Update: Looking into the code for TextBoxFor. It doesn't look like there is an easy way. Hopefully someone can prove me wrong.

Body:
It is called Microsoft GOTCHA...

Use the name in caps, like this

@Html.TextBoxFor(m => m.Reply.Answer, new { Name = "Whatyouwant" })


问:
How to insert Json values into Azure TableStorage?
Here is my code

I am trying to insert Json values into Azure as Entity, but I always get only the first value when I get back from Azure..Is there anything I need to change in the below code?

```<code>    string Emulators = "['TestEmulator1','Testemulator12','Testemulator2','TestEmulator3']";

    List<string> Emulators = new List<string>();
    EmulatorIDS.Add(Emulators);
    var jsondata = JsonConvert.SerializeObject(Emulators);
    Console.WriteLine(jsondata);
    var EmulatorID = new EntityProperty(jsondata);

    //Instantiate serializer
    Random rnd = new Random();
    int a = rnd.Next(1, 1000);

    DynamicTableEntity actordata = new DynamicTableEntity();

    actordata.RowKey = "Test"+a.ToString();
    actordata.PartitionKey = "test@gmail.com";
    actordata.Properties["DetailsValue"] = EmulatorID;
    actordata.Properties["OtherData"] = EmulatorID;

    TableOperation insertOperation = TableOperation.Insert(actordata);
    table.Execute(insertOperation);
</code>```

答: If anybody is looking for answer for this..Please see here about how to insert Json values via TableEntity instead of using JsonPayload format</p>

Body:
Here is my code

I am trying to insert Json values into Azure as Entity, but I always get only the first value when I get back from Azure..Is there anything I need to change in the below code?

    string Emulators = "['TestEmulator1','Testemulator12','Testemulator2','TestEmulator3']";

    List<string> Emulators = new List<string>();
    EmulatorIDS.Add(Emulators);
    var jsondata = JsonConvert.SerializeObject(Emulators);
    Console.WriteLine(jsondata);
    var EmulatorID = new EntityProperty(jsondata);

    //Instantiate serializer
    Random rnd = new Random();
    int a = rnd.Next(1, 1000);

    DynamicTableEntity actordata = new DynamicTableEntity();

    actordata.RowKey = "Test"+a.ToString();
    actordata.PartitionKey = "test@gmail.com";
    actordata.Properties["DetailsValue"] = EmulatorID;
    actordata.Properties["OtherData"] = EmulatorID;

    TableOperation insertOperation = TableOperation.Insert(actordata);
    table.Execute(insertOperation);


问:
Versioning library like SQLite database library?
I like how SQLite library can be included into an application and the application has a full-fledged database to use.

Similarly, is there an open source versioning library that I can include into my application so that I can save versions of files as well as do diffs and merges?

答:
I am not entirely sure what you mean by "included in an application", as you could potentially deliver any library so long as the licensing allows.  Are you referring to the fact that sqlite is small or that it is public domain?

Mercurial is a similarly lightweight piece of revision control software.  If you are writing your application in python, which is likely since python now includes sqlite3, importing features directly from mercurial's source code should not be too difficult.  Otherwise there's no shame in invoking commandline processes, though this may be clunkier.  Mercurial is not public domain, but it is GPL'd.

Mercurial is also my personal favorite among modern revision control systems.  It's leaps ahead of CVS and Subversion, and very similar to GIT although somewhat simpler to use.

OwnerDisplayName: Swaroop C H

LastEditorDisplayName: Cebjyre

OwnerDisplayName: Nick Retallack


答:
Remove the POSTFIEILDS line and replace the URL line with this

```<code>curl_setopt($ch, CURLOPT_URL, $url."?reqxml=" . urlencode($input_xml));
</code>```

That should work.

Title: API URL call with PHP and cURL

Body:
Remove the POSTFIEILDS line and replace the URL line with this

curl_setopt($ch, CURLOPT_URL, $url."?reqxml=" . urlencode($input_xml));

That should work.


问:
Get sum of two columns and save it to variable
In my MySQL, I have field ID, price, and date field (timestamp).

I want to, at end of the month, calculate total cost for that month and save it to variable $monthjuly.

```<code>SELECT SUM(price) FROM app WHERE YEAR(datum) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND MONTH(datum) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)"
</code>```

I tried via this command to output results, but I am not getting any result with this metod.
Where is my mistake here?

答:
You are not mention server, application and DB details so I am sharing you overview of functionality to achieve your requirement.

step 1 : You need to add function in your application which will call using URL. and that function should should have following code,

```<code>function foo() {
    // compare today date and check is it last day of month or not
    if($islastday) {
        // fetch data from sql current month
        //SELECT sum(cost)
        //FROM table
        //WHERE MONTH(date field) = MONTH(CURRENT_DATE())
        //AND YEAR(date field) = YEAR(CURRENT_DATE())

        //write mail function and send mail with email template providing it
        sql data
    }
}
</code>```

step 2 : set cron job for daily basis to call above function.

Thanks.

Body:
In my MySQL, I have field ID, price, and date field (timestamp).

I want to, at end of the month, calculate total cost for that month and save it to variable $monthjuly.

SELECT SUM(price) FROM app WHERE YEAR(datum) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND MONTH(datum) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)"

I tried via this command to output results, but I am not getting any result with this metod.
Where is my mistake here?

Body:
You are not mention server, application and DB details so I am sharing you overview of functionality to achieve your requirement.

step 1 : You need to add function in your application which will call using URL. and that function should should have following code,

function foo() {
    // compare today date and check is it last day of month or not
    if($islastday) {
        // fetch data from sql current month
        //SELECT sum(cost)
        //FROM table
        //WHERE MONTH(date field) = MONTH(CURRENT_DATE())
        //AND YEAR(date field) = YEAR(CURRENT_DATE())

        //write mail function and send mail with email template providing it
        sql data
    }
}

step 2 : set cron job for daily basis to call above function.

Thanks.


问:
Trying to Understand an Implementation of Hash#merge with Procs
trying to understand this problem here. I am creating my own verison of the hash#merge called hash#my_merge that can take in a proc. I'm trying to understand what does do:

```<code>self.each do |k,v|
  newhash[k]=hash[k] ? prc.call(k,v,hash[k]): v
end
</code>```

Its look like a ternary operation but newhash[k]=hash[k] isn't a true/false statement? The prompt and the rest of the question is as follows:

```<code>class Hash
# Hash#merge takes a proc that accepts three arguments: a key and the two
# corresponding values in the hashes being merged. Hash#merge then sets that
# key to the return value of the proc in a new hash. If no proc is given,
# Hash#merge simply merges the two hashes.
#
# Write a method with the functionality of Hash#merge. Your Hash#my_merge
method
# should optionally take a proc as an argument and return a new hash. If a
proc
# is not given, your method should provide default merging behavior. Do not
use
# Hash#merge in your method.

  def my_merge(hash, &prc)
    prc ||=Proc.new{|k,oldval,newval|}
    newhash=Hash.new

    self.each do |k,v|
      newhash[k]=hash[k] ? prc.call(k,v,hash[k]): v
    end

    hash.each do |k,v|
      newhash[k]=v if newhash[k].nil?
    end
    newhash
  end
end
</code>```

Any help would be greatly appreciated. Thanks!

答:
The line your misunderstanding is a ternary, but the order of operations aren't what you're expecting. When Ruby sees:

```<code>newhash[k]=hash[k] ? prc.call(k,v,hash[k]): v
</code>```

it views it as

```<code>newhash[k]= (hash[k] ? prc.call(k,v,hash[k]): v)
</code>```

So, if hash[k] is a truth-y value, call the proc and assign the result to newhash[k]; otherwise, assign v to newhash[k].

You can see that this is how Ruby views this line by looking at the Operator Precedence file, which has (among a bunch of other operators):

?, :

modifier-rescue

=, +=, -=, etc.

So the ternary is higher precedence than the assignment operators.

It's also worth noting that newhash[k] = hash[k] is, in Ruby, a true/false statement, since assignment returns what was assigned:

```<code>a = 1 # => 1
a = nil # => nil
</code>```

and everything except for false and nil in Ruby are seen as a truth-y value, you can do stuff like:

```<code>if a = 2
  puts "truthy"
end
# outputs 'truthy'
</code>```

and

```<code>if a = nil
  puts "truthy"
end
# outputs nothing
</code>```

and with proper parenthesizing, you can use it in a ternary:

```<code>(a = 1) ? 'truthy' : 'falsey' # => 'truthy'
(a = nil) ? 'truthy' : 'falsey' # => 'falsey'
</code>```

Though, this can be confusing (usually in a conditional you'd see == not =, and in fact my Ruby gives me a warning that I'm using the = instead of == in a conditional); but it can be done

Body:
trying to understand this problem here. I am creating my own verison of the hash#merge called hash#my_merge that can take in a proc. I'm trying to understand what does do:

self.each do |k,v|
  newhash[k]=hash[k] ? prc.call(k,v,hash[k]): v
end

Its look like a ternary operation but newhash[k]=hash[k] isn't a true/false statement? The prompt and the rest of the question is as follows:

class Hash
# Hash#merge takes a proc that accepts three arguments: a key and the two
# corresponding values in the hashes being merged. Hash#merge then sets that
# key to the return value of the proc in a new hash. If no proc is given,
# Hash#merge simply merges the two hashes.
#
# Write a method with the functionality of Hash#merge. Your Hash#my_merge
method
# should optionally take a proc as an argument and return a new hash. If a
proc
# is not given, your method should provide default merging behavior. Do not
use
# Hash#merge in your method.

  def my_merge(hash, &prc)
    prc ||=Proc.new{|k,oldval,newval|}
    newhash=Hash.new

    self.each do |k,v|
      newhash[k]=hash[k] ? prc.call(k,v,hash[k]): v
    end

    hash.each do |k,v|
      newhash[k]=v if newhash[k].nil?
    end
    newhash
  end
end

Any help would be greatly appreciated. Thanks!

Body:
The line your misunderstanding is a ternary, but the order of operations aren't what you're expecting. When Ruby sees:

newhash[k]=hash[k] ? prc.call(k,v,hash[k]): v

it views it as

newhash[k]= (hash[k] ? prc.call(k,v,hash[k]): v)

So, if hash[k] is a truth-y value, call the proc and assign the result to newhash[k]; otherwise, assign v to newhash[k].

You can see that this is how Ruby views this line by looking at the Operator Precedence file, which has (among a bunch of other operators):

?, :

modifier-rescue

=, +=, -=, etc.

So the ternary is higher precedence than the assignment operators.

It's also worth noting that newhash[k] = hash[k] is, in Ruby, a true/false statement, since assignment returns what was assigned:

a = 1 # => 1
a = nil # => nil

and everything except for false and nil in Ruby are seen as a truth-y value, you can do stuff like:

if a = 2
  puts "truthy"
end
# outputs 'truthy'

and

if a = nil
  puts "truthy"
end
# outputs nothing

and with proper parenthesizing, you can use it in a ternary:

(a = 1) ? 'truthy' : 'falsey' # => 'truthy'
(a = nil) ? 'truthy' : 'falsey' # => 'falsey'

Though, this can be confusing (usually in a conditional you'd see == not =, and in fact my Ruby gives me a warning that I'm using the = instead of == in a conditional); but it can be done


问:
Using Angular and Ionic, how can I add elements to the DOM on a button click
I'm working on an app using Ionic and Angular and would like the user to add input fields as they need. All tutorials I see on this topic are using Angular 1.x and I'm using Angular 4.

Here is the HTML:

```<code><ion-content>

    <ion-row id="row" ng-repeat= "emailinput of emailinputs">
      <ion-col col-3 id="label">
        Email
      </ion-col>
      <ion-col col-8 id="emailcol">
        <input type="email" id="email" placeholder="jdoe@gmail.com" (keyup.enter)="Send($event.target.value)" [(ngModel)]="emailinput">
      </ion-col>
    </ion-row>

  <div padding>
    <button (click) = "addnewemail(emailinput)" id="register" ion-button full color="nudgetprim" block>Add</button>
    <button (click) = "sendinvite(emailVal)" id="register" ion-button full color="nudgetprim" block>Invite</button>
  </div>

</ion-content>
</code>```

The Typescript for the button is:

```<code>addnewemail(emailinput) {
    console.log(emailinput)
    var emailinputs = [];

    var newItem = emailinputs.length+1;
    emailinputs.push({'id' : 'row' + newItem, 'name' : 'row' + newItem});
}
</code>```

答:
This is what it should look like if I am interpreting what you want correctly. Your id and name attributes of an emailinput don't need to be there unless you have some use for them somewhere else.

```<code><ion-content>

  <ion-item id="row" *ngFor="let emailinput of emailinputs ; let i = index">
    <ion-label>
      Email
    </ion-label>
    <ion-input type="email" id="email{{i}}" placeholder="jdoe@gmail.com" (keyup.enter)="Send($event.target.value)" [(ngModel)]="emailinput.email"></ion-input>
  </ion-item>

  <div padding>
    <button (click) = "addnewemail()" id="register" ion-button full color="nudgetprim" block>Add</button>
    <button (click) = "sendinvite(emailVal)" id="sendinvite" ion-button full color="nudgetprim" block>Invite</button>
  </div>

</ion-content>
</code>```

```<code>emailinputs = [{'id' : 'row0', 'name' : 'row0', 'email': ''}];

...

constructor(...

...

addnewemail() {
    let newItem = this.emailinputs.length;
    this.emailinputs.push({'id' : 'row' + newItem, 'name' : 'row' + newItem, 'email': ''});
}
</code>```

Body:
I'm working on an app using Ionic and Angular and would like the user to add input fields as they need. All tutorials I see on this topic are using Angular 1.x and I'm using Angular 4.

Here is the HTML:

<ion-content>

    <ion-row id="row" ng-repeat= "emailinput of emailinputs">
      <ion-col col-3 id="label">
        Email
      </ion-col>
      <ion-col col-8 id="emailcol">
        <input type="email" id="email" placeholder="jdoe@gmail.com" (keyup.enter)="Send($event.target.value)" [(ngModel)]="emailinput">
      </ion-col>
    </ion-row>

    <button (click) = "addnewemail(emailinput)" id="register" ion-button full color="nudgetprim" block>Add</button>
    <button (click) = "sendinvite(emailVal)" id="register" ion-button full color="nudgetprim" block>Invite</button>

</ion-content>

The Typescript for the button is:

addnewemail(emailinput) {
    console.log(emailinput)
    var emailinputs = [];

    var newItem = emailinputs.length+1;
    emailinputs.push({'id' : 'row' + newItem, 'name' : 'row' + newItem});
}

Body:
This is what it should look like if I am interpreting what you want correctly. Your id and name attributes of an emailinput don't need to be there unless you have some use for them somewhere else.

<ion-content>

  <ion-item id="row" *ngFor="let emailinput of emailinputs ; let i = index">
    <ion-label>
      Email
    </ion-label>
    <ion-input type="email" id="email{{i}}" placeholder="jdoe@gmail.com" (keyup.enter)="Send($event.target.value)" [(ngModel)]="emailinput.email"></ion-input>
  </ion-item>

  <div padding>
    <button (click) = "addnewemail()" id="register" ion-button full color="nudgetprim" block>Add</button>
    <button (click) = "sendinvite(emailVal)" id="sendinvite" ion-button full color="nudgetprim" block>Invite</button>
  </div>

</ion-content>

emailinputs = [{'id' : 'row0', 'name' : 'row0', 'email': ''}];

...

constructor(...

...

addnewemail() {
    let newItem = this.emailinputs.length;
    this.emailinputs.push({'id' : 'row' + newItem, 'name' : 'row' + newItem, 'email': ''});
}


问:
Custom widget throws a NullPointerException on setRequestedViewSize
Good morning folks,

I'm working on an Android app and I've run into a bit of a problem. I have created a new class that extends View.  I have overridden the appropriate methods (the Constructor, onDraw, onMeasure) and am instantiating the View through the applications layout XML (which is called main.xml).

Within the source code of my app I have the following code:

```<code>public class CustomViewTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

/* I *think* I need to setContentView before I actually can use any of the widgets on the form. */
        setContentView(R.layout.main);
        Button b = (Button)findViewById(R.id.button);

        b.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
// my new widget
newWidget s = (newWidget)findViewById(R.id.testWidget);
s.setRequestedViewSize(300);
   }

        });

    }
}
</code>```

the problem here, is that s.setRequestedViewSize(300) throws a NullPointerException. Has anyone run into this before or can lend me some advice?

[EDIT]
The main.XML looks like this:

It returning null, but the XML looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <com.testing.CustomViewTest02.newWidget
        android:id="@+id/testWidget"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            ></Button>
</LinearLayout>
</code>```

Thanks you!
Sam

答:
Do you reference your custom view inside your main.xml? @Pontus is right. There is no View being returned from the findViewById() method.

It would probably be better to get your reference to it in the onCreate method (call the constructor there if necessary) and then set it visible or add it to another view (whatever you are trying to do with it) once the button is clicked.

EDIT: Based on your XML above. Does your custom class implement a constructor that takes a Context and an AttributeSet? The constructor with the AttributeSet is the constructor that Android will call to create your class from the XML layout.

Body:
Good morning folks,

I'm working on an Android app and I've run into a bit of a problem. I have created a new class that extends View.  I have overridden the appropriate methods (the Constructor, onDraw, onMeasure) and am instantiating the View through the applications layout XML (which is called main.xml).

Within the source code of my app I have the following code:

public class CustomViewTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

/* I *think* I need to setContentView before I actually can use any of the widgets on the form. */
        setContentView(R.layout.main);
        Button b = (Button)findViewById(R.id.button);

        b.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
// my new widget
newWidget s = (newWidget)findViewById(R.id.testWidget);
s.setRequestedViewSize(300);
   }

        });

    }
}

the problem here, is that s.setRequestedViewSize(300) throws a NullPointerException. Has anyone run into this before or can lend me some advice?

[EDIT]
The main.XML looks like this:

It returning null, but the XML looks like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <com.testing.CustomViewTest02.newWidget
        android:id="@+id/testWidget"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            ></Button>
</LinearLayout>

Thanks you!
Sam


问:
Summing the child nodes in an XML using oracle sql
I have XML in the following format

```<code><Receive
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Date>20171106</Date>
    <ReceiptDetails>
        <ReceiptDetail>
            <Quantity>3</Quantity>
        </ReceiptDetail>
        <ReceiptDetail>
            <Quantity>2</Quantity>
        </ReceiptDetail>
        <ReceiptDetail>
            <Quantity>1</Quantity>
        </ReceiptDetail>
        <ReceiptDetail>
            <Quantity>4</Quantity>
        </ReceiptDetail>
    </ReceiptDetails>
</Receive>
</code>```

Now I want a query Oracle SQL query which returns me the sum of the Quantities Node.

I wrote a query which is concatenating the values.

```<code>SELECT
 XMLTYPE(t.REQ_MSG).EXTRACT('//Receive/ReceiptDetails/ReceiptDetail/Quantity/text()').getStringVal()
FROM
   TABLE_NAME t;
</code>```

This Gives me 3214 which is the Concatenated value but I want 10 which is the Sum.

答:
Consider parsing XML node into a column using XMLTABLE and then aggregate in outer query.

SELECT  SUM(e.Quantity) AS SumQuantity

FROM  XMLTABLE('/Receive/ReceiptDetails/ReceiptDetail'
      PASSING XMLTYPE('<Receive xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                            <Date>20171106</Date>
                            <ReceiptDetails>
                                <ReceiptDetail>
                                    <Quantity>3</Quantity>
                                </ReceiptDetail>
                                <ReceiptDetail>
                                    <Quantity>2</Quantity>
                                </ReceiptDetail>
                                <ReceiptDetail>
                                    <Quantity>1</Quantity>
                                </ReceiptDetail>
                                <ReceiptDetail>
                                    <Quantity>4</Quantity>
                                </ReceiptDetail>
                            </ReceiptDetails>
                        </Receive>')
       COLUMNS
        Quantity NUMBER PATH 'Quantity') as e
```

<p>And for the XML column in a table</p>

<pre class="lang-sql prettyprint-override"><code>SELECT  SUM(e.Quantity) AS SumQuantity

FROM  MY_TABLE,
      XMLTABLE('/Receive/ReceiptDetails/ReceiptDetail'
      PASSING XMLTYPE(MY_TABLE.MY_XML_COLUMN)

      COLUMNS
        Quantity NUMBER PATH 'Quantity') as e
</code>```

Rextester Demo

Body:
I have XML in the following format

<Receive
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Date>20171106</Date>
    <ReceiptDetails>
        <ReceiptDetail>
            <Quantity>3</Quantity>
        </ReceiptDetail>
        <ReceiptDetail>
            <Quantity>2</Quantity>
        </ReceiptDetail>
        <ReceiptDetail>
            <Quantity>1</Quantity>
        </ReceiptDetail>
        <ReceiptDetail>
            <Quantity>4</Quantity>
        </ReceiptDetail>
    </ReceiptDetails>
</Receive>

Now I want a query Oracle SQL query which returns me the sum of the Quantities Node.

I wrote a query which is concatenating the values.

SELECT
 XMLTYPE(t.REQ_MSG).EXTRACT('//Receive/ReceiptDetails/ReceiptDetail/Quantity/text()').getStringVal()
FROM
   TABLE_NAME t;

This Gives me 3214 which is the Concatenated value but I want 10 which is the Sum.

Body:
Consider parsing XML node into a column using XMLTABLE and then aggregate in outer query.

SELECT  SUM(e.Quantity) AS SumQuantity

FROM  XMLTABLE('/Receive/ReceiptDetails/ReceiptDetail'
      PASSING XMLTYPE('<Receive xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                            <Date>20171106</Date>
                            <ReceiptDetails>
                                <ReceiptDetail>
                                    <Quantity>3</Quantity>
                                </ReceiptDetail>
                                <ReceiptDetail>
                                    <Quantity>2</Quantity>
                                </ReceiptDetail>
                                <ReceiptDetail>
                                    <Quantity>1</Quantity>
                                </ReceiptDetail>
                                <ReceiptDetail>
                                    <Quantity>4</Quantity>
                                </ReceiptDetail>
                            </ReceiptDetails>
                        </Receive>')
       COLUMNS
        Quantity NUMBER PATH 'Quantity') as e

And for the XML column in a table

SELECT  SUM(e.Quantity) AS SumQuantity

FROM  MY_TABLE,
      XMLTABLE('/Receive/ReceiptDetails/ReceiptDetail'
      PASSING XMLTYPE(MY_TABLE.MY_XML_COLUMN)

      COLUMNS
        Quantity NUMBER PATH 'Quantity') as e

Rextester Demo


问:
How can I disable the scroll bars of a page?
how to disable the scroll bars of the page.

and disable this button.

答:
This will remove your scroll bar. [I did it by accident]</p>

```<code>@media screen{
body>div#header{
position:fixed;
}
body>div#footer{
position:fixed;
} `
</code>```

Body:
This will remove your scroll bar. [I did it by accident]

@media screen{
body>div#header{
position:fixed;
}
body>div#footer{
position:fixed;
} `


问:
How can I replace multiple characters from all columns of a spark dataframe?
I have a dataframe containing multiple columns.

```<code>>>> df.take(1)
[Row(A=u'{dt:dt=string, content=Prod}', B=u'{dt:dt=string, content=Staging}')]
</code>```

I want to remove both curly braces '{' and '}' from values of column A and B of df. I know we can use:

```<code>df.withColumn('A',regexp_replace('A','//{',''))
df.withColumn('A',regexp_replace('A','//}',''))
df.withColumn('B',regexp_replace('B','//}',''))
</code>```

How do I replace characters dynamically for all columns of Spark dataframe? (Pandas version is shown below)

```<code>df = df.replace({'{':'','}':''},regex=True)
</code>```

答:
Just use proper regular expression:</p>

```<code>df.withColumn("A", regexp_replace("A", "[{}]", ""))
</code>```

Body:
I have a dataframe containing multiple columns.

>>> df.take(1)
[Row(A=u'{dt:dt=string, content=Prod}', B=u'{dt:dt=string, content=Staging}')]

I want to remove both curly braces '{' and '}' from values of column A and B of df. I know we can use:

df.withColumn('A',regexp_replace('A','//{',''))
df.withColumn('A',regexp_replace('A','//}',''))
df.withColumn('B',regexp_replace('B','//}',''))

How do I replace characters dynamically for all columns of Spark dataframe? (Pandas version is shown below)

df = df.replace({'{':'','}':''},regex=True)

Body:
Just use proper regular expression:

df.withColumn("A", regexp_replace("A", "[{}]", ""))


问:
Open a deeplink while the app is already open
I am having an issue with a deeplink. If I have the app open and I repeatedly try to deeplink I can end up in a situation where the activity that should be accept the deeplink does not get started but instead the task is brought to the front. What could be causing this issue?</p>

答:
Try changing the launchMode of your activity (android:launchMode="singleInstance") in your AndroidManifest file :</p>

```<code><activity
    android:name=".YourActivity"
    android:launchMode="singleInstance" />
</code>```

Body:
Try changing the launchMode of your activity (android:launchMode="singleInstance") in your AndroidManifest file :

<activity
    android:name=".YourActivity"
    android:launchMode="singleInstance" />


问:
How do I asynchronously call fetch after data from the Firebase has been retrieved
I would like to fetch data from a URL that is stored in the Firebase database and display the data in my React Native app, I tried some tutorials on Promies and Async/Await but I can't seem to apply them to my problem here is my code:

```<code>listenForItems(itemsRef) {
    itemsRef.on('value', (snap) => {
      var items = [];
      snap.forEach((child) => {
        items.push({
          url: child.val().url,
          _key: child.key
        });
      });
      this.setState({ urls: items });
      //this.fetchData(); calling fetch here causes duplicate data
    });
    this.fetchData(); // calling fetch here does not display data
  }
</code>```

How can I asynchronously display the data using promises or async/await?

答:
You should use a boolean flag to indicate that the initial data has been loaded inside 'value'. 'value' will load all the data at once and any changes the data set will cause it to retrigger.

If you don't want it to retrigger, consider using ref.once.

```<code>var initialDataLoaded;
listenForItems(itemsRef) {
    itemsRef.on('value', (snap) => {
      var items = [];
      snap.forEach((child) => {
        items.push({
          url: child.val().url,
          _key: child.key
        });
      });
      if(!initialDataLoaded) {
         initialDataLoaded = true;
         this.setState({ urls: items });
         this.fetchData();
      }
    });
  }
</code>```

You might want to read this https://stackoverflow.com/a/27995609/1405577 comment explaining how to separate 'value' and 'child_added' listeners. And finally check out the Firebase JS SDK documentation for Reference.on

Body:
I would like to fetch data from a URL that is stored in the Firebase database and display the data in my React Native app, I tried some tutorials on Promies and Async/Await but I can't seem to apply them to my problem here is my code:

listenForItems(itemsRef) {
    itemsRef.on('value', (snap) => {
      var items = [];
      snap.forEach((child) => {
        items.push({
          url: child.val().url,
          _key: child.key
        });
      });
      this.setState({ urls: items });
      //this.fetchData(); calling fetch here causes duplicate data
    });
    this.fetchData(); // calling fetch here does not display data
  }

How can I asynchronously display the data using promises or async/await?

Body:
You should use a boolean flag to indicate that the initial data has been loaded inside 'value'. 'value' will load all the data at once and any changes the data set will cause it to retrigger.

If you don't want it to retrigger, consider using ref.once.

var initialDataLoaded;
listenForItems(itemsRef) {
    itemsRef.on('value', (snap) => {
      var items = [];
      snap.forEach((child) => {
        items.push({
          url: child.val().url,
          _key: child.key
        });
      });
      if(!initialDataLoaded) {
         initialDataLoaded = true;
         this.setState({ urls: items });
         this.fetchData();
      }
    });
  }

You might want to read this https://stackoverflow.com/a/27995609/1405577 comment explaining how to separate 'value' and 'child_added' listeners. And finally check out the Firebase JS SDK documentation for Reference.on


问:
Shuffling array in multiple threads
I have an array of size N. I want to shuffle its elements in 2 threads (or more). Each thread should work with it's own part of the array.

Lets say, the first thread shuffles elements from 0 to K, and the second thread shuffles elements from K to N (where 0 < K < N). So, it can look like this:

```<code>//try-catch stuff is ommited
static void shuffle(int[] array) {
   Thread t1 = new ShufflingThread(array, 0, array.length / 2);
   Thread t2 = new ShufflingThread(array, array.length / 2, array.length);
   t1.start();
   t2.start();
   t1.join();
   t2.join();
}

public static void main(String[] args) {
   int array = generateBigSortedArray();
   shuffle(array);
}
</code>```

Are there any guaranties from JVM that I will see changes in the array from the main method after such shuffling?

How should I implement ShufflingThread (or, how should I run it, maybe within a synchronized block or whatever else) in order to get such guaranties?

答: using ExecutorService from java.util.Concurrent package  along with Callable Task to return the part of the array's  from each thread run, once both thread are completed is another way to do for consistent behaviour.</p>

Title: Shuffling array in multiple threads

Body:
I have an array of size N. I want to shuffle its elements in 2 threads (or more). Each thread should work with it's own part of the array.

Lets say, the first thread shuffles elements from 0 to K, and the second thread shuffles elements from K to N (where 0 < K < N). So, it can look like this:

//try-catch stuff is ommited
static void shuffle(int[] array) {
   Thread t1 = new ShufflingThread(array, 0, array.length / 2);
   Thread t2 = new ShufflingThread(array, array.length / 2, array.length);
   t1.start();
   t2.start();
   t1.join();
   t2.join();
}

public static void main(String[] args) {
   int array = generateBigSortedArray();
   shuffle(array);
}

Are there any guaranties from JVM that I will see changes in the array from the main method after such shuffling?

How should I implement ShufflingThread (or, how should I run it, maybe within a synchronized block or whatever else) in order to get such guaranties?


问:
How to append multiple items to a force simulation node?
I'm using D3 v4 and can't seem to get multiple items to append to a node. In the code below I'm trying to get text to appear with the image as part of my force simulation. Both the image and text need to move together around the screen. It works perfectly if I only append either the image or the text but I can't get it to group both. When I run this it just shows 1 node in the corner.</p>

```<code>this.node = this.d3Graph.append("g")
    .attr("class", "nodes")
    .selectAll("circle")
    .data(Nodes)
    .enter()
    .append("svg:image")
    .attr("xlink:href", 'https://seeklogo.com/images/T/twitter-2012-negative-logo-5C6C1F1521-seeklogo.com.png')
    .attr("height", 50)
    .attr("width", 50)
    .append("text")
    .attr("x", 20)
    .attr("y", 20)
    .attr("fill", "black")
    .text("test text");

this.force.on('tick', this.tickActions);

tickActions() {
    this.node
        .attr("transform", function(d) {
            return "translate(" + d.x + "," + d.y + ")";
        })

    this.force
        .restart()
}
</code>```

答:
You cannot append a <text> element to an <image> element. You have to append the <text> to the <g>.

The easiest solution is breaking your selection:

```<code>this.node = this.d3Graph.selectAll(null)
    .data(Nodes)
    .enter()
    .append("g")
    .attr("class", "nodes");

this.node.append("svg:image")
    .attr("xlink:href", 'https://seeklogo.com/images/T/twitter-2012-negative-logo-5C6C1F1521-seeklogo.com.png')
    .attr("height", 50)
    .attr("width", 50);

this.node.append("text")
    .attr("x", 20)
    .attr("y", 20)
    .attr("fill", "black")
    .text("test text");
</code>```

Here we use the data to create <g> elements in the enter selection. Then, to each <g> element, we append an <image> and a <text> as children.

Body:
I'm using D3 v4 and can't seem to get multiple items to append to a node. In the code below I'm trying to get text to appear with the image as part of my force simulation. Both the image and text need to move together around the screen. It works perfectly if I only append either the image or the text but I can't get it to group both. When I run this it just shows 1 node in the corner.

this.node = this.d3Graph.append("g")
    .attr("class", "nodes")
    .selectAll("circle")
    .data(Nodes)
    .enter()
    .append("svg:image")
    .attr("xlink:href", 'https://seeklogo.com/images/T/twitter-2012-negative-logo-5C6C1F1521-seeklogo.com.png')
    .attr("height", 50)
    .attr("width", 50)
    .append("text")
    .attr("x", 20)
    .attr("y", 20)
    .attr("fill", "black")
    .text("test text");

this.force.on('tick', this.tickActions);

tickActions() {
    this.node
        .attr("transform", function(d) {
            return "translate(" + d.x + "," + d.y + ")";
        })

    this.force
        .restart()
}

Body:
You cannot append a <text> element to an <image> element. You have to append the <text> to the <g>.

The easiest solution is breaking your selection:

this.node = this.d3Graph.selectAll(null)
    .data(Nodes)
    .enter()
    .append("g")
    .attr("class", "nodes");

this.node.append("svg:image")
    .attr("xlink:href", 'https://seeklogo.com/images/T/twitter-2012-negative-logo-5C6C1F1521-seeklogo.com.png')
    .attr("height", 50)
    .attr("width", 50);

this.node.append("text")
    .attr("x", 20)
    .attr("y", 20)
    .attr("fill", "black")
    .text("test text");

Here we use the data to create <g> elements in the enter selection. Then, to each <g> element, we append an <image> and a <text> as children.


问:
Using Auth0 to authenticate against multiple resources with a single application login
My app is authenticated using Auth0. The user enters their username + password and Auth0 gives back a token which my app uses to call my backend.

My app also uses 3rd party applications behind the scenes, and those 3rd party applications all have their own authentication. When a user logs in to my application, it needs to go out and get authentication tokens for all these 3rd party apps as well.

For example, my app needs to use an API on Watson which is authenticated using a different username + password. The user can’t know what that username + password are. Instead, they are ‘known’ by my app, which uses them to login to Watson and get an auth token to make the API calls.

That Watson API isn’t the only 3rd party API my app needs to use.  The 3rd party APIs all have their own authentication schemes. Some use a username + password, others use an App ID and Secret, etc. But in all of these cases, the authentication credentials are owned and managed by my application - not by the user of my application.

So the question is, how can I use Auth0 to automatically go out and get all these 3rd party authentication tokens when the user logs in to my app?

答: Once Auth0 authentication token is authenticated then pass your watson API in the initialisation event, using the API profile module get the token of your watson API. Hope it will give some idea. </p>


问:
address error when send email with 32bit outlook using automation
NOTE: edited from original after I discovered the outlook version was 32-bit not 64-bit.

I have a legacy 32-bit VB6 program that uses outlook 2010 32bit (full version, not express) to send email.  Works perfect on many machines except one machine with windows 7 (64-bit I assume).  Not sure if all windows 7 machines don't work or just this one.

If I use the automation technique or the MAPI technique (as I call them, see code below) outlook sends the email but the mail server kicks it back as undeliverable saying the recipient does not exist.

Now if the automation technique is used outlook displays no UI and the email is sent in the background.

However if the MAPI technique is used outlook opens it's compose email dialog which allows the user to edit the email prior to sending.  What is interesting is that the recipient email looks fine but will fail as undeliverable if sent. However if the recipient is deleted and re-typed then the email will succeed.  I believe a copy and re-paste works also.

This tells me there must be one or more hidden illegal characters in the recipient email address (nulls perhaps?).  The code to do this shown below is very plain and I can't think of any obvious fix. txtTo is a vb6 string with an email address and this is the field that is causing all the problems.

The error message:

```<code>  Your message did not reach some or all of the intended recipients.

  Subject:  a test from daryls cpu #2
  Sent: 11/17/2017 8:01 PM

  The following recipient(s) cannot be reached:

  'someemail@gmail.com' on 11/17/2017 8:01 PM
        None of your e-mail accounts could send to this recipient.
</code>```

Automation Technique

```<code>        Dim mOutlookApp As Object
        Set mOutlookApp = GetObject("", "Outlook.application")

        Dim olNs As Object
        Set olNs = mOutlookApp.GetNamespace("MAPI")
        olNs.Logon

        Dim OutMail As Object
        Set OutMail = mOutlookApp.CreateItem(0)

        'Set the To and Subject lines.  Send the message.
        With OutMail
            .To = txtTo
            .CC = txtCC
            .Subject = txtSubjext
            .HTMLBody = txtBody & vbCrLf

            Dim myAttachments As Object
            Set myAttachments = .Attachments
            vAttach = Split(mAttachments, ",")
            For i = 0 To UBound(vAttach)
                myAttachments.add vAttach(i)
            Next i

            Dim myFolder As Object
            Set myFolder = olNs.GetDefaultFolder(5) 'olFolderSent
            Set .SaveSentMessageFolder = myFolder

            StatusBar1.Panels(1).Text = "Status: Sending"

            .send
        End With
</code>```

MAPI Technique

```<code>    'Open up a MAPI session:
    With frmMain.MAPISession1
        .DownLoadMail = False
        .Username = ""
        .LogonUI = True
        .SignOn
    End With

    With frmMain.MAPIMessages1
        .SessionID = frmMain.MAPISession1.SessionID
        .Compose
        .MsgIndex = -1

        .RecipIndex = 0
        .RecipAddress = txtTo
        .RecipDisplayName = txtTo
        .RecipType = mapToList

        If txtCC <> "" Then
            .RecipIndex = 1
            .RecipDisplayName = txtCC
            .RecipAddress = txtCC
            .RecipType = mapCcList
        End If

        'spaces are important! need one space for each attachment
        'NOTE .MsgNoteText = " " MUST be there see.. KB173853 in microsoft

        .MsgSubject = txtSubjext

        .MsgNoteText = Space$(UBound(vAttach) + 1) & vbCrLf
        .MsgNoteText = txtBody & vbCrLf

        For i = 0 To UBound(vAttach)
            .AttachmentIndex = i
            .AttachmentPosition = i
            .AttachmentType = mapData
            .AttachmentName = GetFileFromPath(vAttach(i))
            .AttachmentPathName = vAttach(i)
        Next i

        StatusBar1.Panels(1).Text = "Status: Sending"

        .send True

    End With
</code>```

More Info:

I'm making some progress.  The error has to do with email type in outlook not being SMTP.  If on the send-to email in the outlook compose dialog you right-click on the email address then select outlook properties and change the email type to SMTP it will work.  The type displayed is the email address itself, valid values seem to be 'mailto' and 'smtp'.  So if I can set the email type from vb6 it should fix the error.

The 'Answer'?  https://kb.intermedia.net/article/2344

I can't believe there is no fix for this...

答:
RESOLVED!

I realize this topic is most likely of no interest to anyone programming in the 20th century but here is the fix:

```<code>.RecipAddress = "SMTP:" & txtTo
</code>```

It just came to me. :)

Body:
NOTE: edited from original after I discovered the outlook version was 32-bit not 64-bit.

I have a legacy 32-bit VB6 program that uses outlook 2010 32bit (full version, not express) to send email.  Works perfect on many machines except one machine with windows 7 (64-bit I assume).  Not sure if all windows 7 machines don't work or just this one.

If I use the automation technique or the MAPI technique (as I call them, see code below) outlook sends the email but the mail server kicks it back as undeliverable saying the recipient does not exist.

Now if the automation technique is used outlook displays no UI and the email is sent in the background.

However if the MAPI technique is used outlook opens it's compose email dialog which allows the user to edit the email prior to sending.  What is interesting is that the recipient email looks fine but will fail as undeliverable if sent. However if the recipient is deleted and re-typed then the email will succeed.  I believe a copy and re-paste works also.

This tells me there must be one or more hidden illegal characters in the recipient email address (nulls perhaps?).  The code to do this shown below is very plain and I can't think of any obvious fix. txtTo is a vb6 string with an email address and this is the field that is causing all the problems.

The error message:

  Your message did not reach some or all of the intended recipients.

  Subject:  a test from daryls cpu #2
  Sent: 11/17/2017 8:01 PM

  The following recipient(s) cannot be reached:

  'someemail@gmail.com' on 11/17/2017 8:01 PM
        None of your e-mail accounts could send to this recipient.

Automation Technique

        Dim mOutlookApp As Object
        Set mOutlookApp = GetObject("", "Outlook.application")

        Dim olNs As Object
        Set olNs = mOutlookApp.GetNamespace("MAPI")
        olNs.Logon

        Dim OutMail As Object
        Set OutMail = mOutlookApp.CreateItem(0)

        'Set the To and Subject lines.  Send the message.
        With OutMail
            .To = txtTo
            .CC = txtCC
            .Subject = txtSubjext
            .HTMLBody = txtBody & vbCrLf

            Dim myAttachments As Object
            Set myAttachments = .Attachments
            vAttach = Split(mAttachments, ",")
            For i = 0 To UBound(vAttach)
                myAttachments.add vAttach(i)
            Next i

            Dim myFolder As Object
            Set myFolder = olNs.GetDefaultFolder(5) 'olFolderSent
            Set .SaveSentMessageFolder = myFolder

            StatusBar1.Panels(1).Text = "Status: Sending"

            .send
        End With

MAPI Technique

    'Open up a MAPI session:
    With frmMain.MAPISession1
        .DownLoadMail = False
        .Username = ""
        .LogonUI = True
        .SignOn
    End With

    With frmMain.MAPIMessages1
        .SessionID = frmMain.MAPISession1.SessionID
        .Compose
        .MsgIndex = -1

        .RecipIndex = 0
        .RecipAddress = txtTo
        .RecipDisplayName = txtTo
        .RecipType = mapToList

        If txtCC <> "" Then
            .RecipIndex = 1
            .RecipDisplayName = txtCC
            .RecipAddress = txtCC
            .RecipType = mapCcList
        End If

        'spaces are important! need one space for each attachment
        'NOTE .MsgNoteText = " " MUST be there see.. KB173853 in microsoft

        .MsgSubject = txtSubjext

        .MsgNoteText = Space$(UBound(vAttach) + 1) & vbCrLf
        .MsgNoteText = txtBody & vbCrLf

        For i = 0 To UBound(vAttach)
            .AttachmentIndex = i
            .AttachmentPosition = i
            .AttachmentType = mapData
            .AttachmentName = GetFileFromPath(vAttach(i))
            .AttachmentPathName = vAttach(i)
        Next i

        StatusBar1.Panels(1).Text = "Status: Sending"

        .send True

    End With

More Info:

I'm making some progress.  The error has to do with email type in outlook not being SMTP.  If on the send-to email in the outlook compose dialog you right-click on the email address then select outlook properties and change the email type to SMTP it will work.  The type displayed is the email address itself, valid values seem to be 'mailto' and 'smtp'.  So if I can set the email type from vb6 it should fix the error.

The 'Answer'?  https://kb.intermedia.net/article/2344

I can't believe there is no fix for this...

Body:
RESOLVED!

I realize this topic is most likely of no interest to anyone programming in the 20th century but here is the fix:

.RecipAddress = "SMTP:" & txtTo

It just came to me. :)


问:
Using Formula Language to return column values
I'm trying to return all values stored in the tNames variable.

Values exists in the field. The show multivalues as separate entries have been selected already but none of the names is returned.

Below is the sample code:

```<code>tNames := "";
@For(n := 0; n <= QuestionCount - 1; n := n + 1;
tNames := tNames + ", " + @Implode(@GetField("ChecklistContact_" +
  @Text(n));",")
);
@Trim(tNames)
</code>```

I dont know why its not returning anything, will appreciate your help.

The below returns only the contact with index 0, but I want to return all contacts in each document.

```<code>tCount := 0;
@For(n := 0; n <= QuestionCount - 1; n := n + 1;
 tCount := tCount + @If(@GetField("ChecklistContact_" + @Text(n)) = ""; 0; 1)
);
@GetField("ChecklistContact_" + @Text(tCount))
</code>```

Following comments from Richard the below return the required values, but will prefer not to hard code field name.

Is there any way of using for loop to return field names and values?

```<code>tNames := "";
tNames:= @GetField("ChecklistContact_1") : @GetField("ChecklistContact_2") : ... @GetField("ChecklistContact_7");
@Trim(tNames)
</code>```

答:
I don't believe that IBM's documentation says this explicitly, but I don't think @GetField works in column value formulas. The doc says that it works in the "current document", and there is no current document when the formula is executing in a view.

Assuming you know what the maximum number for N is, the way to do this is with a simple list:

```<code>ChecklistContact_1 : ChecklistContact_2 : ChecklistContact_3 : ... : ChecklistContact_N
</code>```

If N is large, this will be a lot of typing, but you'll only have to do it once and copying and pasting and editing the numbers will make it go pretty quickly.

Body:
I'm trying to return all values stored in the tNames variable.

Values exists in the field. The show multivalues as separate entries have been selected already but none of the names is returned.

Below is the sample code:

tNames := "";
@For(n := 0; n <= QuestionCount - 1; n := n + 1;
tNames := tNames + ", " + @Implode(@GetField("ChecklistContact_" +
  @Text(n));",")
);
@Trim(tNames)

I dont know why its not returning anything, will appreciate your help.

The below returns only the contact with index 0, but I want to return all contacts in each document.

tCount := 0;
@For(n := 0; n <= QuestionCount - 1; n := n + 1;
 tCount := tCount + @If(@GetField("ChecklistContact_" + @Text(n)) = ""; 0; 1)
);
@GetField("ChecklistContact_" + @Text(tCount))

Following comments from Richard the below return the required values, but will prefer not to hard code field name.

Is there any way of using for loop to return field names and values?

tNames := "";
tNames:= @GetField("ChecklistContact_1") : @GetField("ChecklistContact_2") : ... @GetField("ChecklistContact_7");
@Trim(tNames)

Body:
I don't believe that IBM's documentation says this explicitly, but I don't think @GetField works in column value formulas. The doc says that it works in the "current document", and there is no current document when the formula is executing in a view.

Assuming you know what the maximum number for N is, the way to do this is with a simple list:

ChecklistContact_1 : ChecklistContact_2 : ChecklistContact_3 : ... : ChecklistContact_N

If N is large, this will be a lot of typing, but you'll only have to do it once and copying and pasting and editing the numbers will make it go pretty quickly.


问:
What exactly is a reference variable in Java? How does it differ from other variables?
I have been studying Inheritance in Java and the writer makes the statement "it is the type of object being referred to (not the type of reference variable) that determines which version of an overridden method will be executed."
This statement is awfully confusing.</p>

答:
A reference variable is the type you specify on the left hand side (a variable that holds a reference type). What the author is referring to is when the right hand side then differs. Consider

```<code>Object a = new Foo();
System.out.println(a.toString());
</code>```

if Foo overrides the Object.toString() (that is, if Foo provides a public String toString()) method then it is Foo's toString that is invoked (not Object's). See also Overriding and Hiding Methods in the Java tutorials.

Body:
A reference variable is the type you specify on the left hand side (a variable that holds a reference type). What the author is referring to is when the right hand side then differs. Consider

Object a = new Foo();
System.out.println(a.toString());

if Foo overrides the Object.toString() (that is, if Foo provides a public String toString()) method then it is Foo's toString that is invoked (not Object's). See also Overriding and Hiding Methods in the Java tutorials.


问:
Any way to fetch hyperlink of a column to another column on google spreadsheet?
I copy a list of company name from a website, each of them has its hyperlink.

But now I would like to paste the names on column B of a google spreadsheet and the link list on column C.

the sample spreadsheet shows here

Column B shows name and column C shows its link like http://.....

The =HYPERLINK function syntax are as followed

HYPERLINK(url, [link_label])

Is there any way I can make the [link_label] become link url itself?

Or is there any other way to list all the hyperlink of a sheet on a column?

答:
The square brackets in a Google function indicate that the parameter is optional. HYPERLINK defaults to display the link itself if the [link_label] is omitted.

In other words, =HYPERLINK("www.example.com") will display as www.example.com.

See Google's documentation.